Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15728

discord.py on_message cancel when new command is executed

How can I cancel my on_message event when I execute another command? My code:

@client.event
async def on_message(message):
    channel = message.author
    def check(m):
        return m.channel == message.channel and m.author != client.user

    if message.content.startswith("!order"):
        await channel.send("in game name")
        in_game_name = await client.wait_for('message', check=check)

        await channel.send("in game ID")
        in_game_ID = await client.wait_for('message', check=check)

    else:
        await client.process_commands(message)

Upvotes: 0

Views: 771

Answers (2)

Pármenas Haniel
Pármenas Haniel

Reputation: 86

You can put your on_message event inside a cog. That way, the on_message event (or any other event/command) will only be triggered when the cog is active.

class Foo(commands.Cog):

    @commands.Cog.listener()
    async def on_message(self, message):
        # Do something

To register the cog (activate):

bot.add_cog(Foo(bot))

To remove the cog (deactivate):

bot.remove_cog('Foo')

Link to cog doc

Upvotes: 0

Generic Nerd
Generic Nerd

Reputation: 327

on_message should realistically only be reserved for events that require an on_message event (say if you are writing an auto-moderation feature).

For commands, you should be using the @client.command or @bot.command decorators before a function. Here is the usage for commands. Here are a few reasons on why you should use commands (taken directly from the ?tag commands on the discord.py discord):

  • Prevents spaghetti code
    • Better performance
    • Easy handling and processing of command arguments
    • Argument type converters
    • Easy sub commands
    • Command cooldowns
    • Built-in help function
    • Easy prefix management
    • Command checks, for controlling when they're to be invoked
    • Ability to add command modules via extensions/cogs
    • Still able to do everything you can do with Client

If you have any questions, feel free to comment on this answer!

Upvotes: 1

Related Questions