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

Discord机器人命令扩展已加载但不显示问题求助

Discord机器人拆分命令后斜杠命令无法显示的问题解决

问题情况

将Discord机器人的命令拆分至独立文件,已添加setup函数,机器人可正常运行且setup函数的打印内容能输出,但斜杠命令无法使用,也不显示在Discord的自动补全列表中。

主文件代码

import discord
# 原代码未将创建好的intents传入Bot实例,需修正
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)

@bot.event
async def on_ready():
    print(str(bot.user) + ' has connected to Discord!')

bot.load_extension("Commands")

bot.run(TOKEN)

原命令文件代码(存在问题)

import discord
# 错误:自行创建了新的Bot实例,未使用主文件传入的bot对象
bot = discord.Bot()

def setup(bot):
    print("Hey is being unloaded!")

@bot.slash_command()
async def hey(ctx):
    print(f"Sending message to {ctx.author.name} id: = {ctx.author.id}")
    await ctx.respond(f"Hello! I'm {str(bot.user)[:-5]}!\n\nOr am I?")

错误原因

命令文件中重新创建了独立的discord.Bot实例,所有斜杠命令都注册到了这个未运行的实例上,而非主文件中正在运行的Bot实例。虽然setup函数被调用(因此打印内容能输出),但实际命令并未注册到正确的Bot对象,导致Discord端无法识别这些命令。

修复步骤

  1. 移除命令文件中自行创建的Bot实例,直接使用setup函数传入的bot参数注册命令
  2. 修正setup函数的打印信息(可选,避免混淆加载/卸载状态)
  3. 确保主文件中正确传入intents参数(原代码创建了intents但未传给Bot,可能引发其他功能异常)

修正后的命令文件代码

import discord

def setup(bot):
    print("Hey命令已加载!")

    # 使用setup传入的bot对象注册斜杠命令
    @bot.slash_command(name="hey", description="发送问候消息")
    async def hey(ctx):
        print(f"Sending message to {ctx.author.name} id: = {ctx.author.id}")
        await ctx.respond(f"Hello! I'm {str(bot.user)[:-5]}!\n\nOr am I?")

额外注意

  • 确保命令文件的目录结构正确:如果Commands是文件夹,需包含__init__.py;若为单个文件,load_extension参数应为文件名(不含.py后缀)
  • 若使用最新版discord.py,斜杠命令需同步到Discord服务器,机器人需拥有applications.commands权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:12:40