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

Discord机器人斜杠命令与消息事件均失效:命令存在却提示未找到

我的Discord机器人使用斜杠命令时无法响应,明明命令存在却提示“未找到命令”。尝试用on_message事件也无法正常工作,相关代码如下:

bot = commands.Bot(command_prefix='-', Help_Command=help, intents=discord.Intents.all())
intents=discord.Intents.all()
client = discord.Client(intents = intents)
activity = discord.Activity(type = discord.ActivityType.streaming, name="name", url = "twitch_url")
tree = app_commands.CommandTree(client)
bot.remove_command('help')
blue = discord.Color.from_rgb(0, 0, 200)
red = discord.Color.from_rgb(200, 0, 0)
green = discord.Color.from_rgb(0, 200, 0)
discord_blue = discord.Color.from_rgb(84, 102, 244)
guild_id= 1132535168247275600

@tree.command(name="sync", description="Make slash commands global.", guild=discord.Object(id=guild_id))
async def sync(int: discord.Interaction, member: discord.Member):
  await tree.sync()
  print('Command tree synced.')

@bot.command()
async def test(ctx):
  await ctx.send("hello")

问题根源

你同时初始化了commands.Bot和discord.Client两个实例,二者功能重叠且冲突——commands.Bot本身就是discord.Client的子类,所有客户端功能都可以通过Bot实现。你把斜杠命令绑定到了单独的Client实例的CommandTree,但实际运行的是Bot,导致命令无法被识别。

修复方案

  1. 删除多余的discord.Client实例,统一使用commands.Bot处理所有逻辑
  2. 将斜杠命令绑定到Bot的CommandTree(即bot.tree)
  3. 修正参数命名错误:int是Python关键字,不能用作discord.Interaction参数的变量名,改为interaction
  4. 确保启动的是Bot实例,并补充缺失的bot.run()调用

修复后的完整代码

import discord
from discord import app_commands
from discord.ext import commands

# 初始化单一Bot实例,整合所有配置
bot = commands.Bot(
    command_prefix='-',
    help_command=None,  # 移除默认help命令
    intents=discord.Intents.all(),
    activity=discord.Activity(
        type=discord.ActivityType.streaming,
        name="name",
        url="twitch_url"
    )
)

# 颜色常量定义
blue = discord.Color.from_rgb(0, 0, 200)
red = discord.Color.from_rgb(200, 0, 0)
green = discord.Color.from_rgb(0, 200, 0)
discord_blue = discord.Color.from_rgb(84, 102, 244)
guild_id = 1132535168247275600

# 绑定斜杠命令到Bot的CommandTree
@bot.tree.command(
    name="sync",
    description="同步斜杠命令",
    guild=discord.Object(id=guild_id)
)
async def sync(interaction: discord.Interaction, member: discord.Member):
    await bot.tree.sync()
    await interaction.response.send_message("命令树已同步")
    print('Command tree synced.')

# 前缀命令示例
@bot.command()
async def test(ctx):
    await ctx.send("hello")

# 启动机器人(替换为你的机器人Token)
bot.run("YOUR_BOT_TOKEN")

额外注意事项

  • 运行机器人后,先执行/sync命令同步斜杠命令:服务器专属命令通常几分钟生效,全局命令可能需要1小时
  • 确保在Discord开发者门户中开启所有需要的Intents,尤其是message_content(如果要使用前缀命令或on_message事件)
  • 若需自定义on_message事件,必须添加await bot.process_commands(message),否则前缀命令会失效:
@bot.event
async def on_message(message):
    # 你的自定义消息处理逻辑
    await bot.process_commands(message)

内容的提问来源于stack exchange,提问作者sumnaah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 16:51:26