pythonpython-3.xdiscorddiscord.pyinteraction

get user mentions from Discord.py 2.0 interactions


Using discord.py 2.0's new slash commands, how do I get mentions from discord.Interaction?

tree = discord.app_commands.CommandTree(client)


@tree.command(name="test", description="test")
async def test(interaction: discord.Interaction, message: str):
# ...

I am able to parse through the message param for user id's. But I was wondering if there is an easier way to maybe get a list of mentions instead of having to parse through it. If I try to print interaction.message I get None in return.


Solution

  • As far as I know, it's not possible to get the mentions trough the library, like Message.mentions, in interactions. But you can do it in an easier way instead of manually iterating through it.

    Use regex to do it, like that:

    import re
    
    @tree.command(name="test", description="test")
    async def test(interaction: discord.Interaction, message: str):
        guild = interaction.guild
    
        # get the member IDs in the string
        matches = re.findall(r"<@!?([0-9]{15,20})>", message) # returns list of strings
    
        # create list of discord.Member
        members = [guild.get_member(int(match)) for match in matches]
    
        await interaction.response.send_message(f"Mentioned members: {', '.join(str(member) for member in members)}")
    

    Result

    Result


    Edit

    It exists something called Transformer which allows this, but in my opinion it's unnecessarily complicated for your problem. But in case you want to use it:

    Docs: https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer
    Example: https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/transformers.py