1
votes

I'm trying to make my bot respond if somebody mentions the bot. My current code is this

 if message.content.startswith('@435379055253127178'):
    text = await client.send_message(message.channel, "**Baking a cake**")
    await client.send_message(message.channel, "**Baking a cake**")
    await client.edit_message(text, "Hi i'm cake bot nice to meet you!")

However, I got no response.

3

3 Answers

1
votes

The cleanest way to do this seems to be as follows:

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        await message.channel.send("hello!")
0
votes

Mentions are stored in an attribute named message.mentions

if discord.utils.get(message.server.members, '435379055253127178') in message.mentions:
    text = await client.send_message(message.channel, "**Baking a cake**")
    await client.send_message(message.channel, "**Baking a cake**")
    await client.edit_message(text, "Hi i'm cake bot nice to meet you!")

But if you want to check mentions manually instead, there's sometimes a ! in between the @ and id and they are wrapped by <>. I would use a regex:

from re import match

if match("<@!?435379055253127178>", message.content) is not None:
    text = await client.send_message(message.channel, "**Baking a cake**")
    await client.send_message(message.channel, "**Baking a cake**")
    await client.edit_message(text, "Hi i'm cake bot nice to meet you!")

This will check if the mention of the user is at the front of the message, similar to what you were trying to do. Since .mentions keeps a unordered list of all mentioned users.

Btw, if the id is the bot's, you could don't have to hard code the id.

if client.user in message.mentions:
    ...
0
votes

this is the way I do it can't tell if its the best way

import discord
from discord.ext import commands

client = commands.Bot(command_prefix=">")

@client.event    
async def on_message(message):
    for x in message.mentions:
        if(x==client.user):
            await message.channel.send(f":sauropod: did someone mention me?")

    await client.process_commands(message)        

by the way, u don't have to use the prefix while sending a message unlike commands for this to work. the code will trigger no matter where the bot is mentioned in the message