From e2846d342a2082804fa4836ebebc4d40d64df812 Mon Sep 17 00:00:00 2001 From: Thomas Rubini <74205383+ThomasRubini@users.noreply.github.com> Date: Wed, 11 Jan 2023 10:46:50 +0100 Subject: [PATCH] add channel API + @API decorator --- truthseeker/discord_bot.py | 30 +++++++++++++++++++++++++++++- truthseeker/routes/routes_api.py | 2 +- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/truthseeker/discord_bot.py b/truthseeker/discord_bot.py index 3707636..bc86c76 100644 --- a/truthseeker/discord_bot.py +++ b/truthseeker/discord_bot.py @@ -1,7 +1,10 @@ import discord import threading import truthseeker +import asyncio +async def empty_coro(): + return def init_bot(token): discord_bot = DiscordBot() @@ -14,18 +17,43 @@ def init_bot(token): class DiscordBot: def __init__(self): self.bot = discord.Client(intents=discord.Intents.default()) + self.__channel__ = None @self.bot.event async def on_ready(): print('Discord bot connected !') + self.event_loop = asyncio.get_event_loop() - await self.update_games_presence() + self.__setup__channel__() + self.update_games_presence() + + def __setup__channel__(self): + if len(self.bot.guilds) == 1: + self.__channel__ = discord.utils.get(self.bot.guilds[0].channels, name="bot") + else: + print("Could not find channel #bot") def __run__(self, token): self.bot.run(token) + def API(func): + def decorator(self, *args, **kwargs): + if self.bot and self.bot.is_ready(): + self.event_loop.create_task(func(self, *args, **kwargs)) + else: + print(f"Discord bot not ready, not processing function {func.__name__}()") + return decorator + + @API 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) + + @API + async def send_message(self, text): + if self.__channel__: + await self.__channel__.send(text) + else: + print("channel member not defined, not sending discord message") diff --git a/truthseeker/routes/routes_api.py b/truthseeker/routes/routes_api.py index fb26701..da09201 100644 --- a/truthseeker/routes/routes_api.py +++ b/truthseeker/routes/routes_api.py @@ -24,7 +24,7 @@ def create_game(): flask.session["is_owner"] = True flask.session["username"] = username - asyncio.run(APP.discord_bot.update_games_presence()) + APP.discord_bot.update_games_presence() return response