diff --git a/bot_instance.py b/bot_instance.py index 270152a..94d53c9 100644 --- a/bot_instance.py +++ b/bot_instance.py @@ -1,7 +1,25 @@ from discord.ext import commands import discord +import threading +import os +from dotenv import load_dotenv + +_started = False intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) bot.tracked_games = [] +bot.tracked_games_lock = threading.Lock() + + +async def start_bot(): + global _started + if _started: + return + _started = True + load_dotenv() + TOKEN = os.getenv("TOKEN") + if not TOKEN: + raise ValueError("No token found") + await bot.start(TOKEN) diff --git a/main.py b/main.py index 78cdf88..bb18865 100644 --- a/main.py +++ b/main.py @@ -1,21 +1,11 @@ import discord import os from discord.ext import tasks -from dotenv import load_dotenv from dom5game import Dom5game -from servermanager import create_server -from nicegui import ui from webui import create_ui -from bot_instance import bot +from bot_instance import bot, start_bot +from nicegui import ui import asyncio -import threading - -bot_start_lock = threading.Lock() -bot_started = False -load_dotenv() -TOKEN = os.getenv("TOKEN") -if not TOKEN: - raise ValueError("No token found") def reload_games(): @@ -29,29 +19,21 @@ def reload_games(): ) -async def start_discord_bot(): - await bot.load_extension("cogs.slash_commands") - await bot.start(TOKEN) - - def main(): - global bot_started create_ui() - with bot_start_lock: - if not bot_started and __name__ == "__mp_main__": - print("Starting bot") - bot_started = True - ui.timer(0, lambda: asyncio.create_task(start_discord_bot()), once=True) - ui.run() + loop = asyncio.get_event_loop() + loop.create_task(start_bot()) + ui.run(reload=False) -if __name__ in {"__main__", "__mp_main__"}: +if __name__ == "__main__": main() @bot.event async def on_ready(): print(f"Logged in as {bot.user}") + await bot.load_extension("cogs.slash_commands") # await bot.tree.sync() reload_games() if not task_loop.is_running(): @@ -60,15 +42,13 @@ async def on_ready(): @tasks.loop(seconds=5) async def task_loop(): - with bot.tracked_games_lock: - games = list(bot.tracked_games) await bot.change_presence( activity=discord.Activity( type=discord.ActivityType.watching, - name=str(len(games)) + " Servers.", + name=str(len(bot.tracked_games)) + " Servers.", ) ) - for game in bot.games: + for game in bot.tracked_games: channel = bot.get_channel(game.channelId) if channel is None: continue