Discord Bot Commands not working with on_message

Viewed 840

I have a few commands that worked perfectly, but when I add on_message they don't. I read that you need to add the await bot.process_commands(message) line, but it still doesn't work for me. Why?

@bot.event
async def on_message(message):
    if message.content.lower() == 'prefix':
        prefix = guilds.find_one({"_id": message.guild.id})["prefix"]
        await message.channel.send(f"> The prefix for this server is: {prefix}")
    else:
        return
    await bot.process_commands(message)
2 Answers

A function ends as soon as it encounters a return statement, with your current logic it will only process the commands if the if statement is True. Simply remove that else part.

@bot.event
async def on_message(message):
    if message.content.lower() == 'prefix':
        prefix = guilds.find_one({"_id": message.guild.id})["prefix"]
        await message.channel.send(f"> The prefix for this server is: {prefix}")
    await bot.process_commands(message)

The await bot.process_commands(message) code is only reachable when the message content is 'prefix'. To fix that put the await bot.process_commands(message) in the else body:

@bot.event
async def on_message(message):
    if message.content.lower() == 'prefix':
        prefix = guilds.find_one({"_id": message.guild.id})["prefix"]
        await message.channel.send(f"> The prefix for this server is: {prefix}")
    else:
        await bot.process_commands(message)
Related