Bump black to 20.8b1 (and reformat) (#4371)

* Bump black version

* Reformat with black
This commit is contained in:
jack1142 2020-08-29 19:12:28 +02:00 committed by GitHub
parent 56b54d4d34
commit 85afe19455
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 83 additions and 54 deletions

View File

@ -319,7 +319,7 @@ def handle_edit(cli_flags: Namespace):
async def run_bot(red: Red, cli_flags: Namespace) -> None: async def run_bot(red: Red, cli_flags: Namespace) -> None:
""" """
This runs the bot. This runs the bot.
Any shutdown which is a result of not being able to log in needs to raise Any shutdown which is a result of not being able to log in needs to raise
a SystemExit exception. a SystemExit exception.

View File

@ -76,7 +76,8 @@ class Admin(commands.Cog):
self.config.register_global(serverlocked=False, schema_version=0) self.config.register_global(serverlocked=False, schema_version=0)
self.config.register_guild( self.config.register_guild(
announce_channel=None, selfroles=[], # Integer ID # List of integer ID's announce_channel=None, # Integer ID
selfroles=[], # List of integer ID's
) )
self.__current_announcer = None self.__current_announcer = None

View File

@ -24,7 +24,7 @@ class AliasEntry:
uses: int uses: int
def __init__( def __init__(
self, name: str, command: Union[Tuple[str], str], creator: int, guild: Optional[int], self, name: str, command: Union[Tuple[str], str], creator: int, guild: Optional[int]
): ):
super().__init__() super().__init__()
self.name = name self.name = name
@ -161,7 +161,7 @@ class AliasCache:
return aliases return aliases
async def get_alias( async def get_alias(
self, guild: Optional[discord.Guild], alias_name: str, self, guild: Optional[discord.Guild], alias_name: str
) -> Optional[AliasEntry]: ) -> Optional[AliasEntry]:
"""Returns an AliasEntry object if the provided alias_name is a registered alias""" """Returns an AliasEntry object if the provided alias_name is a registered alias"""
server_aliases: List[AliasEntry] = [] server_aliases: List[AliasEntry] = []

View File

@ -102,7 +102,9 @@ class AudioAPIInterface:
return track return track
async def route_tasks( async def route_tasks(
self, action_type: str = None, data: Union[List[MutableMapping], MutableMapping] = None, self,
action_type: str = None,
data: Union[List[MutableMapping], MutableMapping] = None,
) -> None: ) -> None:
"""Separate the tasks and run them in the appropriate functions""" """Separate the tasks and run them in the appropriate functions"""

View File

@ -33,7 +33,7 @@ class YouTubeWrapper:
def update_token(self, new_token: Mapping[str, str]): def update_token(self, new_token: Mapping[str, str]):
self._token = new_token self._token = new_token
async def _get_api_key(self,) -> str: async def _get_api_key(self) -> str:
"""Get the stored youtube token""" """Get the stored youtube token"""
if not self._token: if not self._token:
self._token = await self.bot.get_shared_api_tokens("youtube") self._token = await self.bot.get_shared_api_tokens("youtube")

View File

@ -78,12 +78,12 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
if isinstance(error, commands.ArgParserFailure): if isinstance(error, commands.ArgParserFailure):
handled = True handled = True
msg = _("`{user_input}` is not a valid value for `{command}`").format( msg = _("`{user_input}` is not a valid value for `{command}`").format(
user_input=error.user_input, command=error.cmd, user_input=error.user_input, command=error.cmd
) )
if error.custom_help_msg: if error.custom_help_msg:
msg += f"\n{error.custom_help_msg}" msg += f"\n{error.custom_help_msg}"
await self.send_embed_msg( await self.send_embed_msg(
ctx, title=_("Unable To Parse Argument"), description=msg, error=True, ctx, title=_("Unable To Parse Argument"), description=msg, error=True
) )
if error.send_cmd_help: if error.send_cmd_help:
await ctx.send_help() await ctx.send_help()
@ -101,7 +101,7 @@ class DpyEvents(MixinMeta, metaclass=CompositeMetaClass):
) )
else: else:
await self.send_embed_msg( await self.send_embed_msg(
ctx, title=_("Invalid Argument"), description=error.args[0], error=True, ctx, title=_("Invalid Argument"), description=error.args[0], error=True
) )
else: else:
await ctx.send_help() await ctx.send_help()

View File

@ -146,8 +146,10 @@ class ServerManager:
@staticmethod @staticmethod
async def _get_java_version() -> Tuple[int, int]: async def _get_java_version() -> Tuple[int, int]:
"""This assumes we've already checked that java exists.""" """This assumes we've already checked that java exists."""
_proc: asyncio.subprocess.Process = await asyncio.create_subprocess_exec( # pylint:disable=no-member _proc: asyncio.subprocess.Process = (
"java", "-version", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE await asyncio.create_subprocess_exec( # pylint:disable=no-member
"java", "-version", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
) )
# java -version outputs to stderr # java -version outputs to stderr
_, err = await _proc.communicate() _, err = await _proc.communicate()

View File

@ -416,10 +416,9 @@ class Cleanup(commands.Cog):
is_cc = lambda name: False is_cc = lambda name: False
alias_cog = self.bot.get_cog("Alias") alias_cog = self.bot.get_cog("Alias")
if alias_cog is not None: if alias_cog is not None:
alias_names: Set[str] = ( alias_names: Set[str] = set(
set((a.name for a in await alias_cog._aliases.get_global_aliases())) a.name for a in await alias_cog._aliases.get_global_aliases()
| set(a.name for a in await alias_cog._aliases.get_guild_aliases(ctx.guild)) ) | set(a.name for a in await alias_cog._aliases.get_guild_aliases(ctx.guild))
)
is_alias = lambda name: name in alias_names is_alias = lambda name: name in alias_names
else: else:
is_alias = lambda name: False is_alias = lambda name: False
@ -559,7 +558,7 @@ class Cleanup(commands.Cog):
return False return False
to_delete = await self.get_messages_for_deletion( to_delete = await self.get_messages_for_deletion(
channel=ctx.channel, limit=number, check=check, before=ctx.message, channel=ctx.channel, limit=number, check=check, before=ctx.message
) )
if len(to_delete) > 100: if len(to_delete) > 100:

View File

@ -40,7 +40,7 @@ class Downloader(commands.Cog):
Community cogs, also called third party cogs, are not included Community cogs, also called third party cogs, are not included
in the default Red install. in the default Red install.
Community cogs come in repositories. Repos are a group of cogs Community cogs come in repositories. Repos are a group of cogs
you can install. You always need to add the creator's repository you can install. You always need to add the creator's repository
using the `[p]repo` command before you can install one or more using the `[p]repo` command before you can install one or more
@ -545,7 +545,9 @@ class Downloader(commands.Cog):
) )
except OSError: except OSError:
log.exception( log.exception(
"Something went wrong trying to add repo %s under name %s", repo_url, name, "Something went wrong trying to add repo %s under name %s",
repo_url,
name,
) )
await ctx.send( await ctx.send(
_( _(

View File

@ -1153,11 +1153,11 @@ class RepoManager:
async def update_repos( async def update_repos(
self, repos: Optional[Iterable[Repo]] = None self, repos: Optional[Iterable[Repo]] = None
) -> Tuple[Dict[Repo, Tuple[str, str]], List[str]]: ) -> Tuple[Dict[Repo, Tuple[str, str]], List[str]]:
"""Calls `Repo.update` on passed repositories and """Calls `Repo.update` on passed repositories and
catches failing ones. catches failing ones.
Calling without params updates all currently installed repos. Calling without params updates all currently installed repos.
Parameters Parameters
---------- ----------
repos: Iterable repos: Iterable
@ -1168,7 +1168,7 @@ class RepoManager:
tuple of Dict and list tuple of Dict and list
A mapping of `Repo` objects that received new commits to A mapping of `Repo` objects that received new commits to
a 2-`tuple` of `str` containing old and new commit hashes. a 2-`tuple` of `str` containing old and new commit hashes.
`list` of failed `Repo` names `list` of failed `Repo` names
""" """
failed = [] failed = []

View File

@ -550,7 +550,8 @@ class Economy(commands.Cog):
embed.description = box(temp_msg, lang="md") embed.description = box(temp_msg, lang="md")
embed.set_footer( embed.set_footer(
text=footer_message.format( text=footer_message.format(
page_num=len(highscores) + 1, page_len=ceil(len(bank_sorted) / 10), page_num=len(highscores) + 1,
page_len=ceil(len(bank_sorted) / 10),
) )
) )
highscores.append(embed) highscores.append(embed)
@ -565,7 +566,8 @@ class Economy(commands.Cog):
embed.description = box(temp_msg, lang="md") embed.description = box(temp_msg, lang="md")
embed.set_footer( embed.set_footer(
text=footer_message.format( text=footer_message.format(
page_num=len(highscores) + 1, page_len=ceil(len(bank_sorted) / 10), page_num=len(highscores) + 1,
page_len=ceil(len(bank_sorted) / 10),
) )
) )
highscores.append(embed) highscores.append(embed)

View File

@ -248,14 +248,15 @@ class General(commands.Cog):
async def serverinfo(self, ctx, details: bool = False): async def serverinfo(self, ctx, details: bool = False):
""" """
Show server information. Show server information.
`details`: Shows more information when set to `True`. `details`: Shows more information when set to `True`.
Default to False. Default to False.
""" """
guild = ctx.guild guild = ctx.guild
passed = (ctx.message.created_at - guild.created_at).days passed = (ctx.message.created_at - guild.created_at).days
created_at = _("Created on {date}. That's over {num} days ago!").format( created_at = _("Created on {date}. That's over {num} days ago!").format(
date=guild.created_at.strftime("%d %b %Y %H:%M"), num=humanize_number(passed), date=guild.created_at.strftime("%d %b %Y %H:%M"),
num=humanize_number(passed),
) )
online = humanize_number( online = humanize_number(
len([m.status for m in guild.members if m.status != discord.Status.offline]) len([m.status for m in guild.members if m.status != discord.Status.offline])

View File

@ -194,7 +194,7 @@ class Mod(
@commands.is_owner() @commands.is_owner()
async def movedeletedelay(self, ctx: commands.Context) -> None: async def movedeletedelay(self, ctx: commands.Context) -> None:
""" """
Move deletedelay settings to core Move deletedelay settings to core
""" """
all_guilds = await self.config.all_guilds() all_guilds = await self.config.all_guilds()
for guild_id, settings in all_guilds.items(): for guild_id, settings in all_guilds.items():

View File

@ -48,7 +48,7 @@ class GlobalUniqueObjectFinder(commands.Converter):
async for guild in AsyncIter(bot.guilds, steps=100) async for guild in AsyncIter(bot.guilds, steps=100)
] ]
objects = itertools.chain(bot.get_all_channels(), bot.users, bot.guilds, *all_roles,) objects = itertools.chain(bot.get_all_channels(), bot.users, bot.guilds, *all_roles)
maybe_matches = [] maybe_matches = []
async for obj in AsyncIter(objects, steps=100): async for obj in AsyncIter(objects, steps=100):

View File

@ -453,7 +453,7 @@ class Permissions(commands.Cog):
`<cog_or_command>` is the cog or command to remove the rule `<cog_or_command>` is the cog or command to remove the rule
from. This is case sensitive. from. This is case sensitive.
`<who_or_what>` is one or more users, channels or roles the rule is for. `<who_or_what>` is one or more users, channels or roles the rule is for.
""" """
if not who_or_what: if not who_or_what:
await ctx.send_help() await ctx.send_help()

View File

@ -27,7 +27,7 @@ class Reports(commands.Cog):
Users can open reports using `[p]report`. These are then sent Users can open reports using `[p]report`. These are then sent
to a channel in the server for staff, and the report creator to a channel in the server for staff, and the report creator
gets a DM. Both can be used to communicate. gets a DM. Both can be used to communicate.
""" """
default_guild_settings = {"output_channel": None, "active": False, "next_ticket": 1} default_guild_settings = {"output_channel": None, "active": False, "next_ticket": 1}

View File

@ -207,7 +207,9 @@ class Streams(commands.Cog):
await self.maybe_renew_twitch_bearer_token() await self.maybe_renew_twitch_bearer_token()
token = (await self.bot.get_shared_api_tokens("twitch")).get("client_id") token = (await self.bot.get_shared_api_tokens("twitch")).get("client_id")
stream = TwitchStream( stream = TwitchStream(
name=channel_name, token=token, bearer=self.ttv_bearer_cache.get("access_token", None), name=channel_name,
token=token,
bearer=self.ttv_bearer_cache.get("access_token", None),
) )
await self.check_online(ctx, stream) await self.check_online(ctx, stream)

View File

@ -314,7 +314,8 @@ class Warnings(commands.Cog):
for r, v in registered_reasons.items(): for r, v in registered_reasons.items():
if await ctx.embed_requested(): if await ctx.embed_requested():
em = discord.Embed( em = discord.Embed(
title=_("Reason: {name}").format(name=r), description=v["description"], title=_("Reason: {name}").format(name=r),
description=v["description"],
) )
em.add_field(name=_("Points"), value=str(v["points"])) em.add_field(name=_("Points"), value=str(v["points"]))
msg_list.append(em) msg_list.append(em)
@ -343,7 +344,9 @@ class Warnings(commands.Cog):
em = discord.Embed(title=_("Action: {name}").format(name=r["action_name"])) em = discord.Embed(title=_("Action: {name}").format(name=r["action_name"]))
em.add_field(name=_("Points"), value="{}".format(r["points"]), inline=False) em.add_field(name=_("Points"), value="{}".format(r["points"]), inline=False)
em.add_field( em.add_field(
name=_("Exceed command"), value=r["exceed_command"], inline=False, name=_("Exceed command"),
value=r["exceed_command"],
inline=False,
) )
em.add_field(name=_("Drop command"), value=r["drop_command"], inline=False) em.add_field(name=_("Drop command"), value=r["drop_command"], inline=False)
msg_list.append(em) msg_list.append(em)
@ -436,7 +439,10 @@ class Warnings(commands.Cog):
title = _("Warning from {user}").format(user=ctx.author) title = _("Warning from {user}").format(user=ctx.author)
else: else:
title = _("Warning") title = _("Warning")
em = discord.Embed(title=title, description=reason_type["description"],) em = discord.Embed(
title=title,
description=reason_type["description"],
)
em.add_field(name=_("Points"), value=str(reason_type["points"])) em.add_field(name=_("Points"), value=str(reason_type["points"]))
try: try:
await user.send( await user.send(
@ -462,14 +468,18 @@ class Warnings(commands.Cog):
title = _("Warning from {user}").format(user=ctx.author) title = _("Warning from {user}").format(user=ctx.author)
else: else:
title = _("Warning") title = _("Warning")
em = discord.Embed(title=title, description=reason_type["description"],) em = discord.Embed(
title=title,
description=reason_type["description"],
)
em.add_field(name=_("Points"), value=str(reason_type["points"])) em.add_field(name=_("Points"), value=str(reason_type["points"]))
warn_channel = self.bot.get_channel(guild_settings["warn_channel"]) warn_channel = self.bot.get_channel(guild_settings["warn_channel"])
if warn_channel: if warn_channel:
if warn_channel.permissions_for(guild.me).send_messages: if warn_channel.permissions_for(guild.me).send_messages:
with contextlib.suppress(discord.HTTPException): with contextlib.suppress(discord.HTTPException):
await warn_channel.send( await warn_channel.send(
_("{user} has been warned.").format(user=user.mention), embed=em, _("{user} has been warned.").format(user=user.mention),
embed=em,
) )
if not dm_failed: if not dm_failed:

View File

@ -1422,8 +1422,10 @@ class RedBase(
await self._red_ready.wait() await self._red_ready.wait()
async def _delete_delay(self, ctx: commands.Context): async def _delete_delay(self, ctx: commands.Context):
"""Currently used for: """
* delete delay""" Currently used for:
* delete delay
"""
guild = ctx.guild guild = ctx.guild
if guild is None: if guild is None:
return return

View File

@ -235,7 +235,7 @@ def parse_cli_flags(args):
help="Set the maximum number of messages to store in the internal message cache.", help="Set the maximum number of messages to store in the internal message cache.",
) )
parser.add_argument( parser.add_argument(
"--no-message-cache", action="store_true", help="Disable the internal message cache.", "--no-message-cache", action="store_true", help="Disable the internal message cache."
) )
args = parser.parse_args(args) args = parser.parse_args(args)

View File

@ -1026,7 +1026,7 @@ class Cog(CogMixin, DPYCog, metaclass=DPYCogMeta):
.. warning:: .. warning::
None of your methods should start with ``red_`` or None of your methods should start with ``red_`` or
be dunder names which start with red (eg. ``__red_test_thing__``) be dunder names which start with red (eg. ``__red_test_thing__``)
unless to override behavior in a method designed to be overriden, unless to override behavior in a method designed to be overriden,
as this prefix is reserved for future methods in order to be as this prefix is reserved for future methods in order to be

View File

@ -75,7 +75,7 @@ def parse_timedelta(
""" """
This converts a user provided string into a timedelta This converts a user provided string into a timedelta
The units should be in order from largest to smallest. The units should be in order from largest to smallest.
This works with or without whitespace. This works with or without whitespace.
Parameters Parameters

View File

@ -623,7 +623,10 @@ class RedHelpFormatter(HelpFormatterABC):
@staticmethod @staticmethod
async def help_filter_func( async def help_filter_func(
ctx, objects: Iterable[SupportsCanSee], help_settings: HelpSettings, bypass_hidden=False, ctx,
objects: Iterable[SupportsCanSee],
help_settings: HelpSettings,
bypass_hidden=False,
) -> AsyncIterator[SupportsCanSee]: ) -> AsyncIterator[SupportsCanSee]:
""" """
This does most of actual filtering. This does most of actual filtering.

View File

@ -443,7 +443,7 @@ class Core(commands.commands._RuleDropper, commands.Cog, CoreLogic):
await ctx.send(embed=embed) await ctx.send(embed=embed)
else: else:
python_version = "{}.{}.{}".format(*sys.version_info[:3]) python_version = "{}.{}.{}".format(*sys.version_info[:3])
dpy_version = "{}".format(discord.__version__,) dpy_version = "{}".format(discord.__version__)
red_version = "{}".format(__version__) red_version = "{}".format(__version__)
about = _( about = _(

View File

@ -124,7 +124,7 @@ def cog_data_path(cog_instance=None, raw_name: str = None) -> Path:
Parameters Parameters
---------- ----------
cog_instance cog_instance
The instance of the cog you wish to get a data path for. The instance of the cog you wish to get a data path for.
If calling from a command or method of your cog, this should be ``self``. If calling from a command or method of your cog, this should be ``self``.
raw_name : str raw_name : str
The name of the cog to get a data path for. The name of the cog to get a data path for.

View File

@ -115,7 +115,7 @@ def init_events(bot, cli_flags):
"**we highly recommend you to read the update docs at <{docs}> and " "**we highly recommend you to read the update docs at <{docs}> and "
"make sure there is nothing else that " "make sure there is nothing else that "
"needs to be done during the update.**" "needs to be done during the update.**"
).format(docs="https://docs.discord.red/en/stable/update_red.html",) ).format(docs="https://docs.discord.red/en/stable/update_red.html")
if expected_version(current_python, py_version_req): if expected_version(current_python, py_version_req):
installed_extras = [] installed_extras = []
for extra, reqs in red_pkg._dep_map.items(): for extra, reqs in red_pkg._dep_map.items():
@ -142,8 +142,10 @@ def init_events(bot, cli_flags):
if platform.system() == "Windows" if platform.system() == "Windows"
else _("Terminal") else _("Terminal")
) )
extra_update += '```"{python}" -m pip install -U Red-DiscordBot{package_extras}```'.format( extra_update += (
python=sys.executable, package_extras=package_extras '```"{python}" -m pip install -U Red-DiscordBot{package_extras}```'.format(
python=sys.executable, package_extras=package_extras
)
) )
else: else:
@ -222,7 +224,7 @@ def init_events(bot, cli_flags):
await ctx.send_help() await ctx.send_help()
elif isinstance(error, commands.ArgParserFailure): elif isinstance(error, commands.ArgParserFailure):
msg = _("`{user_input}` is not a valid value for `{command}`").format( msg = _("`{user_input}` is not a valid value for `{command}`").format(
user_input=error.user_input, command=error.cmd, user_input=error.user_input, command=error.cmd
) )
if error.custom_help_msg: if error.custom_help_msg:
msg += f"\n{error.custom_help_msg}" msg += f"\n{error.custom_help_msg}"

View File

@ -14,9 +14,9 @@ from .utils import AsyncIter
class PrefixManager: class PrefixManager:
def __init__(self, config: Config, cli_flags: Namespace): def __init__(self, config: Config, cli_flags: Namespace):
self._config: Config = config self._config: Config = config
self._global_prefix_overide: Optional[List[str]] = sorted( self._global_prefix_overide: Optional[List[str]] = (
cli_flags.prefix, reverse=True sorted(cli_flags.prefix, reverse=True) or None
) or None )
self._cached: Dict[Optional[int], List[str]] = {} self._cached: Dict[Optional[int], List[str]] = {}
async def get_prefixes(self, guild: Optional[discord.Guild] = None) -> List[str]: async def get_prefixes(self, guild: Optional[discord.Guild] = None) -> List[str]:

View File

@ -154,7 +154,7 @@ async def _sem_wrapper(sem, task):
def bounded_gather_iter( def bounded_gather_iter(
*coros_or_futures, limit: int = 4, semaphore: Optional[Semaphore] = None, *coros_or_futures, limit: int = 4, semaphore: Optional[Semaphore] = None
) -> Iterator[Awaitable[Any]]: ) -> Iterator[Awaitable[Any]]:
""" """
An iterator that returns tasks as they are ready, but limits the An iterator that returns tasks as they are ready, but limits the

View File

@ -169,7 +169,7 @@ async def close_menu(
def start_adding_reactions( def start_adding_reactions(
message: discord.Message, emojis: Iterable[_ReactableEmoji], message: discord.Message, emojis: Iterable[_ReactableEmoji]
) -> asyncio.Task: ) -> asyncio.Task:
"""Start adding reactions to a message. """Start adding reactions to a message.

View File

@ -87,7 +87,8 @@ docs =
postgres = postgres =
asyncpg==0.20.1 asyncpg==0.20.1
style = style =
black==19.10b0 black==20.8b1
mypy-extensions==0.4.3
pathspec==0.8.0 pathspec==0.8.0
regex==2020.7.14 regex==2020.7.14
toml==0.10.1 toml==0.10.1