Skip to content

Commit 90e7aab

Browse files
committed
Asynchronous sqlite
1 parent a0653ed commit 90e7aab

File tree

8 files changed

+115
-76
lines changed

8 files changed

+115
-76
lines changed

Diff for: launcher.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,11 @@ async def on_command_error(ctx: Interaction, exc) -> None:
7373
else:
7474
raise exc
7575

76-
def exit_handler():
77-
bot.db.commit()
76+
async def exit_handler():
77+
asyncio.run(bot.db.commit())
7878

79-
atexit.register(exit_handler)
79+
atexit.register(asyncio.run, (exit_handler,))
80+
await bot.db.build()
8081
await bot.start(bot.config.token)
8182

8283

Diff for: lib/bot/__init__.py

+29-23
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,46 @@
11
import asyncio
22
import json
33
import os
4-
from datetime import datetime
54
import random
5+
from datetime import datetime
66
from typing import Any
77

88
import discord
99
import psutil
1010
import tzlocal
1111
from apscheduler.schedulers.asyncio import AsyncIOScheduler
1212
from discord import Guild, Interaction, VoiceChannel
13-
from discord.app_commands import Command, CommandOnCooldown, MissingPermissions, BotMissingPermissions
13+
from discord.app_commands import Command
1414
from discord.embeds import Embed
15-
from discord.errors import NotFound, HTTPException, InteractionResponded
15+
from discord.errors import NotFound, InteractionResponded
1616
from discord.ext.commands import AutoShardedBot
1717
from discord.ext.commands.errors import CommandNotFound, BadArgument
18-
from discord import AutoShardedClient
1918

2019
from lib.config import Config
2120
from lib.db import DB
22-
from lib.errors import BotNotReady
23-
from lib.progress import Progress, Timer, Loading
21+
from lib.progress import Progress, Timer
2422
from lib.urban import UrbanDictionary
2523

2624
COMMAND_ERROR_REGEX = r"Command raised an exception: (.*?(?=: )): (.*)"
2725
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument, RuntimeError)
2826

2927

28+
def synchronize_async_helper(to_await):
29+
async_response = []
30+
31+
async def run_and_capture_result():
32+
r = await to_await
33+
async_response.append(r)
34+
35+
loop = asyncio.get_event_loop()
36+
loop.run_until_complete(run_and_capture_result())
37+
return async_response[0]
38+
39+
3040
class Bot(AutoShardedBot):
3141
def __init__(self, shards: list[int], version: str):
3242
self.config: Config = Config()
3343
self.db: DB = DB()
34-
self.db.build()
3544
self.cache: dict = dict()
3645
self.tasks = AsyncIOScheduler(timezone=str(tzlocal.get_localzone()))
3746
self.shards_ready = False
@@ -55,10 +64,10 @@ async def on_connect(self):
5564
await asyncio.sleep(.5)
5665
self.tree.copy_global_to(guild=discord.Object(id="1064582321728143421"))
5766
await self.tree.sync(guild=discord.Object(id="1064582321728143421"))
58-
self.register_guilds()
67+
await self.register_guilds()
5968
asyncio.ensure_future(self.monitor_shutdown())
6069
print(f"Signed into {self.user.display_name}#{self.user.discriminator}")
61-
# asyncio.ensure_future(self.timer.start())
70+
asyncio.ensure_future(self.timer.start())
6271

6372
async def on_shard_ready(self, shard_id):
6473
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,
@@ -72,11 +81,10 @@ async def on_interaction(self, ctx: Interaction):
7281
if isinstance(ctx.command, Command):
7382
name_list, options = self.get_name(ctx.data, [])
7483
name = " ".join(name_list)
75-
self.db.insert.commands(command_name=name, guild_id=ctx.guild_id, user_id=ctx.user.id, params=json.dumps(options), ts=datetime.now().timestamp())
76-
self.db.run(f"""INSERT INTO commands VALUES (?,?,?,?,?)""", name, ctx.guild_id,
77-
ctx.user.id, json.dumps(options), datetime.now().timestamp())
78-
79-
84+
self.db.insert.commands(command_name=name, guild_id=ctx.guild_id, user_id=ctx.user.id,
85+
params=json.dumps(options), ts=datetime.now().timestamp())
86+
await self.db.run(f"""INSERT INTO commands VALUES (?,?,?,?,?)""", name, ctx.guild_id,
87+
ctx.user.id, json.dumps(options), datetime.now().timestamp())
8088

8189
@staticmethod
8290
async def send(ctx: Interaction, *args, **kwargs):
@@ -87,7 +95,6 @@ async def send(ctx: Interaction, *args, **kwargs):
8795
embed.colour = color
8896
embed.set_footer(text="Made by Gccody")
8997
embed.timestamp = datetime.now()
90-
# embed.set_thumbnail(url=self.logo_path)
9198
kwargs['embed'] = embed
9299

93100
if ctx.is_expired():
@@ -105,28 +112,27 @@ async def send(ctx: Interaction, *args, **kwargs):
105112
async def monitor_shutdown(self):
106113
while True:
107114
if psutil.Process().status() == psutil.STATUS_ZOMBIE:
108-
# Perform cleanup actions, such as committing the database
109-
self.db.commit()
115+
await self.db.commit()
110116
break
111117
if psutil.process_iter(['pid', 'name']):
112118
for process in psutil.process_iter():
113119
if process.name() == 'shutdown.exe':
114-
self.db.commit()
120+
await self.db.commit()
115121
await self.close()
116122
exit()
117123
await asyncio.sleep(1)
118124

119-
def register_guilds(self):
125+
async def register_guilds(self):
120126
progress = Progress('Registering guilds', len(self.guilds))
121127
progress.start()
122128
for guild in self.guilds:
123-
self.db.insert.guilds(id=guild.id)
129+
await self.db.insert.guilds(id=guild.id)
124130
progress.next()
125131

126-
for guild in self.db.get.guilds():
132+
for guild in (await self.db.get.guilds()):
127133
if not self.get_guild(guild.id):
128-
self.db.delete.guilds(id=guild.id)
129-
self.db.commit()
134+
await self.db.delete.guilds(id=guild.id)
135+
await self.db.commit()
130136
self.ready = True
131137
self.tasks.start()
132138

Diff for: lib/cogs/Announcment.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,14 @@ async def announce_enable(self, ctx: Interaction, channel: Optional[discord.Text
3333
if not channel.permissions_for(await ctx.guild.fetch_member(self.bot.user.id)).send_messages:
3434
return await ctx.response.send_message(
3535
Embed(title=f">>> I can't send messages in channel: {channel.name} ({channel.id})", colour=0xff0000))
36-
self.bot.db.update.guilds(where=f'id={ctx.guild_id}', set_data={'a_id': channel.id})
36+
await self.bot.db.update.guilds(where=f'id={ctx.guild_id}', set_data={'a_id': channel.id})
3737
await self.bot.send(ctx, embed=Embed(
3838
title=f">>> Successfully Enabled Announcements in {channel.mention} ({channel.id})"))
3939

4040
@announce.command(name='disable', description='Disable bot announcements')
4141
@has_guild_permissions(manage_guild=True)
4242
async def announce_disable(self, ctx: Interaction):
43-
self.bot.db.update.guilds(where=f'id={ctx.guild_id}', set_data={'a_id': None})
43+
await self.bot.db.update.guilds(where=f'id={ctx.guild_id}', set_data={'a_id': None})
4444
await self.bot.send(ctx,
4545
embed=Embed(title=f">>> Successfully Disabled Announcements"))
4646

Diff for: lib/cogs/Handlers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def __init__(self, bot):
2020
# if isinstance(ctx.command, discord.app_commands.Command):
2121
# name_list, options = self.bot.get_name(ctx.data, [])
2222
# name = " ".join(name_list)
23-
# self.bot.db.run(f"""INSERT INTO commands VALUES (?,?,?,?,?)""", name, ctx.guild_id,
23+
# await self.bot.db.run(f"""INSERT INTO commands VALUES (?,?,?,?,?)""", name, ctx.guild_id,
2424
# ctx.user.id, json.dumps(options), datetime.now().timestamp())
2525

2626

Diff for: lib/cogs/Mod.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ async def ban_add(self, ctx: Interaction, member: discord.Member, delete_message
8585
elif isinstance(member, User):
8686
await ctx.guild.ban(user=member, delete_message_days=self.days[delete_messages] if delete_messages else 0,
8787
reason=f"{reason} | {ctx.user.display_name}#{ctx.user.discriminator}")
88-
self.bot.db.insert.bans(guild_id=ctx.guild_id, user_id=member.id, mod_id=ctx.user.id, reason=reason,
88+
await self.bot.db.insert.bans(guild_id=ctx.guild_id, user_id=member.id, mod_id=ctx.user.id, reason=reason,
8989
ts=datetime.now().timestamp())
9090
embed = Embed(title=f"✅ | {member.display_name}#{member.discriminator} ({member.id}) has been banned")
9191
await ctx.response.send_message(embed=embed)
@@ -108,7 +108,7 @@ async def ban_remove(self, ctx: Interaction, id: str, reason: Optional[str] = "N
108108
return await ctx.response.send_message(
109109
embed=Embed(title=f":x: | That member is already unbanned", colour=0xff0000))
110110
await ctx.guild.unban(user=member, reason=reason)
111-
self.bot.db.delete.bans(guild_id=ctx.guild_id, user_id=member.id)
111+
await self.bot.db.delete.bans(guild_id=ctx.guild_id, user_id=member.id)
112112
await ctx.response.send_message(
113113
embed=Embed(title=f"✅ | {member.display_name}#{member.discriminator} ({member.id}) has been unbanned"))
114114

@@ -145,7 +145,7 @@ async def massban_add(self, ctx: Interaction, str_members: str, delete_messages:
145145
continue
146146
await member.ban(delete_message_days=self.days[delete_messages],
147147
reason=f"{reason} | {ctx.user.display_name}#{ctx.user.discriminator}")
148-
self.bot.db.insert.bans(guild_id=ctx.guild_id, user_id=member.id, mod_id=ctx.user.id, reason=reason,
148+
await self.bot.db.insert.bans(guild_id=ctx.guild_id, user_id=member.id, mod_id=ctx.user.id, reason=reason,
149149
ts=datetime.now().timestamp())
150150
success.append(f"{member.display_name}#{member.discriminator} ({id})")
151151
embed = Embed()
@@ -181,7 +181,7 @@ async def massban_remove(self, ctx: Interaction, str_members: str, reason: Optio
181181
continue
182182

183183
await member.unban(reason=f"{reason} | {ctx.user.display_name}#{ctx.user.discriminator}")
184-
self.bot.db.delete.bans(guild_id=ctx.guild_id, user_id=member.id)
184+
await self.bot.db.delete.bans(guild_id=ctx.guild_id, user_id=member.id)
185185
success.append(f"{member.display_name}#{member.discriminator} ({id})")
186186
embed = Embed()
187187
s_users = "\n".join(success)

Diff for: lib/cogs/Youtube.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ async def youtube_notify(self, ctx: Interaction, handle: str, message: Optional[
3636
elif res.status not in range(200, 300):
3737
return await ctx.response.send_message(embed=Embed(title=':x: | Something went wrong', colour=0xff0000))
3838

39-
user = self.bot.db.get.youtube(handle=handle, guild_id=ctx.guild_id)
39+
user = await self.bot.db.get.youtube(handle=handle, guild_id=ctx.guild_id)
4040
if user:
4141
return await ctx.response.send_message(embed=Embed(title=':x: | Already watching for new videos', colour=0xff0000))
4242

@@ -47,7 +47,7 @@ async def youtube_notify(self, ctx: Interaction, handle: str, message: Optional[
4747
latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
4848
except AttributeError:
4949
latest_video_url = ""
50-
self.bot.db.insert.youtube(handle=handle, guild_id=ctx.guild_id, message=message if message else f"@{handle} has uploaded a video", latest_url=latest_video_url)
50+
await self.bot.db.insert.youtube(handle=handle, guild_id=ctx.guild_id, message=message if message else f"@{handle} has uploaded a video", latest_url=latest_video_url)
5151
await ctx.response.send_message(embed=Embed(title=f'✅ | Waiting for @{handle} to post more videos'))
5252
self.bot.tasks.add_job(id=f"{handle}|{ctx.guild_id}", args=(handle, message, ctx.guild_id,), trigger='interval',
5353
minutes=1)

0 commit comments

Comments
 (0)