Files
dom5bot/main.py

121 lines
3.4 KiB
Python

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
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():
with bot.tracked_games_lock:
bot.tracked_games = []
for _, _, files in os.walk("games"):
for name in files:
if name.endswith("json"):
bot.tracked_games.append(
Dom5game.load_json("games/" + name[:-5] + "/" + name)
)
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()
if __name__ in {"__main__", "__mp_main__"}:
main()
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
# await bot.tree.sync()
reload_games()
if not task_loop.is_running():
task_loop.start()
@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.",
)
)
for game in bot.games:
channel = bot.get_channel(game.channelId)
if channel is None:
continue
# handle turn ticks
new_turn = game.get_turn()
if new_turn != game.turn and new_turn.isdigit():
game.update_turn()
pingstr = ""
if game.members:
pingstr += "-# "
for member in game.members:
pingstr += "<@" + str(member) + "> "
await channel.send(
'Game **"'
+ game.name
+ '"** has advanced to turn '
+ game.turn
+ " \n"
+ pingstr
)
game.to_json()
# handle uploaded turns
turns = game.get_new_turns()
if turns != {}:
for key in turns:
value = turns[key]
if value == "Turn played":
await channel.send(
'Game **"'
+ game.name
+ '"**: '
+ key
+ " has played their turn."
)
if value == "Eliminated":
await channel.send(
'Game **"' + game.name + '"**: ' + key + " has been eliminated."
)
if value == "Turn unfinished":
await channel.send(
'Game **"'
+ game.name
+ '"**: '
+ key
+ " has marked their turn as unfinished."
)
game.update_players()
game.to_json()