最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Interaction failed when pressing button in Discord.py bot - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question asked Mar 17 at 13:06 Matei SerbanMatei Serban 1 4
  • Before doing interaction.followup.send() have you deferred the interaction? – Łukasz Kwieciński Commented Mar 17 at 13:17
  • I did that but it still doesnt work – Matei Serban Commented Mar 17 at 13:36
  • This problem usually always has to do with you not responding to the interaction within the three second allowed window. If you're doing anything long you should be always deferring first, then completing the actions, then sending a follow-up. Could you edit your code provided to show the version with deferral? – Ryry013 Commented Mar 17 at 15:12
  • I use defer and it still doesnt work – Matei Serban Commented Mar 18 at 16:49
Add a comment  | 

1 Answer 1

Reset to default 0

First of all, understand that a Discord interaction has a short lifetime, which is exactly 3 seconds. That is, you must respond to the interaction that called your command within 3 seconds or else it will become unknown.

If your command performs a time-consuming task, where you can't respond to the interaction in less than 3 seconds, you can defer the interaction response (which will cause your bot to go into status thinking) and then send a followup message using await interaction.followup.send().

async def on_button_click(interaction: discord.Interaction):
    await interaction.response.defer()    # put this on the start

    # ... do some stuff ... 

    # when sending a message:
    await interaction.followup.send("Resquest successfully!")
发布评论

评论列表(0)

  1. 暂无评论