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

discord.py斜杠命令问题求助:Bot对象无application_command属性

解决discord.py斜杠命令报错及旧命令残留问题

一、修复AttributeError: 'Bot' object has no attribute 'application_command'报错

  • 报错原因:application_command并非discord.py中Bot对象的有效方法,属于错误写法。当前discord.py的标准斜杠命令装饰器为@bot.tree.command()。
  • 代码替换示例:
    错误写法:
    @bot.application_command()
    async def hello(interaction: discord.Interaction):
        await interaction.response.send_message("Hello!")
    
    正确写法:
    @bot.tree.command(name="hello", description="发送问候消息")
    async def hello(interaction: discord.Interaction):
        await interaction.response.send_message("Hello!")
    

二、移除残留的旧斜杠命令

斜杠命令是注册在Discord服务器/全局层面的,并非仅存于本地代码,因此删去本地代码后仍会残留,可通过以下两种方式清理:

1. 代码批量清理

  • 全局清理所有命令(适用于全局注册的命令):在on_ready事件中加入清理代码,执行一次后即可移除:
    @bot.event
    async def on_ready():
        # 清理全局命令
        await bot.tree.clear_commands(guild=None)
        # 清理指定服务器的命令,将GUILD_ID替换为你的服务器ID
        # await bot.tree.clear_commands(guild=discord.Object(id=GUILD_ID))
        # 同步命令变更到Discord
        await bot.tree.sync()
        print(f"已登录为 {bot.user},旧命令已清理")
    
    注意:执行一次后建议注释清理代码,避免每次启动都清空命令。

2. 手动在Discord开发者门户删除

  • 进入Discord开发者门户,找到你的Bot应用;
  • 进入「Bot」页面,下滑找到「Commands」选项;
  • 在「Global Commands」或「Guild Commands」列表中找到残留旧命令,点击删除即可。

三、部署正确的新斜杠命令

完整示例代码:

import discord
from discord.ext import commands

# 初始化Bot,替换为你的Bot令牌
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())

@bot.event
async def on_ready():
    # 同步斜杠命令到全局,若需同步到指定服务器,添加guild参数
    # await bot.tree.sync(guild=discord.Object(id=GUILD_ID))
    await bot.tree.sync()
    print(f"已登录为 {bot.user},斜杠命令已同步")

# 定义新的斜杠命令
@bot.tree.command(name="greet", description="向用户发送问候")
async def greet(interaction: discord.Interaction, name: str):
    await interaction.response.send_message(f"你好,{name}!")

# 运行Bot,替换为你的Bot令牌
bot.run("YOUR_BOT_TOKEN")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:32:38