From 09ff620e51cfb7cb9b459fcd732a041bf658f034 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 20 Dec 2023 21:24:44 -0500 Subject: [PATCH] Add loop for changing presence. --- cogs/loops/__init__.py | 4 +++- cogs/loops/bot_presence.py | 48 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 cogs/loops/bot_presence.py diff --git a/cogs/loops/__init__.py b/cogs/loops/__init__.py index 20564de..dc7c70d 100644 --- a/cogs/loops/__init__.py +++ b/cogs/loops/__init__.py @@ -4,7 +4,8 @@ Initializing code for all loops. from nextcord.ext import commands -from .daily_loop import DailyLoop +from cogs.loops.bot_presence import BotPresence +from cogs.loops.daily_loop import DailyLoop def setup(bot: commands.Bot): @@ -12,4 +13,5 @@ def setup(bot: commands.Bot): Adds functions to bot. """ + bot.add_cog(BotPresence(bot)) bot.add_cog(DailyLoop(bot)) diff --git a/cogs/loops/bot_presence.py b/cogs/loops/bot_presence.py new file mode 100644 index 0000000..f026809 --- /dev/null +++ b/cogs/loops/bot_presence.py @@ -0,0 +1,48 @@ +""" +Functions for controlling the bot's presence. Also contains the loop. +""" + +import nextcord +from nextcord.ext import commands, tasks +from sqlalchemy import func, select +from sqlalchemy.orm import Session + +from database_setup.sql_data_classes import Presences, engine + + +class BotPresence(commands.Cog, name="Bot Presence"): + """Class for bot presence functions.""" + + def __init__(self, bot: commands.Bot): + self.bot = bot + + @commands.Cog.listener() + async def on_guild_join( + self, guild: nextcord.Guild + ): # pylint: disable=unused-argument + """Listener for Guild Join. Updated presence on guild join.""" + await self.change_presence() + + @commands.Cog.listener() + async def on_ready(self): + """Starts the loop when bot is ready.""" + await self.bot.wait_until_ready() + # pylint doesn't recognize that periodic_change_presense is subclassed from tasks.loop. + self.periodic_change_presence.start() # pylint: disable=no-member + + @tasks.loop(minutes=5) + async def periodic_change_presence(self): + """Loops every 5 minutes and changes presence.""" + await self.change_presence() + + async def change_presence(self): + """Randomly chooses a presence and updates bot's presence.""" + + with Session(engine) as session: + presence = session.scalar( + select(Presences.Presence).order_by(func.random()) + ) + + await self.bot.change_presence( + activity=nextcord.CustomActivity(name="Custom Status", state=presence) + )