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

discord.py编写Slash Commands报错:'Bot'无'slash_command'属性求助

解决discord.py中'Bot'对象无'slash_command'属性的问题

错误原因

你使用的commands.Bot类并不自带slash_command装饰器——这个写法要么来自第三方旧版斜杠命令库,要么是混淆了discord.py不同版本的API用法。当前官方discord.py(v2.x+)已原生支持斜杠命令,但API与你写的不一致。

解决方案

1. 升级discord.py到最新版本

首先确保安装支持原生斜杠命令的v2.x版本:

pip install -U discord.py

2. 修改代码适配官方斜杠命令API

替换原有的斜杠命令定义部分,使用官方的@bot.tree.command()装饰器,同时调整交互对象和回复方式:

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

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix="/", intents=intents)

@bot.event
async def on_ready():
    print(f'Zalogowano jako {bot.user.name}')
    # 同步命令到目标服务器(测试用,全局同步需1小时左右生效)
    try:
        # 替换为你的服务器ID字符串
        synced = await bot.tree.sync(guild=discord.Object(id="你的服务器ID"))
        print(f"同步了 {len(synced)} 条斜杠命令")
    except Exception as e:
        print(e)

@bot.tree.command(name="witaj", description="Komenda witająca.")
@app_commands.describe(nick="Twój nick")
async def witaj(interaction: discord.Interaction, nick: str = None):
    if nick:
        await interaction.response.send_message(f'Witaj, {nick}!')
    else:
        await interaction.response.send_message("Witaj!")

bot.run('My token')

关键变化说明

  • 新增导入discord.app_commands模块,用于定义命令参数描述
  • 使用@bot.tree.command()替代@bot.slash_command()
  • 斜杠命令函数接收discord.Interaction对象而非传统的ctx,回复需调用interaction.response.send_message()
  • 启动时同步命令到服务器:全局同步(去掉guild参数)需等待1小时左右生效,测试时建议指定服务器ID快速同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:52:47