Skip to content

Commit de0aa77

Browse files
author
RealKiller666
committed
more readable
1 parent d813754 commit de0aa77

8 files changed

Lines changed: 183 additions & 145 deletions

File tree

topgg/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
__author__ = "Assanali Mukhanov"
1313
__maintainer__ = "RealKiller666"
1414
__license__ = "MIT"
15-
__version__ = "2.0.0a2"
15+
__version__ = "2.0.0a3"
1616

1717
from .autopost import *
1818
from .client import *

topgg/autopost.py

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,32 @@
2222

2323
__all__ = ["AutoPoster"]
2424

25+
from __future__ import annotations
26+
2527
import asyncio
2628
import datetime
2729
import sys
2830
import traceback
29-
import typing as t
31+
from typing import (
32+
Any,
33+
Callable,
34+
Optional,
35+
overload,
36+
TYPE_CHECKING,
37+
Union
38+
)
3039

3140
from topgg import errors
3241

3342
from .types import StatsWrapper
3443

35-
if t.TYPE_CHECKING:
44+
if TYPE_CHECKING:
3645
import asyncio
3746

3847
from .client import DBLClient
3948

40-
CallbackT = t.Callable[..., t.Any]
41-
StatsCallbackT = t.Callable[[], StatsWrapper]
49+
CallbackT = Callable[..., Any]
50+
StatsCallbackT = Callable[[], StatsWrapper]
4251

4352

4453
class AutoPoster:
@@ -67,9 +76,9 @@ class AutoPoster:
6776
_success: CallbackT
6877
_stats: CallbackT
6978
_interval: float
70-
_task: t.Optional["asyncio.Task[None]"]
79+
_task: Optional[asyncio.Task[None]]
7180

72-
def __init__(self, client: "DBLClient") -> None:
81+
def __init__(self, client: DBLClient) -> None:
7382
super().__init__()
7483
self.client = client
7584
self._interval: float = 900
@@ -82,15 +91,15 @@ def _default_error_handler(self, exception: Exception) -> None:
8291
type(exception), exception, exception.__traceback__, file=sys.stderr
8392
)
8493

85-
@t.overload
86-
def on_success(self, callback: None) -> t.Callable[[CallbackT], CallbackT]:
94+
@overload
95+
def on_success(self, callback: None) -> Callable[[CallbackT], CallbackT]:
8796
...
8897

89-
@t.overload
90-
def on_success(self, callback: CallbackT) -> "AutoPoster":
98+
@overload
99+
def on_success(self, callback: CallbackT) -> AutoPoster:
91100
...
92101

93-
def on_success(self, callback: t.Any = None) -> t.Any:
102+
def on_success(self, callback: Any = None) -> Any:
94103
"""
95104
Registers an autopost success callback. The callback can be either sync or async.
96105
@@ -123,15 +132,15 @@ def decorator(callback: CallbackT) -> CallbackT:
123132

124133
return decorator
125134

126-
@t.overload
127-
def on_error(self, callback: None) -> t.Callable[[CallbackT], CallbackT]:
135+
@overload
136+
def on_error(self, callback: None) -> Callable[[CallbackT], CallbackT]:
128137
...
129138

130-
@t.overload
131-
def on_error(self, callback: CallbackT) -> "AutoPoster":
139+
@overload
140+
def on_error(self, callback: CallbackT) -> AutoPoster:
132141
...
133142

134-
def on_error(self, callback: t.Any = None) -> t.Any:
143+
def on_error(self, callback: Any = None) -> Any:
135144
"""
136145
Registers an autopost error callback. The callback can be either sync or async.
137146
@@ -168,15 +177,15 @@ def decorator(callback: CallbackT) -> CallbackT:
168177

169178
return decorator
170179

171-
@t.overload
172-
def stats(self, callback: None) -> t.Callable[[StatsCallbackT], StatsCallbackT]:
180+
@overload
181+
def stats(self, callback: None) -> Callable[[StatsCallbackT], StatsCallbackT]:
173182
...
174183

175-
@t.overload
176-
def stats(self, callback: StatsCallbackT) -> "AutoPoster":
184+
@overload
185+
def stats(self, callback: StatsCallbackT) -> AutoPoster:
177186
...
178187

179-
def stats(self, callback: t.Any = None) -> t.Any:
188+
def stats(self, callback: Any = None) -> Any:
180189
"""
181190
Registers a function that returns an instance of :obj:`~.types.StatsWrapper`.
182191
@@ -221,11 +230,11 @@ def interval(self) -> float:
221230
return self._interval
222231

223232
@interval.setter
224-
def interval(self, seconds: t.Union[float, datetime.timedelta]) -> None:
233+
def interval(self, seconds: Union[float, datetime.timedelta]) -> None:
225234
"""Alias to :meth:`~.autopost.AutoPoster.set_interval`."""
226235
self.set_interval(seconds)
227236

228-
def set_interval(self, seconds: t.Union[float, datetime.timedelta]) -> "AutoPoster":
237+
def set_interval(self, seconds: Union[float, datetime.timedelta]) -> AutoPoster:
229238
"""
230239
Sets the interval between posting stats.
231240
@@ -255,7 +264,7 @@ def _refresh_state(self) -> None:
255264
self._task = None
256265
self._stopping = False
257266

258-
def _fut_done_callback(self, future: "asyncio.Future") -> None:
267+
def _fut_done_callback(self, future: asyncio.Future) -> None:
259268
self._refresh_state()
260269
if future.cancelled():
261270
return
@@ -282,7 +291,7 @@ async def _internal_loop(self) -> None:
282291
finally:
283292
self._refresh_state()
284293

285-
def start(self) -> "asyncio.Task[None]":
294+
def start(self) -> asyncio.Task[None]:
286295
"""
287296
Starts the autoposting loop.
288297
@@ -331,4 +340,4 @@ def cancel(self) -> None:
331340

332341
self._task.cancel()
333342
self._refresh_state()
334-
return None
343+
return None

topgg/client.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
__all__ = ["DBLClient"]
2626

27-
import typing as t
27+
from typing import overload, Optional, Any, Union
2828

2929
import aiohttp
3030

@@ -60,17 +60,17 @@ def __init__(
6060
self,
6161
token: str,
6262
*,
63-
default_bot_id: t.Optional[int] = None,
64-
session: t.Optional[aiohttp.ClientSession] = None,
65-
**kwargs: t.Any,
63+
default_bot_id: Optional[int] = None,
64+
session: Optional[aiohttp.ClientSession] = None,
65+
**kwargs: Any,
6666
) -> None:
6767
super().__init__()
6868
self._token = token
6969
self.default_bot_id = default_bot_id
7070
self._is_closed = False
7171
if session is not None:
7272
self.http = HTTPClient(token, session=session)
73-
self._autopost: t.Optional[AutoPoster] = None
73+
self._autopost: Optional[AutoPoster] = None
7474

7575
@property
7676
def is_closed(self) -> bool:
@@ -83,7 +83,7 @@ async def _ensure_session(self) -> None:
8383
if not hasattr(self, "http"):
8484
self.http = HTTPClient(self._token, session=None)
8585

86-
def _validate_and_get_bot_id(self, bot_id: t.Optional[int]) -> int:
86+
def _validate_and_get_bot_id(self, bot_id: Optional[int]) -> int:
8787
bot_id = bot_id or self.default_bot_id
8888
if bot_id is None:
8989
raise errors.ClientException("bot_id or default_bot_id is unset.")
@@ -104,27 +104,27 @@ async def get_weekend_status(self) -> bool:
104104
data = await self.http.get_weekend_status()
105105
return data["is_weekend"]
106106

107-
@t.overload
107+
@overload
108108
async def post_guild_count(self, stats: types.StatsWrapper) -> None:
109109
...
110110

111-
@t.overload
111+
@overload
112112
async def post_guild_count(
113113
self,
114114
*,
115-
guild_count: t.Union[int, t.List[int]],
116-
shard_count: t.Optional[int] = None,
117-
shard_id: t.Optional[int] = None,
115+
guild_count: Union[int, list[int]],
116+
shard_count: Optional[int] = None,
117+
shard_id: Optional[int] = None,
118118
) -> None:
119119
...
120120

121121
async def post_guild_count(
122122
self,
123-
stats: t.Any = None,
123+
stats: Any = None,
124124
*,
125-
guild_count: t.Any = None,
126-
shard_count: t.Any = None,
127-
shard_id: t.Any = None,
125+
guild_count: Any = None,
126+
shard_count: Any = None,
127+
shard_id: Any = None,
128128
) -> None:
129129
"""Posts your bot's guild count and shards info to Top.gg.
130130
@@ -162,7 +162,7 @@ async def post_guild_count(
162162
await self.http.post_guild_count(guild_count, shard_count, shard_id)
163163

164164
async def get_guild_count(
165-
self, bot_id: t.Optional[int] = None
165+
self, bot_id: Optional[int] = None
166166
) -> types.BotStatsData:
167167
"""Gets a bot's guild count and shard info from Top.gg.
168168
@@ -185,7 +185,7 @@ async def get_guild_count(
185185
response = await self.http.get_guild_count(bot_id)
186186
return types.BotStatsData(**response)
187187

188-
async def get_bot_votes(self) -> t.List[types.BriefUserData]:
188+
async def get_bot_votes(self) -> list[types.BriefUserData]:
189189
"""Gets information about last 1000 votes for your bot on Top.gg.
190190
191191
Note:
@@ -209,7 +209,7 @@ async def get_bot_votes(self) -> t.List[types.BriefUserData]:
209209
response = await self.http.get_bot_votes(self.default_bot_id)
210210
return [types.BriefUserData(**user) for user in response]
211211

212-
async def get_bot_info(self, bot_id: t.Optional[int] = None) -> types.BotData:
212+
async def get_bot_info(self, bot_id: Optional[int] = None) -> types.BotData:
213213
"""This function is a coroutine.
214214
215215
Gets information about a bot from Top.gg.
@@ -238,10 +238,10 @@ async def get_bots(
238238
self,
239239
limit: int = 50,
240240
offset: int = 0,
241-
sort: t.Optional[str] = None,
242-
search: t.Optional[t.Dict[str, t.Any]] = None,
243-
fields: t.Optional[t.List[str]] = None,
244-
) -> types.DataDict[str, t.Any]:
241+
sort: Optional[str] = None,
242+
search: Optional[dict[str, Any]] = None,
243+
fields: Optional[list[str]] = None,
244+
) -> types.DataDict[str, Any]:
245245
"""This function is a coroutine.
246246
247247
Gets information about listed bots on Top.gg.

topgg/data.py

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,28 @@
2323
__all__ = ["data", "DataContainerMixin"]
2424

2525
import inspect
26-
import typing as t
26+
from typing import (
27+
TypeVar,
28+
Any,
29+
Type,
30+
cast,
31+
Generic,
32+
Mapping,
33+
overload,
34+
Callable,
35+
Optional,
36+
Union
37+
)
38+
39+
from typing_extensions import Self
2740

2841
from topgg.errors import TopGGException
2942

30-
T = t.TypeVar("T")
31-
DataContainerT = t.TypeVar("DataContainerT", bound="DataContainerMixin")
43+
T = TypeVar("T")
44+
DataContainerT = TypeVar("DataContainerT", bound="DataContainerMixin")
3245

3346

34-
def data(type_: t.Type[T]) -> T:
47+
def data(type_: Type[T]) -> T:
3548
"""
3649
Represents the injected data. This should be set as the parameter's default value.
3750
@@ -56,14 +69,14 @@ def data(type_: t.Type[T]) -> T:
5669
def get_stats(client: Client = topgg.data(Client)):
5770
return topgg.StatsWrapper(guild_count=len(client.guilds), shard_count=len(client.shards))
5871
"""
59-
return t.cast(T, Data(type_))
72+
return cast(T, Data(type_))
6073

6174

62-
class Data(t.Generic[T]):
75+
class Data(Generic[T]):
6376
__slots__ = ("type",)
6477

65-
def __init__(self, type_: t.Type[T]) -> None:
66-
self.type: t.Type[T] = type_
78+
def __init__(self, type_: Type[T]) -> None:
79+
self.type: Type[T] = type_
6780

6881

6982
class DataContainerMixin:
@@ -77,10 +90,10 @@ class DataContainerMixin:
7790
__slots__ = ("_data",)
7891

7992
def __init__(self) -> None:
80-
self._data: t.Dict[t.Type, t.Any] = {type(self): self}
93+
self._data: dict[Type, Any] = {type(self): Self}
8194

8295
def set_data(
83-
self: DataContainerT, data_: t.Any, *, override: bool = False
96+
self: DataContainerT, data_: Any, *, override: bool = False
8497
) -> DataContainerT:
8598
"""
8699
Sets data to be available in your functions.
@@ -104,28 +117,28 @@ def set_data(
104117
self._data[type_] = data_
105118
return self
106119

107-
@t.overload
108-
def get_data(self, type_: t.Type[T]) -> t.Optional[T]:
120+
@overload
121+
def get_data(self, type_: Type[T]) -> Optional[T]:
109122
...
110123

111-
@t.overload
112-
def get_data(self, type_: t.Type[T], default: t.Any = None) -> t.Any:
124+
@overload
125+
def get_data(self, type_: Type[T], default: Any = None) -> Any:
113126
...
114127

115-
def get_data(self, type_: t.Any, default: t.Any = None) -> t.Any:
128+
def get_data(self, type_: Any, default: Any = None) -> Any:
116129
"""Gets the injected data."""
117130
return self._data.get(type_, default)
118131

119132
async def _invoke_callback(
120-
self, callback: t.Callable[..., T], *args: t.Any, **kwargs: t.Any
133+
self, callback: Callable[..., T], *args: Any, **kwargs: Any
121134
) -> T:
122-
parameters: t.Mapping[str, inspect.Parameter]
135+
parameters: Mapping[str, inspect.Parameter]
123136
try:
124137
parameters = inspect.signature(callback).parameters
125138
except (ValueError, TypeError):
126139
parameters = {}
127140

128-
signatures: t.Dict[str, Data] = {
141+
signatures: dict[str, Data] = {
129142
k: v.default
130143
for k, v in parameters.items()
131144
if v.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
@@ -135,11 +148,11 @@ async def _invoke_callback(
135148
for k, v in signatures.items():
136149
signatures[k] = self._resolve_data(v.type)
137150

138-
res = callback(*args, **{**signatures, **kwargs})
151+
res = callback(*args, Union[signatures, kwargs])
139152
if inspect.isawaitable(res):
140153
return await res
141154

142155
return res
143156

144-
def _resolve_data(self, type_: t.Type[T]) -> T:
157+
def _resolve_data(self, type_: Type[T]) -> T:
145158
return self._data[type_]

0 commit comments

Comments
 (0)