Skip to content

Commit 8f7d020

Browse files
committed
Black/lint
1 parent 0bc17a8 commit 8f7d020

File tree

7 files changed

+101
-54
lines changed

7 files changed

+101
-54
lines changed

bot.py

Lines changed: 41 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,9 @@ def __init__(self):
8686
try:
8787
self.db = AsyncIOMotorClient(mongo_uri).modmail_bot
8888
except ConfigurationError as e:
89-
logger.critical("Your MONGO_URI is copied wrong, try re-copying from the source again.")
89+
logger.critical(
90+
"Your MONGO_URI is copied wrong, try re-copying from the source again."
91+
)
9092
logger.critical(str(e))
9193
sys.exit(0)
9294

@@ -213,7 +215,9 @@ def owner_ids(self):
213215
owner_ids = set(map(int, str(owner_ids).split(",")))
214216
if self.owner_id is not None:
215217
owner_ids.add(self.owner_id)
216-
permissions = self.config["level_permissions"].get(PermissionLevel.OWNER.name, [])
218+
permissions = self.config["level_permissions"].get(
219+
PermissionLevel.OWNER.name, []
220+
)
217221
for perm in permissions:
218222
owner_ids.add(int(perm))
219223
return owner_ids
@@ -230,13 +234,16 @@ def log_channel(self) -> typing.Optional[discord.TextChannel]:
230234
channel = self.get_channel(int(channel_id))
231235
if channel is not None:
232236
return channel
233-
logger.debug('LOG_CHANNEL_ID was invalid, removed.')
237+
logger.debug("LOG_CHANNEL_ID was invalid, removed.")
234238
self.config.remove("log_channel_id")
235239
if self.main_category is not None:
236240
try:
237241
channel = self.main_category.channels[0]
238242
self.config["log_channel_id"] = channel.id
239-
logger.warning("No log channel set, setting #%s to be the log channel.", channel.name)
243+
logger.warning(
244+
"No log channel set, setting #%s to be the log channel.",
245+
channel.name,
246+
)
240247
return channel
241248
except IndexError:
242249
pass
@@ -268,7 +275,9 @@ def aliases(self) -> typing.Dict[str, str]:
268275
def token(self) -> str:
269276
token = self.config["token"]
270277
if token is None:
271-
logger.critical("TOKEN must be set, set this as bot token found on the Discord Dev Portal.")
278+
logger.critical(
279+
"TOKEN must be set, set this as bot token found on the Discord Dev Portal."
280+
)
272281
sys.exit(0)
273282
return token
274283

@@ -321,11 +330,13 @@ def main_category(self) -> typing.Optional[discord.CategoryChannel]:
321330
if cat is not None:
322331
return cat
323332
self.config.remove("main_category_id")
324-
logger.debug('MAIN_CATEGORY_ID was invalid, removed.')
333+
logger.debug("MAIN_CATEGORY_ID was invalid, removed.")
325334
cat = discord.utils.get(self.modmail_guild.categories, name="Modmail")
326335
if cat is not None:
327336
self.config["main_category_id"] = cat.id
328-
logger.debug("No main category set explicitly, setting category \"Modmail\" as the main category.")
337+
logger.debug(
338+
'No main category set explicitly, setting category "Modmail" as the main category.'
339+
)
329340
return cat
330341
return None
331342

@@ -404,7 +415,7 @@ async def setup_indexes(self):
404415
("key", "text"),
405416
]
406417
)
407-
logger.debug('Successfully set up database indexes.')
418+
logger.debug("Successfully set up database indexes.")
408419

409420
async def on_ready(self):
410421
"""Bot startup, sets uptime."""
@@ -413,7 +424,7 @@ async def on_ready(self):
413424
await self.wait_for_connected()
414425

415426
if self.guild is None:
416-
logger.debug('Logging out due to invalid GUILD_ID.')
427+
logger.debug("Logging out due to invalid GUILD_ID.")
417428
return await self.logout()
418429

419430
logger.line()
@@ -444,12 +455,12 @@ async def on_ready(self):
444455

445456
if not thread:
446457
# If the channel is deleted
447-
logger.debug('Failed to close thread for recipient %s.', recipient_id)
458+
logger.debug("Failed to close thread for recipient %s.", recipient_id)
448459
self.config["closures"].pop(recipient_id)
449460
await self.config.update()
450461
continue
451462

452-
logger.debug('Closing thread for recipient %s.', recipient_id)
463+
logger.debug("Closing thread for recipient %s.", recipient_id)
453464

454465
await thread.close(
455466
closer=self.get_user(items["closer_id"]),
@@ -579,7 +590,7 @@ async def _process_blocked(self, message: discord.Message) -> bool:
579590
reaction = blocked_emoji
580591
changed = False
581592
delta = human_timedelta(min_account_age)
582-
logger.debug('Blocked due to account age, user %s.', message.author.name)
593+
logger.debug("Blocked due to account age, user %s.", message.author.name)
583594

584595
if str(message.author.id) not in self.blocked_users:
585596
new_reason = (
@@ -603,7 +614,7 @@ async def _process_blocked(self, message: discord.Message) -> bool:
603614
reaction = blocked_emoji
604615
changed = False
605616
delta = human_timedelta(min_guild_age)
606-
logger.debug('Blocked due to guild age, user %s.', message.author.name)
617+
logger.debug("Blocked due to guild age, user %s.", message.author.name)
607618

608619
if str(message.author.id) not in self.blocked_users:
609620
new_reason = (
@@ -628,13 +639,15 @@ async def _process_blocked(self, message: discord.Message) -> bool:
628639
):
629640
# Met the age limit already, otherwise it would've been caught by the previous if's
630641
reaction = sent_emoji
631-
logger.debug('No longer internally blocked, user %s.', message.author.name)
642+
logger.debug(
643+
"No longer internally blocked, user %s.", message.author.name
644+
)
632645
self.blocked_users.pop(str(message.author.id))
633646
else:
634647
reaction = blocked_emoji
635648
end_time = re.search(r"%(.+?)%$", reason)
636649
if end_time is not None:
637-
logger.debug('No longer blocked, user %s.', message.author.name)
650+
logger.debug("No longer blocked, user %s.", message.author.name)
638651
after = (
639652
datetime.fromisoformat(end_time.group(1)) - now
640653
).total_seconds()
@@ -643,7 +656,7 @@ async def _process_blocked(self, message: discord.Message) -> bool:
643656
reaction = sent_emoji
644657
self.blocked_users.pop(str(message.author.id))
645658
else:
646-
logger.debug('User blocked, user %s.', message.author.name)
659+
logger.debug("User blocked, user %s.", message.author.name)
647660
else:
648661
reaction = sent_emoji
649662

@@ -652,7 +665,7 @@ async def _process_blocked(self, message: discord.Message) -> bool:
652665
try:
653666
await message.add_reaction(reaction)
654667
except (discord.HTTPException, discord.InvalidArgument):
655-
logger.warning('Failed to add reaction %s.', reaction, exc_info=True)
668+
logger.warning("Failed to add reaction %s.", reaction, exc_info=True)
656669
return str(message.author.id) in self.blocked_users
657670

658671
async def process_modmail(self, message: discord.Message) -> None:
@@ -839,9 +852,13 @@ async def on_raw_reaction_add(self, payload):
839852
if isinstance(channel, discord.DMChannel):
840853
if str(reaction) == str(close_emoji): # closing thread
841854
try:
842-
recipient_thread_close = strtobool(self.config["recipient_thread_close"])
855+
recipient_thread_close = strtobool(
856+
self.config["recipient_thread_close"]
857+
)
843858
except ValueError:
844-
recipient_thread_close = self.config.remove("recipient_thread_close")
859+
recipient_thread_close = self.config.remove(
860+
"recipient_thread_close"
861+
)
845862
if not recipient_thread_close:
846863
return
847864
thread = await self.threads.find(recipient=user)
@@ -875,7 +892,7 @@ async def on_guild_channel_delete(self, channel):
875892

876893
if isinstance(channel, discord.CategoryChannel):
877894
if self.main_category.id == channel.id:
878-
logger.debug('Main category was deleted.')
895+
logger.debug("Main category was deleted.")
879896
self.config.remove("main_category_id")
880897
await self.config.update()
881898
return
@@ -884,14 +901,14 @@ async def on_guild_channel_delete(self, channel):
884901
return
885902

886903
if self.log_channel is None or self.log_channel.id == channel.id:
887-
logger.info('Log channel deleted.')
904+
logger.info("Log channel deleted.")
888905
self.config.remove("log_channel_id")
889906
await self.config.update()
890907
return
891908

892909
thread = await self.threads.find(channel=channel)
893910
if thread:
894-
logger.debug('Manually closed channel %s.', channel.name)
911+
logger.debug("Manually closed channel %s.", channel.name)
895912
await thread.close(closer=mod, silent=True, delete_channel=False)
896913

897914
async def on_member_remove(self, member):
@@ -1062,7 +1079,8 @@ async def after_post_metadata(self):
10621079
if __name__ == "__main__":
10631080
try:
10641081
import uvloop
1065-
logger.debug('Setting up with uvloop.')
1082+
1083+
logger.debug("Setting up with uvloop.")
10661084
uvloop.install()
10671085
except ImportError:
10681086
pass

cogs/plugins.py

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ async def load_plugin(self, username, repo, plugin_name, branch):
136136
# so there's no terminal output unless there's an error
137137
except subprocess.CalledProcessError as exc:
138138
err = exc.stderr.decode("utf8").strip()
139-
logger.error('Error.', exc_info=True)
139+
logger.error("Error.", exc_info=True)
140140
if err:
141141
msg = f"Requirements Download Error: {username}/{repo}@{branch}[{plugin_name}]"
142142
logger.error(msg)
@@ -174,7 +174,9 @@ async def plugin_add(self, ctx, *, plugin_name: str):
174174

175175
if plugin_name in self.registry:
176176
details = self.registry[plugin_name]
177-
plugin_name = details["repository"] + "/" + plugin_name + "@" + details["branch"]
177+
plugin_name = (
178+
details["repository"] + "/" + plugin_name + "@" + details["branch"]
179+
)
178180

179181
required_version = details["bot_version"]
180182

@@ -213,7 +215,9 @@ async def plugin_add(self, ctx, *, plugin_name: str):
213215
await self.download_plugin_repo(username, repo, branch)
214216
except Exception as exc:
215217
if not isinstance(exc, DownloadError):
216-
logger.error('Unknown error when adding a plugin:', exc_info=True)
218+
logger.error(
219+
"Unknown error when adding a plugin:", exc_info=True
220+
)
217221
embed = discord.Embed(
218222
description=f"Unable to fetch this plugin from Github: `{exc}`.",
219223
color=self.bot.main_color,
@@ -226,7 +230,9 @@ async def plugin_add(self, ctx, *, plugin_name: str):
226230
await self.load_plugin(username, repo, name, branch)
227231
except Exception as exc:
228232
if not isinstance(exc, DownloadError):
229-
logger.error('Unknown error when adding a plugin:', exc_info=True)
233+
logger.error(
234+
"Unknown error when adding a plugin:", exc_info=True
235+
)
230236
embed = discord.Embed(
231237
description=f"Unable to load this plugin: `{exc}`.",
232238
color=self.bot.main_color,
@@ -249,7 +255,7 @@ async def plugin_add(self, ctx, *, plugin_name: str):
249255
else:
250256
embed = discord.Embed(
251257
description="Invalid plugin name format: use plugin-name or "
252-
"username/repo/plugin or username/repo/plugin@branch.",
258+
"username/repo/plugin or username/repo/plugin@branch.",
253259
color=self.bot.main_color,
254260
)
255261
await ctx.send(embed=embed)
@@ -272,7 +278,7 @@ async def plugin_remove(self, ctx, *, plugin_name: str):
272278
f"plugins.{username}-{repo}-{branch}.{name}.{name}"
273279
)
274280
except commands.ExtensionNotLoaded:
275-
logger.error('Plugin was never loaded.')
281+
logger.error("Plugin was never loaded.")
276282

277283
self.bot.config["plugins"].remove(plugin_name)
278284

@@ -291,8 +297,8 @@ def onerror(func, path, exc_info): # pylint: disable=W0613
291297
shutil.rmtree(
292298
f"plugins/{username}-{repo}-{branch}", onerror=onerror
293299
)
294-
except Exception as exc:
295-
logger.error('Failed to remove plugin %s.', plugin_name, exc_info=True)
300+
except Exception:
301+
logger.error("Failed to remove plugin %s.", plugin_name, exc_info=True)
296302
self.bot.config["plugins"].append(plugin_name)
297303
return
298304

@@ -316,7 +322,9 @@ async def plugin_update(self, ctx, *, plugin_name: str):
316322

317323
if plugin_name in self.registry:
318324
details = self.registry[plugin_name]
319-
plugin_name = details["repository"] + "/" + plugin_name + "@" + details["branch"]
325+
plugin_name = (
326+
details["repository"] + "/" + plugin_name + "@" + details["branch"]
327+
)
320328

321329
if plugin_name not in self.bot.config["plugins"]:
322330
embed = discord.Embed(
@@ -328,8 +336,10 @@ async def plugin_update(self, ctx, *, plugin_name: str):
328336
username, repo, name, branch = self.parse_plugin(plugin_name)
329337

330338
try:
331-
cmd = f"cd plugins/{username}-{repo}-{branch} && " \
339+
cmd = (
340+
f"cd plugins/{username}-{repo}-{branch} && "
332341
f"git reset --hard origin/{branch} && git fetch --all && git pull"
342+
)
333343
cmd = await self.bot.loop.run_in_executor(
334344
None, self._asubprocess_run, cmd
335345
)
@@ -340,7 +350,7 @@ async def plugin_update(self, ctx, *, plugin_name: str):
340350
description=f"An error occurred while updating: {err}.",
341351
color=self.bot.main_color,
342352
)
343-
logger.error('An error occurred while updating plugin:', exc_info=True)
353+
logger.error("An error occurred while updating plugin:", exc_info=True)
344354
await ctx.send(embed=embed)
345355

346356
else:
@@ -363,7 +373,9 @@ async def plugin_update(self, ctx, *, plugin_name: str):
363373
description=f"Unable to start the plugin: `{exc}`.",
364374
color=self.bot.main_color,
365375
)
366-
logger.error('An error occurred while updating plugin:', exc_info=True)
376+
logger.error(
377+
"An error occurred while updating plugin:", exc_info=True
378+
)
367379
await ctx.send(embed=embed)
368380

369381
@plugin.command(name="enabled", aliases=["installed"])
@@ -408,7 +420,9 @@ async def plugin_registry(self, ctx, *, plugin_name: typing.Union[int, str] = No
408420
if index >= len(registry):
409421
index = len(registry) - 1
410422
else:
411-
index = next((i for i, (n, _) in enumerate(registry) if plugin_name == n), 0)
423+
index = next(
424+
(i for i, (n, _) in enumerate(registry) if plugin_name == n), 0
425+
)
412426

413427
if not index and plugin_name is not None:
414428
embed = discord.Embed(

cogs/utility.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,8 @@ async def changelog(self, ctx, version: str.lower = ""):
246246
paginator = PaginatorSession(ctx, *changelog.embeds)
247247
paginator.current = index
248248
await paginator.run()
249+
except asyncio.CancelledError:
250+
pass
249251
except Exception:
250252
await ctx.send(changelog.CHANGELOG_URL)
251253

core/changelog.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,12 +120,15 @@ class Changelog:
120120
"https://raw.githubusercontent.com/kyb3r/modmail/master/CHANGELOG.md"
121121
)
122122
CHANGELOG_URL = "https://github.com/kyb3r/modmail/blob/master/CHANGELOG.md"
123-
VERSION_REGEX = re.compile(r"# ([vV]\d+\.\d+(?:\.\d+)?)(.*?(?=# (?:[vV]\d+\.\d+(?:\.\d+)?)|$))", flags=re.DOTALL)
123+
VERSION_REGEX = re.compile(
124+
r"# ([vV]\d+\.\d+(?:\.\d+)?)(.*?(?=# (?:[vV]\d+\.\d+(?:\.\d+)?)|$))",
125+
flags=re.DOTALL,
126+
)
124127

125128
def __init__(self, bot, text: str):
126129
self.bot = bot
127130
self.text = text
128-
logger.debug('Fetching changelog from GitHub.')
131+
logger.debug("Fetching changelog from GitHub.")
129132
self.versions = [Version(bot, *m) for m in self.VERSION_REGEX.findall(text)]
130133

131134
@property

core/clients.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,17 +88,17 @@ def logs(self):
8888
async def get_user_logs(self, user_id: Union[str, int]) -> list:
8989
query = {"recipient.id": str(user_id), "guild_id": str(self.bot.guild_id)}
9090
projection = {"messages": {"$slice": 5}}
91-
logger.debug('Retrieving user %s logs.', user_id)
91+
logger.debug("Retrieving user %s logs.", user_id)
9292

9393
return await self.logs.find(query, projection).to_list(None)
9494

9595
async def get_log(self, channel_id: Union[str, int]) -> dict:
96-
logger.debug('Retrieving channel %s logs.', channel_id)
96+
logger.debug("Retrieving channel %s logs.", channel_id)
9797
return await self.logs.find_one({"channel_id": str(channel_id)})
9898

9999
async def get_log_link(self, channel_id: Union[str, int]) -> str:
100100
doc = await self.get_log(channel_id)
101-
logger.debug('Retrieving log link for channel %s.', channel_id)
101+
logger.debug("Retrieving log link for channel %s.", channel_id)
102102
return f"{self.bot.config['log_url'].strip('/')}{self.bot.config['log_url_prefix']}/{doc['key']}"
103103

104104
async def create_log_entry(
@@ -134,13 +134,13 @@ async def create_log_entry(
134134
"messages": [],
135135
}
136136
)
137-
logger.debug('Created a log entry, key %s.', key)
137+
logger.debug("Created a log entry, key %s.", key)
138138
return f"{self.bot.config['log_url'].strip('/')}{self.bot.config['log_url_prefix']}/{key}"
139139

140140
async def get_config(self) -> dict:
141141
conf = await self.db.config.find_one({"bot_id": self.bot.user.id})
142142
if conf is None:
143-
logger.debug('Creating a new config entry for bot %s.', self.bot.user.id)
143+
logger.debug("Creating a new config entry for bot %s.", self.bot.user.id)
144144
await self.db.config.insert_one({"bot_id": self.bot.user.id})
145145
return {"bot_id": self.bot.user.id}
146146
return conf

0 commit comments

Comments
 (0)