基于discord.py的Discord Bot按钮交互报错“This action failed”求助
Discord Bot 按钮交互报错(This action failed)排查与修复
针对你开发Discord Bot时,点击绿色按钮出现“This action failed”的问题,我整理了最常见的几个原因和对应的解决方法,附完整修正代码:
常见错误原因及修复
1. View未正确关联或超时失效
发送带按钮的消息时,如果没把包含按钮的View对象传给send()方法,或者View默认的180秒超时到期,都会导致按钮无法正常响应。如果需要按钮长期有效,还要开启持久化配置。
- 修复:发送消息时显式传递View对象;要实现持久化就把View的
timeout设为None,并在Bot启动时用bot.add_view()注册View。
2. 交互响应超时或方法错误
Discord要求按钮回调必须在3秒内返回响应,否则直接触发报错。如果回调里有耗时操作,得先调用defer延迟响应;更新消息时要用正确的方法,比如edit_original_response()。
- 修复:回调函数开头先添加
await interaction.response.defer();更新消息使用await interaction.edit_original_response()。
3. Bot权限不足
Bot需要拥有编辑消息、发送嵌入消息、使用交互组件的权限,否则点击按钮后无法完成Embed更新操作。
- 修复:检查Bot的角色权限,确保开启上述权限;邀请Bot时要携带
applications.commands权限范围。
4. 代码逻辑错误
比如获取用户昵称时使用了错误的属性,或者Embed构建格式出错,都会导致更新消息失败。
- 修复:用
interaction.user.display_name获取服务器昵称(无服务器昵称时会自动回退到用户名);确保Embed的字段、颜色等设置合法。
修正后的完整代码
import discord from discord.ext import commands import time # 配置意图,消息内容意图按需开启 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) class TimerButtonView(discord.ui.View): def __init__(self): # timeout设为None让按钮长期有效,也可设具体秒数(如3600) super().__init__(timeout=None) @discord.ui.button(label="开始计时", style=discord.ButtonStyle.green) async def trigger_timer(self, interaction: discord.Interaction, button: discord.ui.Button): # 先延迟响应,避免超时 await interaction.response.defer() # 获取用户服务器昵称 user_server_nick = interaction.user.display_name # 记录计时启动时间 start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 构建更新后的Embed updated_embed = discord.Embed(title="计时已启动", color=discord.Color.green()) updated_embed.add_field(name="参与用户", value=user_server_nick, inline=False) updated_embed.add_field(name="开始时间", value=start_time, inline=False) # 更新原消息的Embed和View await interaction.edit_original_response(embed=updated_embed, view=self) @bot.event async def on_ready(): print(f"Bot已登录:{bot.user.name}") # 若使用持久化按钮(timeout=None),需在此注册View,重启后按钮仍有效 # bot.add_view(TimerButtonView()) @bot.command() async def send_timer(ctx): # 初始引导Embed initial_embed = discord.Embed(title="点击下方按钮开始计时", color=discord.Color.blue()) # 发送消息时关联View await ctx.send(embed=initial_embed, view=TimerButtonView()) # 替换为你的Bot Token bot.run("YOUR_BOT_TOKEN_HERE")
额外提醒
- 确保使用discord.py v2.x版本,v1.x组件逻辑差异较大,易出问题,更新命令:
pip install -U discord.py - 若使用持久化按钮,Bot重启后必须重新注册View,否则历史消息中的按钮会失效
- 优先在测试服务器调试,避免权限问题干扰排查
内容的提问来源于stack exchange,提问作者superluk 1000
相关产品推荐
相关产品推荐

