add discord bot

This commit is contained in:
Thomas Rubini 2023-01-09 08:33:27 +01:00
parent 86ee9c3863
commit 1c1b117869
No known key found for this signature in database
GPG Key ID: C7D287C8C1CAC373
3 changed files with 50 additions and 0 deletions

View File

@ -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

View File

@ -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)

View File

@ -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"])