1
1
import asyncio
2
2
import json
3
3
import os
4
- from datetime import datetime
5
4
import random
5
+ from datetime import datetime
6
6
from typing import Any
7
7
8
8
import discord
9
9
import psutil
10
10
import tzlocal
11
11
from apscheduler .schedulers .asyncio import AsyncIOScheduler
12
12
from discord import Guild , Interaction , VoiceChannel
13
- from discord .app_commands import Command , CommandOnCooldown , MissingPermissions , BotMissingPermissions
13
+ from discord .app_commands import Command
14
14
from discord .embeds import Embed
15
- from discord .errors import NotFound , HTTPException , InteractionResponded
15
+ from discord .errors import NotFound , InteractionResponded
16
16
from discord .ext .commands import AutoShardedBot
17
17
from discord .ext .commands .errors import CommandNotFound , BadArgument
18
- from discord import AutoShardedClient
19
18
20
19
from lib .config import Config
21
20
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
24
22
from lib .urban import UrbanDictionary
25
23
26
24
COMMAND_ERROR_REGEX = r"Command raised an exception: (.*?(?=: )): (.*)"
27
25
IGNORE_EXCEPTIONS = (CommandNotFound , BadArgument , RuntimeError )
28
26
29
27
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
+
30
40
class Bot (AutoShardedBot ):
31
41
def __init__ (self , shards : list [int ], version : str ):
32
42
self .config : Config = Config ()
33
43
self .db : DB = DB ()
34
- self .db .build ()
35
44
self .cache : dict = dict ()
36
45
self .tasks = AsyncIOScheduler (timezone = str (tzlocal .get_localzone ()))
37
46
self .shards_ready = False
@@ -55,10 +64,10 @@ async def on_connect(self):
55
64
await asyncio .sleep (.5 )
56
65
self .tree .copy_global_to (guild = discord .Object (id = "1064582321728143421" ))
57
66
await self .tree .sync (guild = discord .Object (id = "1064582321728143421" ))
58
- self .register_guilds ()
67
+ await self .register_guilds ()
59
68
asyncio .ensure_future (self .monitor_shutdown ())
60
69
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 ())
62
71
63
72
async def on_shard_ready (self , shard_id ):
64
73
await self .change_presence (activity = discord .Activity (type = discord .ActivityType .watching ,
@@ -72,11 +81,10 @@ async def on_interaction(self, ctx: Interaction):
72
81
if isinstance (ctx .command , Command ):
73
82
name_list , options = self .get_name (ctx .data , [])
74
83
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 ())
80
88
81
89
@staticmethod
82
90
async def send (ctx : Interaction , * args , ** kwargs ):
@@ -87,7 +95,6 @@ async def send(ctx: Interaction, *args, **kwargs):
87
95
embed .colour = color
88
96
embed .set_footer (text = "Made by Gccody" )
89
97
embed .timestamp = datetime .now ()
90
- # embed.set_thumbnail(url=self.logo_path)
91
98
kwargs ['embed' ] = embed
92
99
93
100
if ctx .is_expired ():
@@ -105,28 +112,27 @@ async def send(ctx: Interaction, *args, **kwargs):
105
112
async def monitor_shutdown (self ):
106
113
while True :
107
114
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 ()
110
116
break
111
117
if psutil .process_iter (['pid' , 'name' ]):
112
118
for process in psutil .process_iter ():
113
119
if process .name () == 'shutdown.exe' :
114
- self .db .commit ()
120
+ await self .db .commit ()
115
121
await self .close ()
116
122
exit ()
117
123
await asyncio .sleep (1 )
118
124
119
- def register_guilds (self ):
125
+ async def register_guilds (self ):
120
126
progress = Progress ('Registering guilds' , len (self .guilds ))
121
127
progress .start ()
122
128
for guild in self .guilds :
123
- self .db .insert .guilds (id = guild .id )
129
+ await self .db .insert .guilds (id = guild .id )
124
130
progress .next ()
125
131
126
- for guild in self .db .get .guilds ():
132
+ for guild in ( await self .db .get .guilds () ):
127
133
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 ()
130
136
self .ready = True
131
137
self .tasks .start ()
132
138
0 commit comments