From ae0c707470cef3f76ab06f53a1d9462182bba78a Mon Sep 17 00:00:00 2001 From: Carl Date: Thu, 9 Apr 2026 13:04:20 +0200 Subject: [PATCH] Threading actually sucks. --- bot_instance.py | 2 -- main.py | 39 +++++++++++++++++++++++++-------------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/bot_instance.py b/bot_instance.py index b5528bd..270152a 100644 --- a/bot_instance.py +++ b/bot_instance.py @@ -1,9 +1,7 @@ from discord.ext import commands import discord -import threading intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) bot.tracked_games = [] -bot.tracked_games_lock = threading.Lock() diff --git a/main.py b/main.py index fb2cb6c..70514c6 100644 --- a/main.py +++ b/main.py @@ -1,16 +1,18 @@ import discord import os -from discord.ext import tasks, commands +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 -import threading from bot_instance import bot +import asyncio load_dotenv() TOKEN = os.getenv("TOKEN") +if not TOKEN: + raise ValueError("No token found") def reload_games(): @@ -24,13 +26,28 @@ def reload_games(): ) +async def start_discord_bot(): + await bot.load_extension("cogs.slash_commands") + await bot.start(TOKEN) + + +def main(): + create_ui() + ui.timer(0, lambda: asyncio.create_task(start_discord_bot()), once=True) + ui.run() + + +if __name__ in {"__main__", "__mp_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() - task_loop.start() + if not task_loop.is_running(): + task_loop.start() @tasks.loop(seconds=2) @@ -43,8 +60,11 @@ async def task_loop(): ) for game in bot.tracked_games: channel = bot.get_channel(game.channelId) + if channel is None: + continue # handle turn ticks - if game.get_turn() != game.turn and game.get_turn().isdigit(): + new_turn = game.get_turn() + if new_turn != game.turn and new_turn.isdigit(): game.update_turn() pingstr = "" if game.members: @@ -88,12 +108,3 @@ async def task_loop(): ) game.update_players() game.to_json() - - -def start_bot(): - bot.run(TOKEN) - - -threading.Thread(target=start_bot, daemon=True).start() -create_ui() -ui.run()