diff --git a/truthseeker/__init__.py b/truthseeker/__init__.py index 14cbd3a..08f3077 100644 --- a/truthseeker/__init__.py +++ b/truthseeker/__init__.py @@ -2,6 +2,8 @@ import flask from flask_socketio import SocketIO import os +from truthseeker import discord_bot + class TruthSeekerApp(flask.Flask): def __init__(self): @@ -10,8 +12,15 @@ class TruthSeekerApp(flask.Flask): self.games_list = {} self.set_app_secret() + self.socketio_app = SocketIO(self) + token = self.get_discord_bot_token() + if token: + self.discord_bot = discord_bot.init_bot(token) + else: + print("No token set. Not starting discord bot") + def run_app(self): self.socketio_app.run(self) @@ -30,6 +39,14 @@ class TruthSeekerApp(flask.Flask): f.close() print("Generated secret and wrote to secret.txt !") + def get_discord_bot_token(self): + if os.path.isfile("instance/discord_bot_token.txt"): + f = open("instance/discord_bot_token.txt", "r") + token = f.read() + f.close() + return token + return None + APP = TruthSeekerApp() from truthseeker.routes import routes_api, routes_ui, routes_socketio diff --git a/truthseeker/discord_bot.py b/truthseeker/discord_bot.py new file mode 100644 index 0000000..3707636 --- /dev/null +++ b/truthseeker/discord_bot.py @@ -0,0 +1,31 @@ +import discord +import threading +import truthseeker + + +def init_bot(token): + discord_bot = DiscordBot() + + thr = threading.Thread(target=discord_bot.__run__, args=(token,)) + thr.start() + + return discord_bot + +class DiscordBot: + def __init__(self): + self.bot = discord.Client(intents=discord.Intents.default()) + + @self.bot.event + async def on_ready(): + print('Discord bot connected !') + + await self.update_games_presence() + + def __run__(self, token): + self.bot.run(token) + + async def update_games_presence(self): + games_n = len(truthseeker.APP.games_list) + activity_name = f"Handling {games_n} game{'' if games_n==1 else 's'} !" + activity = discord.Activity(name=activity_name, type=discord.ActivityType.watching) + await self.bot.change_presence(activity=activity) diff --git a/truthseeker/routes/routes_api.py b/truthseeker/routes/routes_api.py index df0e6db..fb26701 100644 --- a/truthseeker/routes/routes_api.py +++ b/truthseeker/routes/routes_api.py @@ -24,6 +24,8 @@ def create_game(): flask.session["is_owner"] = True flask.session["username"] = username + asyncio.run(APP.discord_bot.update_games_presence()) + return response @routes_api.route("/joinGame", methods=["GET", "POST"])