yor-discord-bot / cogs / event_handler.py
event_handler.py
Raw
"""This file contains the EventHandler Discord Cog extension.
"""
import discord
from discord import NotFound
from discord.ui import Button, View
from discord.ext import commands


from py_files.src.cog_utils.fixed_fifo_dict import FixedFIFODict as ffd


class EventHandler(commands.Cog):
    """EventHandler handles general Discord events, such as reaction adding.
    """
    def __init__(self, bot):
        self.bot = bot
        # caches messages that has page turning functionality
        self.bot.nav_cache = ffd(max_len=64)
        # available Buttons
        self.bot.next_button = Button(label="Next", style=discord.ButtonStyle.primary)
        self.bot.prev_button = Button(label="Prev", style=discord.ButtonStyle.secondary)
        # available View templates
        self.bot.nav_view = View()
        self.bot.nav_view.add_item(self.bot.next_button)
        self.bot.nav_view.add_item(self.bot.prev_button)
        # available reactions
        self.bot.reactions = {
            'crossmark' : '',
            'checkmark' : '',
            'bookmark'  : '🔖',
            'leftarrow' : '⬅️',
            'rightarrow': '➡️',
        }

    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        """Prints out a message when the bot joins a guild.
        """
        pass
        # await self.send('Welcome to the Forger family!')

    @commands.Cog.listener()
    async def on_reaction_add(self, reaction, user) -> None:
        """TODO: Document.
        """
        msg = reaction.message
        # check if author is a bot or if reaction is added in authorized channels
        if user == self.bot.user:
            return
        
        # remove reaction if user wants to interact with embed
        if msg.id in self.bot.nav_cache:
            try:
                await reaction.remove(user)
            except NotFound:
                print('[event_handler] on_reaction_add: '
                      'failed to remove reaction from message.')
        
        # flip embed pages
        if reaction.emoji == self.bot.reactions['leftarrow']:
            page = self.bot.nav_cache[msg.id].prev_page()
            await msg.edit(embed=page)
        elif reaction.emoji == self.bot.reactions['rightarrow']:
            page = self.bot.nav_cache[msg.id].next_page()
            await msg.edit(embed=page)
        
    # @commands.Cog.listener()
    # async def on_interaction(self, interaction: discord.Interaction) -> None:
    #     msg = interaction.message
    #     # check is author is bot
    #     if interaction.user == self.bot.user:
    #         return
        
    #     # flip embed pages
    #     if msg.id in self.bot.nav_cache:
    #         print('is nav')
    #         if interaction.
        
        
    
async def setup(bot):
    await bot.add_cog(EventHandler(bot))