Skip to content

Commit 94c422a

Browse files
authored
Merge pull request #298 from Dorukyum/master
Refactor and format discord/bot.py
2 parents 12e90dc + 4342418 commit 94c422a

File tree

1 file changed

+127
-55
lines changed

1 file changed

+127
-55
lines changed

discord/bot.py

Lines changed: 127 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,9 @@ def add_application_command(self, command: ApplicationCommand) -> None:
100100
command.guild_ids = self.debug_guilds
101101
self._pending_application_commands.append(command)
102102

103-
def remove_application_command(self, command: ApplicationCommand) -> Optional[ApplicationCommand]:
103+
def remove_application_command(
104+
self, command: ApplicationCommand
105+
) -> Optional[ApplicationCommand]:
104106
"""Remove a :class:`.ApplicationCommand` from the internal list
105107
of commands.
106108
@@ -155,7 +157,9 @@ async def register_commands(self) -> None:
155157
global_permissions: List = []
156158

157159
registered_commands = await self.http.get_global_commands(self.user.id)
158-
for command in [cmd for cmd in self.pending_application_commands if cmd.guild_ids is None]:
160+
for command in [
161+
cmd for cmd in self.pending_application_commands if cmd.guild_ids is None
162+
]:
159163
as_dict = command.to_dict()
160164
if len(registered_commands) > 0:
161165
matches = [
@@ -185,41 +189,64 @@ async def register_commands(self) -> None:
185189
update_guild_commands = {}
186190
async for guild in self.fetch_guilds(limit=None):
187191
update_guild_commands[guild.id] = []
188-
for command in [cmd for cmd in self.pending_application_commands if cmd.guild_ids is not None]:
192+
for command in [
193+
cmd
194+
for cmd in self.pending_application_commands
195+
if cmd.guild_ids is not None
196+
]:
189197
as_dict = command.to_dict()
190198
for guild_id in command.guild_ids:
191199
to_update = update_guild_commands[guild_id]
192200
update_guild_commands[guild_id] = to_update + [as_dict]
193201

194-
for guild_id in update_guild_commands:
202+
for guild_id, guild_data in update_guild_commands.items():
195203
try:
196-
cmds = await self.http.bulk_upsert_guild_commands(self.user.id, guild_id,
197-
update_guild_commands[guild_id])
204+
cmds = await self.http.bulk_upsert_guild_commands(
205+
self.user.id, guild_id, update_guild_commands[guild_id]
206+
)
198207

199208
# Permissions for this Guild
200209
guild_permissions: List = []
201210
except Forbidden:
202-
if not update_guild_commands[guild_id]:
211+
if not guild_data:
203212
continue
204-
else:
205-
print(f"Failed to add command to guild {guild_id}", file=sys.stderr)
206-
raise
213+
print(f"Failed to add command to guild {guild_id}", file=sys.stderr)
214+
raise
207215
else:
208216
for i in cmds:
209-
cmd = get(self.pending_application_commands, name=i["name"], description=i["description"],
210-
type=i['type'])
217+
cmd = get(
218+
self.pending_application_commands,
219+
name=i["name"],
220+
description=i["description"],
221+
type=i["type"],
222+
)
211223
self.application_commands[i["id"]] = cmd
212224

213225
# Permissions
214-
permissions = [perm.to_dict() for perm in cmd.permissions if perm.guild_id is None or (
215-
perm.guild_id == guild_id and perm.guild_id in cmd.guild_ids)]
216-
guild_permissions.append({"id": i["id"], "permissions": permissions})
226+
permissions = [
227+
perm.to_dict()
228+
for perm in cmd.permissions
229+
if perm.guild_id is None
230+
or (
231+
perm.guild_id == guild_id and perm.guild_id in cmd.guild_ids
232+
)
233+
]
234+
guild_permissions.append(
235+
{"id": i["id"], "permissions": permissions}
236+
)
217237

218238
for global_command in global_permissions:
219-
permissions = [perm.to_dict() for perm in global_command['permissions'] if
220-
perm.guild_id is None or (
221-
perm.guild_id == guild_id and perm.guild_id in cmd.guild_ids)]
222-
guild_permissions.append({"id": global_command["id"], "permissions": permissions})
239+
permissions = [
240+
perm.to_dict()
241+
for perm in global_command["permissions"]
242+
if perm.guild_id is None
243+
or (
244+
perm.guild_id == guild_id and perm.guild_id in cmd.guild_ids
245+
)
246+
]
247+
guild_permissions.append(
248+
{"id": global_command["id"], "permissions": permissions}
249+
)
223250

224251
# Collect & Upsert Permissions for Each Guild
225252
# Command Permissions for this Guild
@@ -231,47 +258,78 @@ async def register_commands(self) -> None:
231258

232259
# Replace Role / Owner Names with IDs
233260
for permission in item["permissions"]:
234-
if isinstance(permission['id'], str):
261+
if isinstance(permission["id"], str):
235262
# Replace Role Names
236-
if permission['type'] == 1 and isinstance(permission['id'], str):
237-
role = get(self.get_guild(guild_id).roles, name=permission['id'])
263+
if permission["type"] == 1:
264+
role = get(
265+
self.get_guild(guild_id).roles,
266+
name=permission["id"],
267+
)
238268

239269
# If not missing
240-
if not role is None:
270+
if role is not None:
241271
new_cmd_perm["permissions"].append(
242-
{"id": role.id, "type": 1, "permission": permission['permission']})
272+
{
273+
"id": role.id,
274+
"type": 1,
275+
"permission": permission["permission"],
276+
}
277+
)
243278
else:
244-
print("No Role ID found in Guild ({guild_id}) for Role ({role})".format(
245-
guild_id=guild_id, role=permission['id']))
246-
# Add Owner IDs
247-
elif permission['type'] == 2 and permission['id'] == "owner":
279+
print(
280+
"No Role ID found in Guild ({guild_id}) for Role ({role})".format(
281+
guild_id=guild_id, role=permission["id"]
282+
)
283+
)
284+
# Add owner IDs
285+
elif (
286+
permission["type"] == 2 and permission["id"] == "owner"
287+
):
248288
app = await self.application_info() # type: ignore
249289
if app.team:
250290
for m in app.team.members:
251291
new_cmd_perm["permissions"].append(
252-
{"id": m.id, "type": 2, "permission": permission['permission']})
292+
{
293+
"id": m.id,
294+
"type": 2,
295+
"permission": permission["permission"],
296+
}
297+
)
253298
else:
254299
new_cmd_perm["permissions"].append(
255-
{"id": app.owner.id, "type": 2, "permission": permission['permission']})
256-
# Add the Rest
300+
{
301+
"id": app.owner.id,
302+
"type": 2,
303+
"permission": permission["permission"],
304+
}
305+
)
306+
# Add the rest
257307
else:
258308
new_cmd_perm["permissions"].append(permission)
259309

260310
# Make sure we don't have over 10 overwrites
261-
if len(new_cmd_perm['permissions']) > 10:
311+
if len(new_cmd_perm["permissions"]) > 10:
262312
print(
263313
"Command '{name}' has more than 10 permission overrides in guild ({guild_id}).\nwill only use the first 10 permission overrides.".format(
264-
name=self.application_commands[new_cmd_perm['id']].name, guild_id=guild_id))
265-
new_cmd_perm['permissions'] = new_cmd_perm['permissions'][:10]
314+
name=self.application_commands[new_cmd_perm["id"]].name,
315+
guild_id=guild_id,
316+
)
317+
)
318+
new_cmd_perm["permissions"] = new_cmd_perm["permissions"][:10]
266319

267320
# Append to guild_cmd_perms
268321
guild_cmd_perms.append(new_cmd_perm)
269322

270323
# Upsert
271324
try:
272-
await self.http.bulk_upsert_command_permissions(self.user.id, guild_id, guild_cmd_perms)
325+
await self.http.bulk_upsert_command_permissions(
326+
self.user.id, guild_id, guild_cmd_perms
327+
)
273328
except Forbidden:
274-
print(f"Failed to add command permissions to guild {guild_id}", file=sys.stderr)
329+
print(
330+
f"Failed to add command permissions to guild {guild_id}",
331+
file=sys.stderr,
332+
)
275333
raise
276334

277335
async def process_application_commands(self, interaction: Interaction) -> None:
@@ -306,16 +364,16 @@ async def process_application_commands(self, interaction: Interaction) -> None:
306364
else:
307365
ctx = await self.get_application_context(interaction)
308366
ctx.command = command
309-
self.dispatch('application_command', ctx)
367+
self.dispatch("application_command", ctx)
310368
try:
311369
if await self.can_run(ctx, call_once=True):
312370
await ctx.command.invoke(ctx)
313371
else:
314-
raise CheckFailure('The global check once functions failed.')
372+
raise CheckFailure("The global check once functions failed.")
315373
except DiscordException as exc:
316374
await ctx.command.dispatch_error(ctx, exc)
317375
else:
318-
self.dispatch('application_command_completion', ctx)
376+
self.dispatch("application_command_completion", ctx)
319377

320378
def slash_command(self, **kwargs):
321379
"""A shortcut decorator that invokes :func:`.ApplicationCommandMixin.command` and adds it to
@@ -400,7 +458,9 @@ def command(self, **kwargs):
400458
"""
401459
return self.application_command(**kwargs)
402460

403-
def command_group(self, name: str, description: str, guild_ids=None) -> SlashCommandGroup:
461+
def command_group(
462+
self, name: str, description: str, guild_ids=None
463+
) -> SlashCommandGroup:
404464
# TODO: Write documentation for this. I'm not familiar enough with what this function does to do it myself.
405465
group = SlashCommandGroup(name, description, guild_ids)
406466
self.add_application_command(group)
@@ -451,24 +511,30 @@ def __init__(self, description=None, *args, **options):
451511
self._check_once = []
452512
self._before_invoke = None
453513
self._after_invoke = None
454-
self.description = inspect.cleandoc(description) if description else ''
455-
self.owner_id = options.get('owner_id')
456-
self.owner_ids = options.get('owner_ids', set())
514+
self.description = inspect.cleandoc(description) if description else ""
515+
self.owner_id = options.get("owner_id")
516+
self.owner_ids = options.get("owner_ids", set())
457517

458-
self.debug_guild = options.pop("debug_guild", None) # TODO: remove or reimplement
518+
self.debug_guild = options.pop(
519+
"debug_guild", None
520+
) # TODO: remove or reimplement
459521
self.debug_guilds = options.pop("debug_guilds", None)
460522

461523
if self.owner_id and self.owner_ids:
462-
raise TypeError('Both owner_id and owner_ids are set.')
524+
raise TypeError("Both owner_id and owner_ids are set.")
463525

464-
if self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection):
465-
raise TypeError(f'owner_ids must be a collection not {self.owner_ids.__class__!r}')
526+
if self.owner_ids and not isinstance(
527+
self.owner_ids, collections.abc.Collection
528+
):
529+
raise TypeError(
530+
f"owner_ids must be a collection not {self.owner_ids.__class__!r}"
531+
)
466532

467533
if self.debug_guild:
468534
if self.debug_guilds is None:
469535
self.debug_guilds = [self.debug_guild]
470536
else:
471-
raise TypeError('Both debug_guild and debug_guilds are set.')
537+
raise TypeError("Both debug_guild and debug_guilds are set.")
472538

473539
self._checks = []
474540
self._check_once = []
@@ -481,7 +547,9 @@ async def on_connect(self):
481547
async def on_interaction(self, interaction):
482548
await self.process_application_commands(interaction)
483549

484-
async def on_application_command_error(self, context: ApplicationContext, exception: DiscordException) -> None:
550+
async def on_application_command_error(
551+
self, context: ApplicationContext, exception: DiscordException
552+
) -> None:
485553
"""|coro|
486554
487555
The default command error handler provided by the bot.
@@ -504,8 +572,10 @@ async def on_application_command_error(self, context: ApplicationContext, except
504572
# if cog and cog.has_error_handler():
505573
# return
506574

507-
print(f'Ignoring exception in command {context.command}:', file=sys.stderr)
508-
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
575+
print(f"Ignoring exception in command {context.command}:", file=sys.stderr)
576+
traceback.print_exception(
577+
type(exception), exception, exception.__traceback__, file=sys.stderr
578+
)
509579

510580
# global check registration
511581
# TODO: Remove these from commands.Bot
@@ -611,7 +681,9 @@ def whitelist(ctx):
611681
self.add_check(func, call_once=True)
612682
return func
613683

614-
async def can_run(self, ctx: ApplicationContext, *, call_once: bool = False) -> bool:
684+
async def can_run(
685+
self, ctx: ApplicationContext, *, call_once: bool = False
686+
) -> bool:
615687
data = self._check_once if call_once else self._checks
616688

617689
if len(data) == 0:
@@ -620,7 +692,6 @@ async def can_run(self, ctx: ApplicationContext, *, call_once: bool = False) ->
620692
# type-checker doesn't distinguish between functions and methods
621693
return await async_all(f(ctx) for f in data) # type: ignore
622694

623-
624695
def before_invoke(self, coro):
625696
"""A decorator that registers a coroutine as a pre-invoke hook.
626697
A pre-invoke hook is called directly before the command is
@@ -646,7 +717,7 @@ def before_invoke(self, coro):
646717
The coroutine passed is not actually a coroutine.
647718
"""
648719
if not asyncio.iscoroutinefunction(coro):
649-
raise TypeError('The pre-invoke hook must be a coroutine.')
720+
raise TypeError("The pre-invoke hook must be a coroutine.")
650721

651722
self._before_invoke = coro
652723
return coro
@@ -678,11 +749,12 @@ def after_invoke(self, coro):
678749
679750
"""
680751
if not asyncio.iscoroutinefunction(coro):
681-
raise TypeError('The post-invoke hook must be a coroutine.')
752+
raise TypeError("The post-invoke hook must be a coroutine.")
682753

683754
self._after_invoke = coro
684755
return coro
685756

757+
686758
class Bot(BotBase, Client):
687759
"""Represents a discord bot.
688760

0 commit comments

Comments
 (0)