Skip to content

Commit 550109e

Browse files
committed
Fix small bugs and added cleaner startup
1 parent 008f60c commit 550109e

File tree

6 files changed

+76
-22
lines changed

6 files changed

+76
-22
lines changed

launcher.py

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,37 @@
1-
import glob
21
import atexit
2+
import glob
3+
import sys
4+
5+
from time import sleep
6+
7+
import numpy as np
8+
import requests
9+
310
from lib.bot import Bot
11+
from lib.config import Config
12+
from lib.progress import Progress
413

514
COGS = [path.split("\\")[-1][:-3] if "\\" in path else path.split("/")[-1][:-3] for path in
615
glob.glob('./lib/cogs/*.py')]
716
VERSION = "0.0.1"
8-
bot: Bot = Bot(VERSION)
9-
print("Registering cogs...")
10-
for cog in COGS:
11-
print(f" - {cog}")
12-
bot.load_extension(f"lib.cogs.{cog}")
13-
print("All cogs ready, now registering shards...")
17+
config = Config()
18+
TOTAL_GUILDS = len(requests.get("https://discord.com/api/v9/users/@me/guilds",
19+
headers={"Authorization": f"Bot {config.token}"}).json())
20+
SHARDS_LIST: list[int] = list(range(round((TOTAL_GUILDS / 1000) + 1)))
21+
CLUSTERS = round((len(SHARDS_LIST) / 2) + 1)
22+
SHARDS_SPLIT: list[np.ndarray[int]] = np.array_split(SHARDS_LIST, CLUSTERS)
1423

1524

16-
if __name__ == '__main__':
25+
def start(cluster_id: int):
26+
bot: Bot = Bot(list((SHARDS_SPLIT[cluster_id])), VERSION)
27+
progress = Progress("Registering Cogs", len(COGS))
28+
for index, cog in enumerate(COGS):
29+
bot.load_extension(f"lib.cogs.{cog}")
30+
sleep(.2)
31+
progress.next()
1732
atexit.register(bot.db.commit)
1833
bot.run(bot.config.token)
34+
35+
36+
if __name__ == '__main__':
37+
start(0)

lib/bot/__init__.py

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,28 @@
2121
from discord import Interaction, Guild
2222
from lib.context import CustomContext
2323
from lib.urban import UrbanDictionary
24+
from lib.progress import Progress
2425

2526
COMMAND_ERROR_REGEX = r"Command raised an exception: (.*?(?=: )): (.*)"
2627
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument, RuntimeError)
2728

2829

2930
class Bot(BaseBot):
30-
def __init__(self, version: str):
31+
def __init__(self, shards: list[int], version: str):
3132
self.config: Config = Config()
32-
3333
self.db: DB = DB()
3434
self.db.build()
3535
self.cache: dict = dict()
3636
self.tasks = AsyncIOScheduler(timezone=str(tzlocal.get_localzone()))
37+
self.logged_in = False
38+
self.shards_ready = False
3739
self.ready = False
40+
self.expected_shards = len(shards)
3841
self.urban: UrbanDictionary = UrbanDictionary()
3942
self.VERSION = version
4043
super().__init__(
4144
owner_id="507214515641778187",
42-
shards=5000,
45+
shards=shards,
4346
intents=discord.Intents.all(),
4447
debug_guilds=["1064582321728143421"],
4548
description="Misc Bot used for advanced moderation and guild customization")
@@ -48,14 +51,29 @@ def __init__(self, version: str):
4851
async def on_connect(self):
4952
self.tasks.start()
5053
await self.sync_commands()
51-
print(f"Signed into {self.user.display_name}#{self.user.discriminator}\n")
52-
self.ready = True
54+
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()
5358

5459
async def on_shard_ready(self, shard_id):
5560
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,
5661
name=f"SHARD {shard_id}"),
5762
shard_id=shard_id)
58-
print(f" - Shard {shard_id+1}/{self.shard_count} ready")
63+
print(f"Shard Ready [{shard_id+1}/{self.shard_count}]")
64+
if shard_id+1 == self.expected_shards:
65+
self.shards_ready = True
66+
if self.shards_ready and self.logged_in:
67+
self.register_guilds()
68+
69+
def register_guilds(self):
70+
progress = Progress('Registering guilds', len(self.guilds))
71+
for guild in self.guilds:
72+
self.db.execute("""INSERT OR IGNORE INTO guilds VALUES (?,?,?)""", guild.id, None, None)
73+
progress.next()
74+
self.db.commit()
75+
self.ready = True
76+
print('\nEverything is ready!')
5977

6078
async def get_application_context(
6179
self, interaction: Interaction, cls=CustomContext
@@ -134,7 +152,8 @@ async def on_application_command_error(self, ctx: CustomContext, exc) -> None:
134152
else:
135153
raise exc
136154

137-
async def cpu_percent(self, interval = None, *args, **kwargs):
155+
@staticmethod
156+
async def cpu_percent(interval=None, *args, **kwargs):
138157
python_process = psutil.Process(os.getpid())
139158
if interval is not None and interval > 0.0:
140159
python_process.cpu_percent(*args, **kwargs)

lib/cogs/Info.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import os
22

3-
import discord
43
import psutil
54
from discord.commands import SlashCommandGroup
65
from discord.embeds import Embed

lib/cogs/Youtube.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import re
22

33
from discord.ext.commands import Cog
4-
from discord.commands import slash_command, SlashCommandGroup, option
4+
from discord.commands import SlashCommandGroup, option
55
from discord.embeds import Embed
66
import aiohttp
77

8-
from bs4 import BeautifulSoup
9-
108
from lib.bot import Bot
119
from lib.context import CustomContext
1210

lib/db/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import re
22
import sys
3+
import time
34
from sqlite3 import Connection, Cursor, connect, Error
45

6+
from lib.progress import Progress
57

68
class DB:
79
DB_PATH = "./data/database.db"
@@ -96,15 +98,13 @@ def update_table(self, table: str, data: str):
9698
self.cur.execute(f"ALTER TABLE {table}_new RENAME TO {table};")
9799

98100
def build(self) -> None:
99-
print('Building Database...')
101+
progress = Progress("Building Database", len(self.table_info))
100102
for table in self.table_info:
101103
table_data = table['table']
102104
for table_name, columns in table_data.items():
103-
print(f' - {table_name}')
104105
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name}("
105106
constraints = table.get('constraints')
106107
for column_name, data_type in columns.items():
107-
print(f' - {column_name}')
108108
if constraints:
109109
not_null = constraints.get('not_null')
110110
if not_null:
@@ -136,6 +136,8 @@ def build(self) -> None:
136136
self.cur.execute(create_table_query)
137137
data = re.search(r"\((?<=\()(?:.)+", create_table_query).group()
138138
self.update_table(table_name, data)
139+
progress.next()
140+
time.sleep(.2)
139141
self.commit()
140142

141143
def commit(self) -> None:

lib/progress/__init__.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import sys
2+
3+
4+
class Progress:
5+
def __init__(self, msg: str, total: int):
6+
self.msg = msg
7+
self.iteration = 0
8+
self.total = total
9+
sys.stdout.write(f"\r{self.msg} [{self.iteration}/{self.total}]")
10+
sys.stdout.flush()
11+
12+
def next(self):
13+
self.iteration += 1
14+
sys.stdout.write(f"\r{self.msg} [{self.iteration}/{self.total}]")
15+
sys.stdout.flush()
16+
if self.iteration == self.total:
17+
print("")

0 commit comments

Comments
 (0)