1
votes

I am a intermediate python programmer and just started coding discord bots using the discord.py module. One question that always revolves around my head is, how does the module detect that a message is sent using on_message() coroutine which is declared in our code and no such detection construct is there?

async def on_message(mssg):
    #our conditions and responses

Consider the above code. Is there an equivalent predefined coroutine in the module that calls when we declare the on_message() in our code or is there something else that makes it to detect messages and pass it to the function argument, or detect any other event? On youtube or elsewhere, they just make you learn the syntax for some reason that you have to use async...await from the documentation.

1

1 Answers

1
votes

so if memory serves me correct, the on_message() is what calls the bot to listen to each message that is sent, every time a message is sent. So with your code there:

async def on_message(mssg):
    #our conditions and responses

we can actually dress that up a bit with some inter-workings, like so:

@bot.listen('on_message')

it's a bot event, so every-time a message is sent, this function is called.

async def stuff(message):

pass message so that the bot knows what to scan.

if message.content.startswith("buttlerprefix"):

start it off with an if statement so that the bot has something to check the user's message against

If I typed buttlerprefix and hit enter, it would respond with this message:

msg = await message.channel.send("my prefix is `>`")

if you want to go an extra step, and keep the channels declutterd, you can set the response equal to a variable msg in the event that you want to manipulate it later, thus in this scenario, it's set to auto delete with

await asyncio.sleep(10)
await msg.delete()

So if we put all of that together:

@bot.listen('on_message') 
async def stuff(message):

    if message.content.startswith("buttlerprefix"):
        msg = await message.channel.send("my prefix is `>`")
        await asyncio.sleep(10)
        await msg.delete()

we get a function that is now scanning every message that comes through the guild that this bot functions in, no matter the channel, due to the on_message() function being called every-time a message is sent which is triggered by the @bot.listen