Python中如何为Discord Webhook添加交互按钮?
实现Discord Webhook消息添加按钮的方法
可以实现,问题出在你的代码存在几个关键疏漏,以下是修正方案:
1. 完善Buttons类定义
你的Buttons类缺少必要的按钮组件和正确的语法结构,必须在类内定义具体的按钮及其回调逻辑:
import discord from discord.ext import commands client = commands.Bot(command_prefix="!", intents=discord.Intents.default()) class Buttons(discord.ui.View): def __init__(self): super().__init__(timeout=None) # 设置为None让按钮长期有效 # 定义一个主色调按钮 @discord.ui.button(label="点击测试", style=discord.ButtonStyle.primary) async def test_button(self, interaction: discord.Interaction, button: discord.ui.Button): # 按钮被点击后的响应 await interaction.response.send_message("按钮生效了!", ephemeral=True) # 机器人启动时加载视图(确保持久化按钮生效) @client.event async def on_ready(): client.add_view(Buttons()) print(f"Logged in as {client.user}")
2. 使用discord.py原生Webhook发送方法
你最初使用的DiscordWebhook是第三方库(如discord-webhook),该库不支持discord.ui.View。必须改用discord.py内置的fetch_webhook方法:
@client.command() async def qube(ctx): try: # 通过ID获取Webhook对象 webhook = await client.fetch_webhook(1071845923254173746) # 创建嵌入消息(可选) embed = discord.Embed( title="你的标题", description="示例描述文本", color=0x03b2f8 ) # 发送带按钮的Webhook消息 await webhook.send(embed=embed, view=Buttons()) await ctx.send("Webhook消息已发送!") except discord.NotFound: await ctx.send("未找到指定的Webhook!") except Exception as e: await ctx.send(f"发送失败:{str(e)}") client.run("你的机器人Token")
关键注意事项
- 确保你的discord.py版本是最新的(至少v2.0+),旧版本不支持视图组件。
- 如果需要按钮长期有效(重启机器人后仍能响应),必须设置
timeout=None并在on_ready中调用client.add_view()。 - 第三方
discord-webhook库无法直接使用discord.ui.View,建议统一使用discord.py的原生功能。
内容的提问来源于stack exchange,提问作者фДУч
相关产品推荐
相关产品推荐

