How to check id of a tagged user with discord.py

Question:

I have a command defined with my discord bot that responds to a prompt like shown:

if message.content.startswith("doge roast") : print("<the roast>")

This responds in all cases, but I would like to check whether I have been tagged in the post and respond differently in said case.

I’ve tried looking at some solutions, but they use command contexts. I have simply defined my command in on_message.

So, how would I find the id of the user that is tagged in the message?

Asked By: Shweta K

||

Answers:

So if you’re using on_message, you could try something like this:

if message.content.startswith("doge roast"):
    if message.content.split(" ")[2].replace('<@','').replace('>','').replace('!','') == "YOUR ID":
        await message.channel.send("You can't roast this person!")
    else:
        await message.channel.send("<The roast>")

The above code will start by checking if you’re using the doge roast command. It will then check the mention, and strip all characters inside it, turning that mention into a user id. This will allow it to check if it’s trying to roast you. If the userid of the person they’ve mentioned is yours, then it will reply saying "you can’t roast this person". If it isn’t you, it will reply with the roast.

You can find your userid by reading this tutorial

Once you have your userid, replace "YOUR ID" with that ID.

Answered By: Trent112232

Explanation

You can access the mentions in a discord.Message using the mentions property.

A list is stored in the mentions property, so you can access the tagged discord.Member using message.mentions[0].

Code

if message.content.startswith("doge roast"):
    if message.mentions[0].id == YOUR_ID:
        print("something else")
    else:
        print("<the roast>")

Note: if using discord.ext.commands.Bot, you can replace YOUR_ID with bot.owner_id

Reference

Message.mentions

Member.id

Answered By: TheFungusAmongUs
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.