Skip to content

Commit cbdf61f

Browse files
committed
Use tasks
1 parent 226b3dc commit cbdf61f

File tree

4 files changed

+60
-44
lines changed

4 files changed

+60
-44
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4343
- Dynamic attribute for configs are removed, must use `config['key']` or `config.get('key')`.
4444
- Removed helper functions `info()` and `error()` for formatting logging, it's formatted automatically now.
4545
- Bumped discord.py version to 1.2.3.
46+
- Use discord tasks for metadata loop.
4647

4748
# v3.0.3
4849

bot.py

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from types import SimpleNamespace
1212

1313
import discord
14-
from discord.ext import commands
14+
from discord.ext import commands, tasks
1515
from discord.ext.commands.view import StringView
1616

1717
import isodate
@@ -70,6 +70,7 @@ def __init__(self):
7070

7171
self.config = ConfigManager(self)
7272
self.config.populate_cache()
73+
7374
self.threads = ThreadManager(self)
7475

7576
self._configure_logging()
@@ -81,7 +82,8 @@ def __init__(self):
8182
self.db = AsyncIOMotorClient(mongo_uri).modmail_bot
8283
self.plugin_db = PluginDatabaseClient(self)
8384

84-
self.metadata_task = self.loop.create_task(self.metadata_loop())
85+
self.metadata_loop = None
86+
8587
self._load_extensions()
8688

8789
@property
@@ -183,12 +185,6 @@ def run(self, *args, **kwargs):
183185
except Exception:
184186
logger.critical("Fatal exception", exc_info=True)
185187
finally:
186-
try:
187-
self.metadata_task.cancel()
188-
self.loop.run_until_complete(self.metadata_task)
189-
except asyncio.CancelledError:
190-
logger.debug("metadata_task has been cancelled.")
191-
192188
self.loop.run_until_complete(self.logout())
193189
for task in asyncio.all_tasks(self.loop):
194190
task.cancel()
@@ -437,6 +433,19 @@ async def on_ready(self):
437433

438434
logger.line()
439435

436+
self.metadata_loop = tasks.Loop(
437+
self.post_metadata,
438+
seconds=0,
439+
minutes=0,
440+
hours=1,
441+
count=None,
442+
reconnect=True,
443+
loop=None,
444+
)
445+
self.metadata_loop.before_loop(self.before_post_metadata)
446+
self.metadata_loop.after_loop(self.after_post_metadata)
447+
self.metadata_loop.start()
448+
440449
async def convert_emoji(self, name: str) -> str:
441450
ctx = SimpleNamespace(bot=self, guild=self.modmail_guild)
442451
converter = commands.EmojiConverter()
@@ -958,7 +967,7 @@ async def validate_database_connection(self):
958967
try:
959968
await self.db.command("buildinfo")
960969
except Exception as exc:
961-
logger.critical("Something went wrong " "while connecting to the database.")
970+
logger.critical("Something went wrong while connecting to the database.")
962971
message = f"{type(exc).__name__}: {str(exc)}"
963972
logger.critical(message)
964973

@@ -981,43 +990,44 @@ async def validate_database_connection(self):
981990
else:
982991
logger.info("Successfully connected to the database.")
983992

984-
async def metadata_loop(self):
993+
async def post_metadata(self):
994+
owner = (await self.application_info()).owner
995+
data = {
996+
"owner_name": str(owner),
997+
"owner_id": owner.id,
998+
"bot_id": self.user.id,
999+
"bot_name": str(self.user),
1000+
"avatar_url": str(self.user.avatar_url),
1001+
"guild_id": self.guild_id,
1002+
"guild_name": self.guild.name,
1003+
"member_count": len(self.guild.members),
1004+
"uptime": (datetime.utcnow() - self.start_time).total_seconds(),
1005+
"latency": f"{self.ws.latency * 1000:.4f}",
1006+
"version": self.version,
1007+
"selfhosted": True,
1008+
"last_updated": str(datetime.utcnow()),
1009+
}
1010+
1011+
async with self.session.post("https://api.modmail.tk/metadata", json=data):
1012+
logger.debug("Uploading metadata to Modmail server.")
1013+
1014+
async def before_post_metadata(self):
1015+
logger.info("Starting metadata loop.")
9851016
await self.wait_for_connected()
9861017
if not self.guild:
987-
return
988-
989-
owner = (await self.application_info()).owner
1018+
self.metadata_loop.cancel()
9901019

991-
while not self.is_closed():
992-
data = {
993-
"owner_name": str(owner),
994-
"owner_id": owner.id,
995-
"bot_id": self.user.id,
996-
"bot_name": str(self.user),
997-
"avatar_url": str(self.user.avatar_url),
998-
"guild_id": self.guild_id,
999-
"guild_name": self.guild.name,
1000-
"member_count": len(self.guild.members),
1001-
"uptime": (datetime.utcnow() - self.start_time).total_seconds(),
1002-
"latency": f"{self.ws.latency * 1000:.4f}",
1003-
"version": self.version,
1004-
"selfhosted": True,
1005-
"last_updated": str(datetime.utcnow()),
1006-
}
1007-
1008-
async with self.session.post("https://api.modmail.tk/metadata", json=data):
1009-
logger.debug("Uploading metadata to Modmail server.")
1010-
1011-
await asyncio.sleep(3600)
1020+
async def after_post_metadata(self):
1021+
logger.info("Metadata loop has been cancelled.")
10121022

10131023

10141024
if __name__ == "__main__":
1015-
if os.name != "nt":
1016-
try:
1017-
import uvloop
1025+
try:
1026+
import uvloop
1027+
1028+
uvloop.install()
1029+
except ImportError:
1030+
pass
10181031

1019-
uvloop.install()
1020-
except ImportError:
1021-
pass
10221032
bot = ModmailBot()
10231033
bot.run()

cogs/utility.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ def cog_unload(self):
227227
@commands.command()
228228
@checks.has_permissions(PermissionLevel.REGULAR)
229229
@trigger_typing
230-
async def changelog(self, ctx, version: str.lower = ''):
230+
async def changelog(self, ctx, version: str.lower = ""):
231231
"""Shows the changelog of the Modmail."""
232232
changelog = await Changelog.from_url(self.bot)
233233
version = version.lstrip("vV") if version else changelog.latest_version.version

core/thread.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,9 @@ async def _close(
319319
else:
320320
message = self.bot.config["thread_close_response"]
321321

322-
message = message.format(closer=closer, loglink=log_url, logkey=log_data["key"] if log_data else None)
322+
message = message.format(
323+
closer=closer, loglink=log_url, logkey=log_data["key"] if log_data else None
324+
)
323325

324326
embed.description = message
325327
footer = self.bot.config["thread_close_footer"]
@@ -764,9 +766,12 @@ async def find(
764766
if recipient is None and channel is not None:
765767
thread = self._find_from_channel(channel)
766768
if thread is None:
767-
id, thread = next(((k, v) for k, v in self.cache.items() if v.channel == channel), (-1, None))
769+
id, thread = next(
770+
((k, v) for k, v in self.cache.items() if v.channel == channel),
771+
(-1, None),
772+
)
768773
if thread is not None:
769-
logger.debug('Found thread with tempered ID.')
774+
logger.debug("Found thread with tempered ID.")
770775
await channel.edit(topic=f"User ID: {id}")
771776
return thread
772777

0 commit comments

Comments
 (0)