Skip to content

Commit

Permalink
Merge pull request #6 from EEKIM10/discord-py-free
Browse files Browse the repository at this point in the history
Remove dependency on discord.py
  • Loading branch information
nexy7574 authored Jun 11, 2022
2 parents 8ce3814 + ef1661f commit f616323
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 52 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ jobs:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade wheel pip pycodestyle pytest discord.py>=1.5.0
python -m pip install --upgrade wheel pip pycodestyle pytest discord.py>=1.7 pytest-asyncio
- name: Lint with pycodestyle
run: |
pycodestyle ./toppy --config ./tox.ini
pycodestyle ./toppy --max-line-length 130
- name: Test with pytest
run: |
pytest
2 changes: 1 addition & 1 deletion .readthedocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ formats:

# Optionally set the version of Python and requirements required to build your docs
python:
version: "3.7"
version: "3.8"
install:
- requirements: docs/requirements.txt
2 changes: 1 addition & 1 deletion docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
discord.py>=1.5.0
discord.py>=1.7.0
sphinx_rtd_theme
8 changes: 7 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
build-backend = "setuptools.build_meta"

[tool.black]
line-length = 120

[tool.pytest.ini_options]
asyncio_mode = "auto"
11 changes: 8 additions & 3 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ classifiers =
[options]
packages = find:
python_requires = >=3.6
install_requires =
discord.py >= 1.5.0

[options.packages.find]
exclude = tests
Expand All @@ -40,4 +38,11 @@ exclude = tests
tests = pytest
docs =
sphinx
sphinx-rtd-dark-mode
sphinx-rtd-dark-mode

[pycodestyle]
count = True
max-line-length = 130
max-doc-length = 160
statistics = True
exclude=venv
11 changes: 5 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
from re import compile
from warnings import warn

from setuptools import setup, find_packages
from setuptools import find_packages
from setuptools import setup

warn(
DeprecationWarning("The setup.py install for this project is deprecated.")
)
warn(DeprecationWarning("The setup.py install for this project is deprecated."))

chdir(Path(__file__).parent)

version_regex = compile(r"__version__ = \"(?P<v>[0-9]\.[0-9]{1,2}\.[0-9]+)((a|b|(r)?c)[0-9]+)?\"")
version_regex = compile(r"__version__ = \"(?P<v>\d\.\d{1,2}\.\d+)((a|b|(r)?c)\d+)?\"")

reqs = ["discord.py>=1.5.0"]
reqs = []

with open("./README.md", encoding="utf-8") as readme_file:
readme = readme_file.read()
Expand Down
7 changes: 2 additions & 5 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,5 @@ def test_import_server():

def test_init_client():
from toppy.client import TopGG
TopGG(
None,
token="hi",
autopost=False
)

TopGG(None, token="hi", autopost=False)
28 changes: 15 additions & 13 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from toppy.server import _create_callback, Vote

pytest_plugins = ("pytest_asyncio",)


POST_DATA = {
"bot": "619328560141697036",
Expand All @@ -27,39 +29,39 @@ class FakeRequest:
headers = {"Authorization": "foobar"}
remote = "127.0.0.1"

def __init__(self, new_data=POST_DATA):
def __init__(self, new_data=None):
if new_data is None:
new_data = POST_DATA
self.data = new_data

async def json(self):
return self.data


def test_vote_server():
@pytest.mark.asyncio
async def test_vote_server():
sponge = Sponge()
loop = asyncio.get_event_loop()

cb = _create_callback(sponge, "foobar")
response = loop.run_until_complete(cb(FakeRequest()))
response = await cb(FakeRequest())
assert response.status == 200


def test_vote_server_broken_creds():
@pytest.mark.asyncio
async def test_vote_server_broken_creds():
sponge = Sponge()
loop = asyncio.get_event_loop()

cb = _create_callback(sponge, "foobarbazz")
response: Response = loop.run_until_complete(cb(FakeRequest()))
response: Response = await cb(FakeRequest())
assert response.status == 401


def test_vote_server_broken_data():
@pytest.mark.asyncio
async def test_vote_server_broken_data():
# This is unlikely to happen in a real webhook, but we'll test that it's handled anyway
sponge = Sponge()
loop = asyncio.get_event_loop()

cb = _create_callback(sponge, "foobar")
_data = POST_DATA.copy()
for key in _data.keys():
# noinspection PyTypeChecker
_data[key] = None
response: Response = loop.run_until_complete(cb(FakeRequest(_data)))
response: Response = await cb(FakeRequest(_data))
assert response.status == 422
15 changes: 12 additions & 3 deletions toppy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
from sys import version_info as python_version_info
from discord import version_info as discord_version_info

try:
from discord import version_info as discord_version_info
except ImportError as e:
raise ImportError("A module with the 'discord' namespace is not installed.") from e
from warnings import warn

if python_version_info <= (3, 6, 0) and discord_version_info >= (1, 8, 0):
Expand All @@ -9,5 +13,10 @@
DeprecationWarning,
)

from .models import large_widget, small_widget, ColourOptions, ColourOptions as ColorOptions, Bot, User
from .client import TopGG, TopGG as Client, TopGG as DBLClient
from .client import TopGG
from .client import TopGG as Client
from .client import TopGG as DBLClient
from .models import Bot
from .models import ColourOptions
from .models import ColourOptions as ColorOptions
from .models import User, large_widget, small_widget
35 changes: 26 additions & 9 deletions toppy/client.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
import logging
from json import dumps
from typing import Union, List, Optional
from typing import List
from typing import Optional
from typing import TYPE_CHECKING
from typing import Union

import aiohttp
import discord
# noinspection PyPep8Naming
from discord import Client as C, AutoShardedClient as AC
# noinspection PyPep8Naming
from discord.ext.commands import Bot as B, AutoShardedBot as AB
from discord.ext.tasks import loop

from .errors import ToppyError, Forbidden, TopGGServerError, Ratelimited, NotFound
from .models import Bot, SimpleUser, BotStats, User, BotSearchResults
from .errors import Forbidden
from .errors import NotFound
from .errors import Ratelimited
from .errors import TopGGServerError
from .errors import ToppyError
from .models import Bot
from .models import BotSearchResults
from .models import BotStats
from .models import SimpleUser
from .models import User
from .ratelimiter import routes

# noinspection PyPep8Naming

if TYPE_CHECKING:
from discord import AutoShardedClient as _AutoClient
from discord import Client as _Client
from discord.ext.commands import AutoShardedBot as _AutoBot
from discord.ext.commands import Bot as _Bot

bot_types = Union[_Client, _AutoClient, _Bot, _AutoBot]

__version__ = "1.3.1"
__api_version__ = "v0"
_base_ = "https://top.gg/api"
Expand All @@ -28,7 +45,7 @@ class TopGG:
class.
"""

def __init__(self, bot: Union[C, B, AC, AB], *, token: str, autopost: bool = True):
def __init__(self, bot: "bot_types", *, token: str, autopost: bool = True):
r"""
Initialises an instance of the top.gg client. Please don't call this multiple times, it WILL break stuff.
Expand Down Expand Up @@ -153,7 +170,7 @@ async def _request(self, method: str, uri: str, **kwargs) -> dict:
routes["*"].add_hit()

if "application/json" not in response.headers.get("content-type", "none").lower():
logger.warning(f"Got unexpected mime type {response.headers['Content-Type']} from top.gg.")
logger.warning(f"Got unexpected content type {response.headers['Content-Type']!r} from top.gg.")
raise ToppyError("Unexpected response from server.")
if response.status in [403, 401]:
raise Forbidden()
Expand Down
5 changes: 3 additions & 2 deletions toppy/ratelimiter/bucket.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime, timedelta
from datetime import datetime
from datetime import timedelta
from typing import Dict


Expand Down Expand Up @@ -59,6 +60,6 @@ def add_hit(self):


_routes: Dict[str, Ratelimit] = {
"*": Ratelimit(route="*", hits=100, cooldown=3600),
"/bots/*": Ratelimit(route="/bots/*", hits=60, cooldown=3600),
"*": Ratelimit(route="*", hits=100, cooldown=3600),
}
6 changes: 0 additions & 6 deletions tox.ini

This file was deleted.

0 comments on commit f616323

Please sign in to comment.