如何为discord.py v2.1机器人的斜杠命令添加参数选项?
Discord.py v2.1 斜杠命令选项配置方法(Ban命令示例)
你的代码存在混用前缀命令与斜杠命令写法、上下文对象错误、参数定义不规范等问题,以下是针对discord.py v2.1的正确实现方案:
核心修正要点
- 斜杠命令需使用
@app_commands.command()装饰器,而非前缀命令的@commands.command() - 斜杠命令的选项通过类型注解+默认值配置:必填参数直接声明类型,可选参数设置默认值为
None - 斜杠命令中用
Interaction对象替代ctx,发送消息需用interaction.response.send_message()(首次响应)或interaction.followup.send()(后续消息)
修正后的完整Ban命令代码
from discord import app_commands from discord.ext import commands import discord class Moderation(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @app_commands.command(name="ban", description="[Mod] 封禁指定成员,可附带理由") @app_commands.checks.bot_has_permissions(ban_members=True) async def ban(self, interaction: discord.Interaction, member: discord.Member, reason: str = None): # 检查目标成员角色等级是否高于或等于发起者 if member.top_role >= interaction.user.top_role: await interaction.response.send_message("该成员角色等级不低于你,无法执行封禁") return # 禁止封禁机器人自身 if member.id == 791667264235634729: await interaction.response.send_message("为啥要封禁我呀?我没做错事!;-;") return # 禁止封禁自己 if member == interaction.user: await interaction.response.send_message("不能封禁自己哦!") return # 组装封禁理由并执行操作 ban_reason = f"由 {interaction.user} 封禁 | 无理由" if not reason else f"由 {interaction.user} 封禁 | {reason}" await member.ban(reason=ban_reason) # 发送封禁结果通知 await interaction.response.send_message(f"{member} 已成功封禁 {f'| 理由:{reason}' if reason else ''}") async def setup(bot: commands.Bot): await bot.add_cog(Moderation(bot))
关键细节说明
member: discord.Member:自动生成员选择器,为必填选项reason: str = None:可选文本输入框,用户可选择填写理由@app_commands.checks.bot_has_permissions(ban_members=True):斜杠命令专用的机器人权限检查装饰器- 角色等级判断用
>=,同时覆盖同等级和更高等级的情况,逻辑更严谨
内容的提问来源于stack exchange,提问作者Leon P. Keates
相关产品推荐
相关产品推荐

