Is there a way to have self, message, and ctx in an on_message event?

Viewed 883

Right now, I am using cogs to make an emoji filter. To use the on_message event to check if people are spamming emojis, I need to have self, message, and ctx as args in the on_message event. (the reason I need ctx is to check the guild id in mongodb, which is what im using to store whether the server has enlisted in the filter system). My code is

    @commands.Cog.listener()
    async def on_message(self, message, ctx):
        existing = collection.find_one({"serverid": ctx.guild.id})
        if not existing:
            return
        else:
            if message.author.bot:
                return
            s = message.content
            s2 = message.content.lower()
            message.content = re.sub("[_~*]", "", message.content)
            message.content = re.sub(r"[\s]+[\s]{2}", "", message.content)
            if emoji_count == 1 and len(without_emojis) < 10:
                current = message.created_at.replace(tzinfo=datetime.timezone.utc).timestamp()
                bucket = self._buckets1.get_bucket(message, current)
                retry_after = bucket.update_rate_limit(current)
                if retry_after:
                    await message.delete()

The command to start using the filter system works fine, but the on_message event throws an error, no matter the order I have tried to replace it in.

Here's the error:
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event await coro(*args, **kwargs) TypeError: on_message() missing 1 required positional argument: 'ctx'

If anyone knows how to fix the error, I would appreciate it, thanks!

1 Answers

As this is an on_event listener, there is no ctx being passed to your function. Think of the arguments of an event listener as less of a menu where you can order what you want and more of you just being able to name the few things it is passing to you. So keep the message argument, as that is the one being passed to the function internally from the library and remove the ctx argument.

That being said, ctx is nothing but an easier way to access things everything that is accessible with ctx can be found some other way. As you want the guild id, this is quite easy with the message object:

guild_id = message.channel.guild.id
Related