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
相关产品推荐
相关产品推荐

