[Python] Interaction failed when pressing button in Discord.py bot

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm building a Discord bot using discord.py 2.5.2 that handles button interactions. When a user clicks a button, they sometimes get the "This interaction failed" message even though the bot processes the action correctly.

    Here's my button click handler:

    @bot.event
    async def on_button_click(interaction: discord.Interaction):
    try:
    if str(interaction.user.id) not in ADMIN_IDS:
    await interaction.response.send_message("You are not authorized to perform this action.", ephemeral=True)
    return

    custom_id = interaction.custom_id
    message = interaction.message
    embed = message.embeds[0]
    user_id = embed.fields[3].value[2:-1]
    amount = float(embed.fields[0].value[1:])
    user = await bot.fetch_user(int(user_id))

    if custom_id in ["accept_deposit", "accept_withdraw"]:
    user_data = get_user_data(user_id) # Database operation
    if custom_id == "accept_deposit":
    user_data["balance"] += amount
    await user.send(f"Your deposit of ${amount:.2f} has been approved!")
    else:
    user_data["balance"] -= amount
    await user.send(f"Your withdrawal of ${amount:.2f} has been approved!")
    save_user_data(user_id, user_data)
    await message.edit(view=None)
    await interaction.response.send_message("Request approved!", ephemeral=True)
    else:
    action = "deposit" if custom_id == "deny_deposit" else "withdrawal"
    await user.send(f"Your {action} request has been denied.")
    await message.edit(view=None)
    await interaction.response.send_message("Request denied!", ephemeral=True)

    except Exception as e:
    print(f"Error in on_button_click: {e}")
    if not interaction.response.is_done():
    await interaction.response.send_message("An error occurred.", ephemeral=True)


    The issue seems to happen because the database operations and DM sending take some time before the bot responds to the interaction. How can I properly handle the interaction to prevent the "This interaction failed" message?

    Environment:

    • Python 3.11
    • discord.py 2.5.2
    • Windows 10

    `

    None of these prevent the "This interaction failed" message.

    1. Using interaction.response.send_message() immediately
    2. Using interaction.followup.send()
    3. Editing the message with view=None

    Continue reading...

Compartilhe esta Página