add channel API + @API decorator

This commit is contained in:
Thomas Rubini 2023-01-11 10:46:50 +01:00
parent 1c1b117869
commit e2846d342a
No known key found for this signature in database
GPG Key ID: C7D287C8C1CAC373
2 changed files with 30 additions and 2 deletions

View File

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

View File

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