Search code examples
pythondiscorddiscord.py

Discord.py Interaction Already Acknowledged


enter image description hereThe code runs fine up until I click the button and It gives an error (included at top). The script still runs with the error but I need to fix it for hosting purposes. Thanks!

class CollabButton(discord.ui.View):

  def __init__(self):
    super().__init__(timeout=None)
    self.add_item(
        discord.ui.Button(label='Accept', style=discord.ButtonStyle.green))


@client.event
async def on_interaction(interaction):
  if interaction.type == discord.InteractionType.component:
    if is_moderator(interaction.user):
      collab_button_view = CollabButton()
      if not interaction.response.is_done():
        await interaction.response.send_message(
            f"Hey {interaction.user.mention}!\nAn admin has accepted the collaboration offer!"
        )
    else:
      if not interaction.response.is_done():
        await interaction.response.send_message(
            "You do not have permission to use this button.", ephemeral=True)


def is_moderator(user):
  #Role name can be changed to anything
  return any(role.name == 'Cadly' for role in user.roles)

I tried adding the if statement to verify if the response is done and I'm running out of ideas. Any insight helps!


Solution

  • This problem is happening because you are not filtering the desired interactions in the on_interaction event. As a result, interactions that are handled in other components are also being received by this event.

    It is highly recommended that you define a custom_id for the component you want to handle in this event and filter only interactions arising from it:

    class CollabButton(discord.ui.View):
    
      def __init__(self):
        super().__init__(timeout=None)
        button = discord.ui.Button(
            label='Accept',
            style=discord.ButtonStyle.green, 
            custom_id="collab_button"
        )
        self.add_item(button)
    
    
    @client.event
    async def on_interaction(interaction):
      item_id = interaction.data.get("custom_id")
      if item_id == "collab_button":
        if is_moderator(interaction.user):
          if not interaction.response.is_done():
            await interaction.response.send_message(
                f"Hey {interaction.user.mention}!\nAn admin has accepted the collaboration offer!"
            )
        else:
          if not interaction.response.is_done():
            await interaction.response.send_message(
                "You do not have permission to use this button.", ephemeral=True)