discord.py

How do you find the ID of a user who sends a slash command with code outside of that command?


I am looking to find the user ID of the user who uses a slash command with code that gets executed when clicking a button on said message. interaction.user.id gives me the id of the button clicker, rather than the original slash command user.

EDIT: Sure I could save the user IDs along with the message ID in a database, but I was hoping to find a better and faster way to go about it.


Solution

  • You can use interaction.message.interaction_metadata.user.id.

    If this is an XY Problem, you should know you can also nest the button callback inside the function which handles the original command, for example:

    async def cookie(interaction: discord.Interaction):
        async def give_cookie(button_interaction: discord.Interaction):
            if interaction.user != button_interaction.user:
                await button_interaction.response.send_message("No cookie for you >:(")
                return
            await button_interaction.response.send_message("Here is a cookie: :cookie:")
    
       view = discord.ui.View()
       button = discord.ui.Button(label="Get a cookie")
       button.callback = give_cookie
       view.add_item(button)
    
       await interaction.response.send_message(view=view)