You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用discord.py(含斜杠命令)为Discord消息添加按钮?

解决Discord.py斜杠命令下添加按钮的问题

问题根源

discord_components这个第三方库已停止维护,完全不兼容discord.py 2.0+版本的应用命令(即你使用的斜杠命令),且Replit默认环境不会预装该库,这就是你触发ModuleNotFoundError的核心原因。目前discord.py官方已在2.0版本内置了交互组件系统,无需依赖第三方库即可实现按钮功能。

正确解决方案步骤

  1. 升级到最新版discord.py
    在Replit终端执行升级命令:

    pip install -U discord.py
    

    或直接修改项目的requirements.txt,添加一行:

    discord.py>=2.0.0
    
  2. 使用官方内置组件实现按钮
    以下是完整的斜杠命令+按钮示例代码:

    import discord
    from discord import app_commands
    from discord.ui import Button, View
    
    # 配置机器人权限
    intents = discord.Intents.default()
    intents.message_content = True  # 需读取消息内容时开启
    client = discord.Client(intents=intents)
    tree = app_commands.CommandTree(client)
    
    # 定义按钮视图类
    class ButtonView(View):
        # 创建蓝色主样式按钮
        @discord.ui.button(label="点击触发", style=discord.ButtonStyle.primary)
        async def on_button_click(self, interaction: discord.Interaction, button: Button):
            # 给点击者发送仅其可见的临时回复
            await interaction.response.send_message("按钮已触发!", ephemeral=True)
    
    # 定义斜杠命令
    @tree.command(name="发送按钮", description="发送带按钮的测试消息")
    async def send_button(interaction: discord.Interaction):
        view = ButtonView()
        await interaction.response.send_message("这是一条带按钮的消息", view=view)
    
    # 机器人启动时同步斜杠命令
    @client.event
    async def on_ready():
        await tree.sync()  # 全局同步,指定服务器可加参数:guild=discord.Object(id=你的服务器ID)
        print(f"机器人已登录:{client.user}")
    
    # 替换为你的机器人令牌
    client.run("你的机器人TOKEN")
    

关键注意事项

  • 首次运行时,tree.sync()会将斜杠命令同步到Discord服务器,可能需数分钟生效
  • 需在Discord开发者平台手动开启机器人对应的intents权限(消息内容权限需单独勾选)
  • 按钮回调函数必须接收interaction和button两个参数,通过interaction.response处理回复,不要使用旧版的message.channel.send

内容的提问来源于stack exchange,提问作者Static Spaghetti 13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:55:19