Setting up a Discord bot to react when users mention it

Hey everyone! I need some advice on my Discord bot project. I’m aiming to build a bot that will recognize when someone mentions it in a chat and respond to the message. For instance, if a user types “@MyBot#1234 what’s your favorite color?”, I’d like the bot to recognize the mention and provide a reply. I’m utilizing the Discord.py library for this task. Initially, I considered creating a comprehensive chatbot, but I’ve decided to simplify my plans for now. Has anyone successfully implemented mention detection? What would be the best way to achieve this? I would greatly appreciate any code examples or tips you could share. Thank you!

yeah, totally get u! just check if bot.user in message.mentions: in your on_message to detect it. don’t forget to prevent it from replying to itself by adding if message.author != bot.user, or else it’ll get stuck in a loop. i did that once, haha!

I’ve used Discord.py for two years, and mention detection is straightforward once you get the message object structure. Discord automatically parses mentions into the message.mentions list—no need to manually parse @MyBot#1234 syntax. Just check if your bot’s user object appears in message.mentions within your on_message handler. Watch out for one thing: make sure the message author isn’t the bot itself or you’ll create infinite loops when your bot mentions itself. Strip the mention from the message content before processing responses. Otherwise, you’re parsing “<@!botid> what’s your favorite color” instead of “what’s your favorite color”. The bot.user object comparison works reliably across servers.

I’ve built plenty of Discord bots and this approach works great. Just remember to handle the message content properly after catching the mention. When someone mentions your bot, strip out the mention part with message.content.replace(f'<@{bot.user.id}>', '').strip() or message.content.replace(f'<@!{bot.user.id}>', '').strip() - Discord formats mentions differently sometimes. Test both direct mentions and reply mentions since they act differently in the API. I usually make a simple utility function that cleans the message and returns just the text without mention formatting. Makes processing user input way cleaner.