2
votes

Recently my bot was growing and I took the time to rewrite the code to make it work with the cogs system of Discord Py

I have adapted all the code correctly, however all the on_message events that I had stopped working, without throwing any type of error message.

The module is loaded correctly and there are no syntax errors, so I can't understand what could be happening.

Some of my code:

import discord
import random
import datetime
from discord.ext import commands

class eastereggs(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.Cog.listener()
    async def on_message(self,message):
        Cheers= ["Hi", "hi", "Hello", "hello"]
        if message.content in Cheers:
            await message.channel.send('Hello again')
            await self.bot.process_commands(message)

def setup(bot):
    bot.add_cog(eastereggs(bot))

However, it does not react to any of the greetings in the array

I edit: I have multiple on_message events with arrays

But only one seems to work

2

2 Answers

2
votes

Problem lies in that you can't have two functions with the same name. If you do, it will only ever call the last one. The file will load without giving any error. Since all are on_message events, only the last one will ever work. You can however tell the listener what to "listen" for.

You can use @Cog.listener("on_message") (or other events in the same way), and then call your functions different names.

    @Cog.listener("on_message")
    async def greet(self,message):
        Cheers= ["Hi", "hi", "Hello", "hello"]
        if message.content in Cheers:
            await message.channel.send('Hello again')
            await self.client.process_commands(message)

    @Cog.listener("on_message")
    async def agree(self,message):
        Agree = ["yes", "yep", "ok"]
        if message.content in Agree:
            await message.channel.send('good')
            await self.client.process_commands(message)


    @Cog.listener("on_message")
    async def dAgree(self,message):
        dAgree= ["no", "nope"]
        if message.content in dAgree:
            await message.channel.send('why')
            await self.client.process_commands(message)

0
votes

You need to unindent process_commands

@commands.Cog.listener()
async def on_message(self, message):
    # some code

    await self.bot.process_commands(message)

And in every other on_message event you have, also if you wanna make your code a bit cleaner and more robust there's bot.dispatch, to create custom events, sadly there´s no docs about it

@commands.Cog.listener()
async def on_message(self, message):
    if message.content in ['some', 'values']:
                          # name of the event, args
        self.bot.dispatch('custom_event', message)

    await self.bot.process_commands(message)


@commands.Cog.listener()
async def on_custom_event(self, message):
    # custom event