Skip to content

Commit b323049

Browse files
committed
Better Startup
1 parent 550109e commit b323049

File tree

5 files changed

+41
-35
lines changed

5 files changed

+41
-35
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,3 +150,4 @@ cython_debug/
150150
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
151151
.idea/
152152
*.db
153+
*.db-journal

launcher.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
import atexit
23
import glob
34
import sys
@@ -10,6 +11,7 @@
1011
from lib.bot import Bot
1112
from lib.config import Config
1213
from lib.progress import Progress
14+
from asyncer import asyncify
1315

1416
COGS = [path.split("\\")[-1][:-3] if "\\" in path else path.split("/")[-1][:-3] for path in
1517
glob.glob('./lib/cogs/*.py')]
@@ -27,7 +29,7 @@ def start(cluster_id: int):
2729
progress = Progress("Registering Cogs", len(COGS))
2830
for index, cog in enumerate(COGS):
2931
bot.load_extension(f"lib.cogs.{cog}")
30-
sleep(.2)
32+
# sleep(.2)
3133
progress.next()
3234
atexit.register(bot.db.commit)
3335
bot.run(bot.config.token)

lib/bot/__init__.py

Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
import asyncio
2+
import json
23
import os
3-
4-
import psutil
5-
from apscheduler.schedulers.asyncio import AsyncIOScheduler
6-
import tzlocal
7-
84
from datetime import datetime
9-
import json
5+
from http.client import HTTPException
106
from typing import Any
117

128
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
1315
from discord.ext.commands import AutoShardedBot as BaseBot
1416
from discord.ext.commands.errors import CommandNotFound, BadArgument, MissingRequiredArgument, CommandOnCooldown, \
1517
MissingPermissions, BotMissingPermissions
16-
from discord.errors import NotFound
17-
from http.client import HTTPException
18-
from discord.embeds import Embed
18+
1919
from lib.config import Config
20-
from lib.db import DB
21-
from discord import Interaction, Guild
2220
from lib.context import CustomContext
23-
from lib.urban import UrbanDictionary
21+
from lib.db import DB
2422
from lib.progress import Progress
23+
from lib.urban import UrbanDictionary
2524

2625
COMMAND_ERROR_REGEX = r"Command raised an exception: (.*?(?=: )): (.*)"
2726
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument, RuntimeError)
@@ -34,37 +33,35 @@ def __init__(self, shards: list[int], version: str):
3433
self.db.build()
3534
self.cache: dict = dict()
3635
self.tasks = AsyncIOScheduler(timezone=str(tzlocal.get_localzone()))
37-
self.logged_in = False
3836
self.shards_ready = False
3937
self.ready = False
4038
self.expected_shards = len(shards)
39+
self.shard_progress = Progress('Shards Ready', self.expected_shards)
4140
self.urban: UrbanDictionary = UrbanDictionary()
4241
self.VERSION = version
4342
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")
4948
self.tasks.add_job(self.db.commit, trigger='interval', minutes=30)
49+
self.shard_progress.start()
5050

5151
async def on_connect(self):
52-
self.tasks.start()
5352
await self.sync_commands()
53+
while not self.shards_ready:
54+
await asyncio.sleep(.5)
5455
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()
5857

5958
async def on_shard_ready(self, shard_id):
6059
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,
6160
name=f"SHARD {shard_id}"),
6261
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:
6564
self.shards_ready = True
66-
if self.shards_ready and self.logged_in:
67-
self.register_guilds()
6865

6966
def register_guilds(self):
7067
progress = Progress('Registering guilds', len(self.guilds))
@@ -73,16 +70,14 @@ def register_guilds(self):
7370
progress.next()
7471
self.db.commit()
7572
self.ready = True
73+
self.tasks.start()
7674
print('\nEverything is ready!')
7775

7876
async def get_application_context(
79-
self, interaction: Interaction, cls=CustomContext
77+
self, interaction: Interaction, cls=CustomContext
8078
):
8179
return await super().get_application_context(interaction, cls=cls)
8280

83-
async def on_disconnect(self):
84-
print(f"Bot Disconnected, Retrying to sign into user {self.user.display_name}#{self.user.discriminator}")
85-
8681
async def on_guild_join(self, guild: Guild):
8782
self.db.execute("""INSERT OR IGNORE INTO guilds VALUES (?,?,?)""", guild.id, None, None)
8883

@@ -115,7 +110,8 @@ async def on_interaction(self, interaction: discord.Interaction):
115110
if interaction.is_command():
116111
name_list, options = self.get_name(interaction.data, [])
117112
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())
119115
return await super().on_interaction(interaction=interaction)
120116

121117
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:
137133
embed: Embed = Embed(title="Http Error", description='Message failed to send', colour=0xff0000)
138134
await ctx.respond(embed=embed)
139135
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))
141138
elif hasattr(exc, "original"):
142139
if isinstance(exc.original, HTTPException):
143140
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):
159156
python_process.cpu_percent(*args, **kwargs)
160157
await asyncio.sleep(interval)
161158
return psutil.cpu_percent(*args, **kwargs)
162-

lib/db/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,6 @@ def build(self) -> None:
137137
data = re.search(r"\((?<=\()(?:.)+", create_table_query).group()
138138
self.update_table(table_name, data)
139139
progress.next()
140-
time.sleep(.2)
141140
self.commit()
142141

143142
def commit(self) -> None:

lib/progress/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
1+
from datetime import datetime
12
import sys
3+
import asyncio
4+
from functools import wraps, partial
25

36

47
class Progress:
58
def __init__(self, msg: str, total: int):
69
self.msg = msg
710
self.iteration = 0
811
self.total = total
12+
13+
def start(self):
914
sys.stdout.write(f"\r{self.msg} [{self.iteration}/{self.total}]")
1015
sys.stdout.flush()
1116

1217
def next(self):
18+
if not self.total:
19+
print(self.msg)
1320
self.iteration += 1
21+
if self.iteration > self.total: raise ValueError("Can't iterate more then the total")
1422
sys.stdout.write(f"\r{self.msg} [{self.iteration}/{self.total}]")
1523
sys.stdout.flush()
1624
if self.iteration == self.total:

0 commit comments

Comments
 (0)