1
1
import asyncio
2
+ import json
2
3
import os
3
-
4
- import psutil
5
- from apscheduler .schedulers .asyncio import AsyncIOScheduler
6
- import tzlocal
7
-
8
4
from datetime import datetime
9
- import json
5
+ from http . client import HTTPException
10
6
from typing import Any
11
7
12
8
import discord
9
+ import psutil
10
+ import tzlocal
11
+ from apscheduler .schedulers .asyncio import AsyncIOScheduler
12
+ from discord import Interaction , Guild
13
+ from discord .embeds import Embed
14
+ from discord .errors import NotFound
13
15
from discord .ext .commands import AutoShardedBot as BaseBot
14
16
from discord .ext .commands .errors import CommandNotFound , BadArgument , MissingRequiredArgument , CommandOnCooldown , \
15
17
MissingPermissions , BotMissingPermissions
16
- from discord .errors import NotFound
17
- from http .client import HTTPException
18
- from discord .embeds import Embed
18
+
19
19
from lib .config import Config
20
- from lib .db import DB
21
- from discord import Interaction , Guild
22
20
from lib .context import CustomContext
23
- from lib .urban import UrbanDictionary
21
+ from lib .db import DB
24
22
from lib .progress import Progress
23
+ from lib .urban import UrbanDictionary
25
24
26
25
COMMAND_ERROR_REGEX = r"Command raised an exception: (.*?(?=: )): (.*)"
27
26
IGNORE_EXCEPTIONS = (CommandNotFound , BadArgument , RuntimeError )
@@ -34,37 +33,35 @@ def __init__(self, shards: list[int], version: str):
34
33
self .db .build ()
35
34
self .cache : dict = dict ()
36
35
self .tasks = AsyncIOScheduler (timezone = str (tzlocal .get_localzone ()))
37
- self .logged_in = False
38
36
self .shards_ready = False
39
37
self .ready = False
40
38
self .expected_shards = len (shards )
39
+ self .shard_progress = Progress ('Shards Ready' , self .expected_shards )
41
40
self .urban : UrbanDictionary = UrbanDictionary ()
42
41
self .VERSION = version
43
42
super ().__init__ (
44
- owner_id = "507214515641778187" ,
45
- shards = shards ,
46
- intents = discord .Intents .all (),
47
- debug_guilds = ["1064582321728143421" ],
48
- description = "Misc Bot used for advanced moderation and guild customization" )
43
+ owner_id = "507214515641778187" ,
44
+ shards = shards ,
45
+ intents = discord .Intents .all (),
46
+ debug_guilds = ["1064582321728143421" ],
47
+ description = "Misc Bot used for advanced moderation and guild customization" )
49
48
self .tasks .add_job (self .db .commit , trigger = 'interval' , minutes = 30 )
49
+ self .shard_progress .start ()
50
50
51
51
async def on_connect (self ):
52
- self .tasks .start ()
53
52
await self .sync_commands ()
53
+ while not self .shards_ready :
54
+ await asyncio .sleep (.5 )
54
55
print (f"Signed into { self .user .display_name } #{ self .user .discriminator } " )
55
- self .logged_in = True
56
- if self .shards_ready and self .logged_in :
57
- self .register_guilds ()
56
+ self .register_guilds ()
58
57
59
58
async def on_shard_ready (self , shard_id ):
60
59
await self .change_presence (activity = discord .Activity (type = discord .ActivityType .watching ,
61
60
name = f"SHARD { shard_id } " ),
62
61
shard_id = shard_id )
63
- print ( f"Shard Ready [ { shard_id + 1 } / { self .shard_count } ]" )
64
- if shard_id + 1 == self .expected_shards :
62
+ self .shard_progress . next ( )
63
+ if shard_id + 1 == self .expected_shards :
65
64
self .shards_ready = True
66
- if self .shards_ready and self .logged_in :
67
- self .register_guilds ()
68
65
69
66
def register_guilds (self ):
70
67
progress = Progress ('Registering guilds' , len (self .guilds ))
@@ -73,16 +70,14 @@ def register_guilds(self):
73
70
progress .next ()
74
71
self .db .commit ()
75
72
self .ready = True
73
+ self .tasks .start ()
76
74
print ('\n Everything is ready!' )
77
75
78
76
async def get_application_context (
79
- self , interaction : Interaction , cls = CustomContext
77
+ self , interaction : Interaction , cls = CustomContext
80
78
):
81
79
return await super ().get_application_context (interaction , cls = cls )
82
80
83
- async def on_disconnect (self ):
84
- print (f"Bot Disconnected, Retrying to sign into user { self .user .display_name } #{ self .user .discriminator } " )
85
-
86
81
async def on_guild_join (self , guild : Guild ):
87
82
self .db .execute ("""INSERT OR IGNORE INTO guilds VALUES (?,?,?)""" , guild .id , None , None )
88
83
@@ -115,7 +110,8 @@ async def on_interaction(self, interaction: discord.Interaction):
115
110
if interaction .is_command ():
116
111
name_list , options = self .get_name (interaction .data , [])
117
112
name = " " .join (name_list )
118
- self .db .execute (f"""INSERT INTO commands VALUES (?,?,?,?,?)""" , name , interaction .guild_id , interaction .user .id , json .dumps (options ), datetime .now ().timestamp ())
113
+ self .db .execute (f"""INSERT INTO commands VALUES (?,?,?,?,?)""" , name , interaction .guild_id ,
114
+ interaction .user .id , json .dumps (options ), datetime .now ().timestamp ())
119
115
return await super ().on_interaction (interaction = interaction )
120
116
121
117
async def on_application_command_error (self , ctx : CustomContext , exc ) -> None :
@@ -137,7 +133,8 @@ async def on_application_command_error(self, ctx: CustomContext, exc) -> None:
137
133
embed : Embed = Embed (title = "Http Error" , description = 'Message failed to send' , colour = 0xff0000 )
138
134
await ctx .respond (embed = embed )
139
135
elif isinstance (exc , NotFound ):
140
- await ctx .respond (embed = Embed (title = 'Not Found Error' , description = 'One or more items could not be found.' , colour = 0xff0000 ))
136
+ await ctx .respond (embed = Embed (title = 'Not Found Error' , description = 'One or more items could not be found.' ,
137
+ colour = 0xff0000 ))
141
138
elif hasattr (exc , "original" ):
142
139
if isinstance (exc .original , HTTPException ):
143
140
embed : Embed = Embed (title = "Http Error" , description = 'Message failed to send' , colour = 0xff0000 )
@@ -159,4 +156,3 @@ async def cpu_percent(interval=None, *args, **kwargs):
159
156
python_process .cpu_percent (* args , ** kwargs )
160
157
await asyncio .sleep (interval )
161
158
return psutil .cpu_percent (* args , ** kwargs )
162
-
0 commit comments