From 7869213060f6e083ef021a0277b15d0035a108b4 Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 21:39:15 +0100 Subject: [PATCH 1/8] Clean up python --- discord/__main__.py | 8 ++++++-- discord/activity.py | 10 +++++----- discord/ext/commands/context.py | 6 ++---- discord/ext/commands/converter.py | 21 ++++++++++----------- discord/ext/commands/view.py | 15 +++++++-------- discord/ext/tasks/__init__.py | 25 ++++++++++--------------- discord/player.py | 13 ++++++++----- discord/ui/button.py | 16 ++++++++-------- 8 files changed, 56 insertions(+), 58 deletions(-) diff --git a/discord/__main__.py b/discord/__main__.py index 513b0cb3..524e4df1 100644 --- a/discord/__main__.py +++ b/discord/__main__.py @@ -32,9 +32,13 @@ import aiohttp import platform def show_version(): - entries = [] + entries = [ + '- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format( + sys.version_info + ) + ] + - entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info)) version_info = discord.version_info entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info)) if version_info.releaselevel != 'final': diff --git a/discord/activity.py b/discord/activity.py index 51205377..cba61f38 100644 --- a/discord/activity.py +++ b/discord/activity.py @@ -794,13 +794,13 @@ class CustomActivity(BaseActivity): return hash((self.name, str(self.emoji))) def __str__(self) -> str: - if self.emoji: - if self.name: - return f'{self.emoji} {self.name}' - return str(self.emoji) - else: + if not self.emoji: return str(self.name) + if self.name: + return f'{self.emoji} {self.name}' + return str(self.emoji) + def __repr__(self) -> str: return f'' diff --git a/discord/ext/commands/context.py b/discord/ext/commands/context.py index 38a24d1d..1d02e6fd 100644 --- a/discord/ext/commands/context.py +++ b/discord/ext/commands/context.py @@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + from __future__ import annotations import inspect @@ -60,10 +61,7 @@ T = TypeVar('T') BotT = TypeVar('BotT', bound="Union[Bot, AutoShardedBot]") CogT = TypeVar('CogT', bound="Cog") -if TYPE_CHECKING: - P = ParamSpec('P') -else: - P = TypeVar('P') +P = ParamSpec('P') if TYPE_CHECKING else TypeVar('P') class Context(discord.abc.Messageable, Generic[BotT]): diff --git a/discord/ext/commands/converter.py b/discord/ext/commands/converter.py index 5740a188..ce7037a4 100644 --- a/discord/ext/commands/converter.py +++ b/discord/ext/commands/converter.py @@ -353,15 +353,15 @@ class PartialMessageConverter(Converter[discord.PartialMessage]): @staticmethod def _resolve_channel(ctx, guild_id, channel_id) -> Optional[PartialMessageableChannel]: - if guild_id is not None: - guild = ctx.bot.get_guild(guild_id) - if guild is not None and channel_id is not None: - return guild._resolve_channel(channel_id) # type: ignore - else: - return None - else: + if guild_id is None: return ctx.bot.get_channel(channel_id) if channel_id else ctx.channel + guild = ctx.bot.get_guild(guild_id) + if guild is not None and channel_id is not None: + return guild._resolve_channel(channel_id) # type: ignore + else: + return None + async def convert(self, ctx: Context, argument: str) -> discord.PartialMessage: guild_id, message_id, channel_id = self._get_id_matches(ctx, argument) channel = self._resolve_channel(ctx, guild_id, channel_id) @@ -754,8 +754,8 @@ class GuildConverter(IDConverter[discord.Guild]): if result is None: result = discord.utils.get(ctx.bot.guilds, name=argument) - if result is None: - raise GuildNotFound(argument) + if result is None: + raise GuildNotFound(argument) return result @@ -939,8 +939,7 @@ class clean_content(Converter[str]): def repl(match: re.Match) -> str: type = match[1] id = int(match[2]) - transformed = transforms[type](id) - return transformed + return transforms[type](id) result = re.sub(r'<(@[!&]?|#)([0-9]{15,20})>', repl, argument) if self.escape_markdown: diff --git a/discord/ext/commands/view.py b/discord/ext/commands/view.py index a7dc7236..39cc35f7 100644 --- a/discord/ext/commands/view.py +++ b/discord/ext/commands/view.py @@ -82,9 +82,7 @@ class StringView: def skip_string(self, string): strlen = len(string) if self.buffer[self.index:self.index + strlen] == string: - self.previous = self.index - self.index += strlen - return True + return self._return_index(strlen, True) return False def read_rest(self): @@ -95,9 +93,7 @@ class StringView: def read(self, n): result = self.buffer[self.index:self.index + n] - self.previous = self.index - self.index += n - return result + return self._return_index(n, result) def get(self): try: @@ -105,9 +101,12 @@ class StringView: except IndexError: result = None + return self._return_index(1, result) + + def _return_index(self, arg0, arg1): self.previous = self.index - self.index += 1 - return result + self.index += arg0 + return arg1 def get_word(self): pos = 0 diff --git a/discord/ext/tasks/__init__.py b/discord/ext/tasks/__init__.py index 5b78f10e..ea02897c 100644 --- a/discord/ext/tasks/__init__.py +++ b/discord/ext/tasks/__init__.py @@ -488,11 +488,7 @@ class Loop(Generic[LF]): The function was not a coroutine. """ - if not inspect.iscoroutinefunction(coro): - raise TypeError(f'Expected coroutine function, received {coro.__class__.__name__!r}.') - - self._before_loop = coro - return coro + return self._raise_expected_coro(coro) def after_loop(self, coro: FT) -> FT: """A decorator that register a coroutine to be called after the loop finished running. @@ -516,11 +512,7 @@ class Loop(Generic[LF]): The function was not a coroutine. """ - if not inspect.iscoroutinefunction(coro): - raise TypeError(f'Expected coroutine function, received {coro.__class__.__name__!r}.') - - self._after_loop = coro - return coro + return self._raise_expected_coro(coro) def error(self, coro: ET) -> ET: """A decorator that registers a coroutine to be called if the task encounters an unhandled exception. @@ -542,10 +534,14 @@ class Loop(Generic[LF]): TypeError The function was not a coroutine. """ - if not inspect.iscoroutinefunction(coro): - raise TypeError(f'Expected coroutine function, received {coro.__class__.__name__!r}.') + return self._raise_expected_coro(coro) + + def _raise_expected_coro(self, coro): + if not inspect.iscoroutinefunction(coro): + raise TypeError( + f'Expected coroutine function, received {coro.__class__.__name__!r}.' + ) - self._error = coro # type: ignore return coro def _get_next_sleep_time(self) -> datetime.datetime: @@ -614,8 +610,7 @@ class Loop(Generic[LF]): ) ret.append(t if t.tzinfo is not None else t.replace(tzinfo=utc)) - ret = sorted(set(ret)) # de-dupe and sort times - return ret + return sorted(set(ret)) def change_interval( self, diff --git a/discord/player.py b/discord/player.py index 8098d3e3..79579c8d 100644 --- a/discord/player.py +++ b/discord/player.py @@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + from __future__ import annotations import threading @@ -63,10 +64,7 @@ __all__ = ( CREATE_NO_WINDOW: int -if sys.platform != 'win32': - CREATE_NO_WINDOW = 0 -else: - CREATE_NO_WINDOW = 0x08000000 +CREATE_NO_WINDOW = 0 if sys.platform != 'win32' else 0x08000000 class AudioSource: """Represents an audio stream. @@ -526,7 +524,12 @@ class FFmpegOpusAudio(FFmpegAudio): @staticmethod def _probe_codec_native(source, executable: str = 'ffmpeg') -> Tuple[Optional[str], Optional[int]]: - exe = executable[:2] + 'probe' if executable in ('ffmpeg', 'avconv') else executable + exe = ( + executable[:2] + 'probe' + if executable in {'ffmpeg', 'avconv'} + else executable + ) + args = [exe, '-v', 'quiet', '-print_format', 'json', '-show_streams', '-select_streams', 'a:0', source] output = subprocess.check_output(args, timeout=20) codec = bitrate = None diff --git a/discord/ui/button.py b/discord/ui/button.py index fedeac68..0b16e87e 100644 --- a/discord/ui/button.py +++ b/discord/ui/button.py @@ -185,16 +185,16 @@ class Button(Item[V]): @emoji.setter def emoji(self, value: Optional[Union[str, Emoji, PartialEmoji]]): # type: ignore - if value is not None: - if isinstance(value, str): - self._underlying.emoji = PartialEmoji.from_str(value) - elif isinstance(value, _EmojiTag): - self._underlying.emoji = value._to_partial() - else: - raise TypeError(f'expected str, Emoji, or PartialEmoji, received {value.__class__} instead') - else: + if value is None: self._underlying.emoji = None + elif isinstance(value, str): + self._underlying.emoji = PartialEmoji.from_str(value) + elif isinstance(value, _EmojiTag): + self._underlying.emoji = value._to_partial() + else: + raise TypeError(f'expected str, Emoji, or PartialEmoji, received {value.__class__} instead') + @classmethod def from_component(cls: Type[B], button: ButtonComponent) -> B: return cls( -- 2.47.2 From 38d4c0ec1b3b08f527ae4c03090775ebded33409 Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 21:42:12 +0100 Subject: [PATCH 2/8] Clean up bot python --- discord/ext/commands/bot.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/discord/ext/commands/bot.py b/discord/ext/commands/bot.py index b4da6100..1e314921 100644 --- a/discord/ext/commands/bot.py +++ b/discord/ext/commands/bot.py @@ -379,11 +379,9 @@ class BotBase(GroupMixin): TypeError The coroutine passed is not actually a coroutine. """ - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The pre-invoke hook must be a coroutine.') - - self._before_invoke = coro - return coro + return self._raise_expected_coro( + coro, 'The pre-invoke hook must be a coroutine.' + ) def after_invoke(self, coro: CFT) -> CFT: r"""A decorator that registers a coroutine as a post-invoke hook. @@ -412,10 +410,15 @@ class BotBase(GroupMixin): TypeError The coroutine passed is not actually a coroutine. """ - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The post-invoke hook must be a coroutine.') + return self._raise_expected_coro( + coro, 'The post-invoke hook must be a coroutine.' + ) + + + def _raise_expected_coro(self, coro, arg1): + if not asyncio.iscoroutinefunction(coro): + raise TypeError(arg1) - self._after_invoke = coro return coro # listener registration @@ -626,10 +629,12 @@ class BotBase(GroupMixin): # remove all the listeners from the module for event_list in self.extra_events.copy().values(): - remove = [] - for index, event in enumerate(event_list): - if event.__module__ is not None and _is_submodule(name, event.__module__): - remove.append(index) + remove = [ + index + for index, event in enumerate(event_list) + if event.__module__ is not None + and _is_submodule(name, event.__module__) + ] for index in reversed(remove): del event_list[index] -- 2.47.2 From 507b413cd1d2215425bf7ca9d20664b60a195a82 Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 22:09:51 +0100 Subject: [PATCH 3/8] revert lists --- discord/__main__.py | 32 ++++++++++++++------------------ discord/ext/commands/bot.py | 10 ++++------ 2 files changed, 18 insertions(+), 24 deletions(-) diff --git a/discord/__main__.py b/discord/__main__.py index 524e4df1..c9572367 100644 --- a/discord/__main__.py +++ b/discord/__main__.py @@ -32,13 +32,9 @@ import aiohttp import platform def show_version(): - entries = [ - '- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format( - sys.version_info - ) - ] - + entries = [] + entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info)) version_info = discord.version_info entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info)) if version_info.releaselevel != 'final': @@ -55,7 +51,7 @@ def core(parser, args): if args.version: show_version() -_bot_template = """#!/usr/bin/env python3 +bot_template = """#!/usr/bin/env python3 from discord.ext import commands import discord @@ -68,10 +64,10 @@ class Bot(commands.{base}): try: self.load_extension(cog) except Exception as exc: - print(f'Could not load extension {{cog}} due to {{exc.__class__.__name__}}: {{exc}}') + print('Could not load extension {{0}} due to {{1.__class__.__name__}}: {{1}}'.format(cog, exc)) async def on_ready(self): - print(f'Logged on as {{self.user}} (ID: {{self.user.id}})') + print('Logged on as {{0}} (ID: {{0.id}})'.format(self.user)) bot = Bot() @@ -81,7 +77,7 @@ bot = Bot() bot.run(config.token) """ -_gitignore_template = """# Byte-compiled / optimized / DLL files +gitignore_template = """# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class @@ -111,7 +107,7 @@ var/ config.py """ -_cog_template = '''from discord.ext import commands +cog_template = '''from discord.ext import commands import discord class {name}(commands.Cog{attrs}): @@ -124,7 +120,7 @@ def setup(bot): bot.add_cog({name}(bot)) ''' -_cog_extras = ''' +cog_extras = ''' def cog_unload(self): # clean up logic goes here pass @@ -174,7 +170,7 @@ _base_table = { # NUL (0) and 1-31 are disallowed _base_table.update((chr(i), None) for i in range(32)) -_translation_table = str.maketrans(_base_table) +translation_table = str.maketrans(_base_table) def to_path(parser, name, *, replace_spaces=False): if isinstance(name, Path): @@ -186,7 +182,7 @@ def to_path(parser, name, *, replace_spaces=False): if len(name) <= 4 and name.upper() in forbidden: parser.error('invalid directory name given, use a different one') - name = name.translate(_translation_table) + name = name.translate(translation_table) if replace_spaces: name = name.replace(' ', '-') return Path(name) @@ -219,14 +215,14 @@ def newbot(parser, args): try: with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp: base = 'Bot' if not args.sharded else 'AutoShardedBot' - fp.write(_bot_template.format(base=base, prefix=args.prefix)) + fp.write(bot_template.format(base=base, prefix=args.prefix)) except OSError as exc: parser.error(f'could not create bot file ({exc})') if not args.no_git: try: with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp: - fp.write(_gitignore_template) + fp.write(gitignore_template) except OSError as exc: print(f'warning: could not create .gitignore file ({exc})') @@ -244,7 +240,7 @@ def newcog(parser, args): try: with open(str(directory), 'w', encoding='utf-8') as fp: attrs = '' - extra = _cog_extras if args.full else '' + extra = cog_extras if args.full else '' if args.class_name: name = args.class_name else: @@ -259,7 +255,7 @@ def newcog(parser, args): attrs += f', name="{args.display_name}"' if args.hide_commands: attrs += ', command_attrs=dict(hidden=True)' - fp.write(_cog_template.format(name=name, extra=extra, attrs=attrs)) + fp.write(cog_template.format(name=name, extra=extra, attrs=attrs)) except OSError as exc: parser.error(f'could not create cog file ({exc})') else: diff --git a/discord/ext/commands/bot.py b/discord/ext/commands/bot.py index 1e314921..b4a7dcfa 100644 --- a/discord/ext/commands/bot.py +++ b/discord/ext/commands/bot.py @@ -629,12 +629,10 @@ class BotBase(GroupMixin): # remove all the listeners from the module for event_list in self.extra_events.copy().values(): - remove = [ - index - for index, event in enumerate(event_list) - if event.__module__ is not None - and _is_submodule(name, event.__module__) - ] + remove = [] + for index, event in enumerate(event_list): + if event.__module__ is not None and _is_submodule(name, event.__module__): + remove.append(index) for index in reversed(remove): del event_list[index] -- 2.47.2 From 1829048c80ea17a314ed9a60477bf32d548b4305 Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 22:19:39 +0100 Subject: [PATCH 4/8] revert commands.bot completely --- discord/__main__.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/discord/__main__.py b/discord/__main__.py index c9572367..25c4620c 100644 --- a/discord/__main__.py +++ b/discord/__main__.py @@ -51,7 +51,7 @@ def core(parser, args): if args.version: show_version() -bot_template = """#!/usr/bin/env python3 +_bot_template = """#!/usr/bin/env python3 from discord.ext import commands import discord @@ -64,10 +64,10 @@ class Bot(commands.{base}): try: self.load_extension(cog) except Exception as exc: - print('Could not load extension {{0}} due to {{1.__class__.__name__}}: {{1}}'.format(cog, exc)) + print(f'Could not load extension {{cog}} due to {{exc.__class__.__name__}}: {{exc}}') async def on_ready(self): - print('Logged on as {{0}} (ID: {{0.id}})'.format(self.user)) + print(f'Logged on as {{self.user}} (ID: {{self.user.id}})') bot = Bot() @@ -77,7 +77,7 @@ bot = Bot() bot.run(config.token) """ -gitignore_template = """# Byte-compiled / optimized / DLL files +_gitignore_template = """# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class @@ -107,7 +107,7 @@ var/ config.py """ -cog_template = '''from discord.ext import commands +_cog_template = '''from discord.ext import commands import discord class {name}(commands.Cog{attrs}): @@ -120,7 +120,7 @@ def setup(bot): bot.add_cog({name}(bot)) ''' -cog_extras = ''' +_cog_extras = ''' def cog_unload(self): # clean up logic goes here pass @@ -170,7 +170,7 @@ _base_table = { # NUL (0) and 1-31 are disallowed _base_table.update((chr(i), None) for i in range(32)) -translation_table = str.maketrans(_base_table) +_translation_table = str.maketrans(_base_table) def to_path(parser, name, *, replace_spaces=False): if isinstance(name, Path): @@ -182,7 +182,7 @@ def to_path(parser, name, *, replace_spaces=False): if len(name) <= 4 and name.upper() in forbidden: parser.error('invalid directory name given, use a different one') - name = name.translate(translation_table) + name = name.translate(_translation_table) if replace_spaces: name = name.replace(' ', '-') return Path(name) @@ -215,14 +215,14 @@ def newbot(parser, args): try: with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp: base = 'Bot' if not args.sharded else 'AutoShardedBot' - fp.write(bot_template.format(base=base, prefix=args.prefix)) + fp.write(_bot_template.format(base=base, prefix=args.prefix)) except OSError as exc: parser.error(f'could not create bot file ({exc})') if not args.no_git: try: with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp: - fp.write(gitignore_template) + fp.write(_gitignore_template) except OSError as exc: print(f'warning: could not create .gitignore file ({exc})') @@ -240,7 +240,7 @@ def newcog(parser, args): try: with open(str(directory), 'w', encoding='utf-8') as fp: attrs = '' - extra = cog_extras if args.full else '' + extra = _cog_extras if args.full else '' if args.class_name: name = args.class_name else: @@ -255,7 +255,7 @@ def newcog(parser, args): attrs += f', name="{args.display_name}"' if args.hide_commands: attrs += ', command_attrs=dict(hidden=True)' - fp.write(cog_template.format(name=name, extra=extra, attrs=attrs)) + fp.write(_cog_template.format(name=name, extra=extra, attrs=attrs)) except OSError as exc: parser.error(f'could not create cog file ({exc})') else: @@ -297,4 +297,4 @@ def main(): args.func(parser, args) if __name__ == '__main__': - main() + main() \ No newline at end of file -- 2.47.2 From 73a4996aa9dfedeb403bfffdbd9baa0c66f88d70 Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 22:52:58 +0100 Subject: [PATCH 5/8] extract raise_expected_coro further --- discord/ext/commands/bot.py | 12 ++++-------- discord/ext/tasks/__init__.py | 18 ++++++------------ discord/utils.py | 36 +++++++++++++++++++---------------- 3 files changed, 30 insertions(+), 36 deletions(-) diff --git a/discord/ext/commands/bot.py b/discord/ext/commands/bot.py index b4a7dcfa..69eeed88 100644 --- a/discord/ext/commands/bot.py +++ b/discord/ext/commands/bot.py @@ -22,6 +22,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ +from TwitchIO.twitchio.ext.commands import utils from __future__ import annotations @@ -43,6 +44,7 @@ from .context import Context from . import errors from .help import HelpCommand, DefaultHelpCommand from .cog import Cog +from discord.utils import raise_expected_coro if TYPE_CHECKING: import importlib.machinery @@ -379,7 +381,7 @@ class BotBase(GroupMixin): TypeError The coroutine passed is not actually a coroutine. """ - return self._raise_expected_coro( + return raise_expected_coro( coro, 'The pre-invoke hook must be a coroutine.' ) @@ -410,17 +412,11 @@ class BotBase(GroupMixin): TypeError The coroutine passed is not actually a coroutine. """ - return self._raise_expected_coro( + return raise_expected_coro( coro, 'The post-invoke hook must be a coroutine.' ) - def _raise_expected_coro(self, coro, arg1): - if not asyncio.iscoroutinefunction(coro): - raise TypeError(arg1) - - return coro - # listener registration def add_listener(self, func: CoroFunc, name: str = MISSING) -> None: diff --git a/discord/ext/tasks/__init__.py b/discord/ext/tasks/__init__.py index ea02897c..6a912ea2 100644 --- a/discord/ext/tasks/__init__.py +++ b/discord/ext/tasks/__init__.py @@ -46,7 +46,9 @@ import traceback from collections.abc import Sequence from discord.backoff import ExponentialBackoff -from discord.utils import MISSING +from discord.utils import MISSING, raise_expected_coro +#from discord.utils import raise_expected_coro + __all__ = ( 'loop', @@ -488,7 +490,7 @@ class Loop(Generic[LF]): The function was not a coroutine. """ - return self._raise_expected_coro(coro) + return raise_expected_coro(coro, f'Expected coroutine function, received {coro.__class__.__name__!r}.') def after_loop(self, coro: FT) -> FT: """A decorator that register a coroutine to be called after the loop finished running. @@ -512,7 +514,7 @@ class Loop(Generic[LF]): The function was not a coroutine. """ - return self._raise_expected_coro(coro) + return raise_expected_coro(coro, f'Expected coroutine function, received {coro.__class__.__name__!r}.') def error(self, coro: ET) -> ET: """A decorator that registers a coroutine to be called if the task encounters an unhandled exception. @@ -534,15 +536,7 @@ class Loop(Generic[LF]): TypeError The function was not a coroutine. """ - return self._raise_expected_coro(coro) - - def _raise_expected_coro(self, coro): - if not inspect.iscoroutinefunction(coro): - raise TypeError( - f'Expected coroutine function, received {coro.__class__.__name__!r}.' - ) - - return coro + return raise_expected_coro(coro, f'Expected coroutine function, received {coro.__class__.__name__!r}.') def _get_next_sleep_time(self) -> datetime.datetime: if self._sleep is not MISSING: diff --git a/discord/utils.py b/discord/utils.py index 4360b77a..b10b11c1 100644 --- a/discord/utils.py +++ b/discord/utils.py @@ -499,14 +499,14 @@ else: def _parse_ratelimit_header(request: Any, *, use_clock: bool = False) -> float: reset_after: Optional[str] = request.headers.get('X-Ratelimit-Reset-After') - if use_clock or not reset_after: - utc = datetime.timezone.utc - now = datetime.datetime.now(utc) - reset = datetime.datetime.fromtimestamp(float(request.headers['X-Ratelimit-Reset']), utc) - return (reset - now).total_seconds() - else: + if not use_clock and reset_after: return float(reset_after) + utc = datetime.timezone.utc + now = datetime.datetime.now(utc) + reset = datetime.datetime.fromtimestamp(float(request.headers['X-Ratelimit-Reset']), utc) + return (reset - now).total_seconds() + async def maybe_coroutine(f, *args, **kwargs): value = f(*args, **kwargs) @@ -659,11 +659,10 @@ def resolve_invite(invite: Union[Invite, str]) -> str: if isinstance(invite, Invite): return invite.code - else: - rx = r'(?:https?\:\/\/)?discord(?:\.gg|(?:app)?\.com\/invite)\/(.+)' - m = re.match(rx, invite) - if m: - return m.group(1) + rx = r'(?:https?\:\/\/)?discord(?:\.gg|(?:app)?\.com\/invite)\/(.+)' + m = re.match(rx, invite) + if m: + return m.group(1) return invite @@ -687,11 +686,10 @@ def resolve_template(code: Union[Template, str]) -> str: if isinstance(code, Template): return code.code - else: - rx = r'(?:https?\:\/\/)?discord(?:\.new|(?:app)?\.com\/template)\/(.+)' - m = re.match(rx, code) - if m: - return m.group(1) + rx = r'(?:https?\:\/\/)?discord(?:\.new|(?:app)?\.com\/template)\/(.+)' + m = re.match(rx, code) + if m: + return m.group(1) return code @@ -1017,3 +1015,9 @@ def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None) if style is None: return f'' return f'' + + +def raise_expected_coro(coro, error: str)-> TypeError: + if not asyncio.iscoroutinefunction(coro): + raise TypeError(error) + return coro \ No newline at end of file -- 2.47.2 From 5a23f1ec75a41d42fe288717d9384ca45783b496 Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 23:08:53 +0100 Subject: [PATCH 6/8] add new lines --- discord/__main__.py | 2 +- discord/utils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/discord/__main__.py b/discord/__main__.py index 25c4620c..513b0cb3 100644 --- a/discord/__main__.py +++ b/discord/__main__.py @@ -297,4 +297,4 @@ def main(): args.func(parser, args) if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/discord/utils.py b/discord/utils.py index b10b11c1..cad99da6 100644 --- a/discord/utils.py +++ b/discord/utils.py @@ -1020,4 +1020,4 @@ def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None) def raise_expected_coro(coro, error: str)-> TypeError: if not asyncio.iscoroutinefunction(coro): raise TypeError(error) - return coro \ No newline at end of file + return coro -- 2.47.2 From 672e07609102778f62697fe202cc2e255c33538a Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sat, 28 Aug 2021 23:13:44 +0100 Subject: [PATCH 7/8] removed erroneous import --- discord/ext/commands/bot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/discord/ext/commands/bot.py b/discord/ext/commands/bot.py index 69eeed88..a94ad846 100644 --- a/discord/ext/commands/bot.py +++ b/discord/ext/commands/bot.py @@ -22,7 +22,6 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ -from TwitchIO.twitchio.ext.commands import utils from __future__ import annotations -- 2.47.2 From ff4a95b45efa6685cb2f79e5d3b18c08ef20398f Mon Sep 17 00:00:00 2001 From: chillymosh Date: Sun, 29 Aug 2021 10:49:56 +0100 Subject: [PATCH 8/8] remove hashed line --- discord/ext/tasks/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord/ext/tasks/__init__.py b/discord/ext/tasks/__init__.py index 6a912ea2..9518390e 100644 --- a/discord/ext/tasks/__init__.py +++ b/discord/ext/tasks/__init__.py @@ -47,7 +47,7 @@ import traceback from collections.abc import Sequence from discord.backoff import ExponentialBackoff from discord.utils import MISSING, raise_expected_coro -#from discord.utils import raise_expected_coro + __all__ = ( -- 2.47.2