为何我的Discord斜杠命令强制要求输入CTX作为必填字段?
问题原因及解决方法
你的代码出现这个问题是因为在Cog内部错误地使用了@client.slash_command装饰器,并且将命令定义在了__init__方法里。这种写法会让discord.py无法正确识别ctx作为命令上下文参数,反而把它当成了需要用户输入的必填选项。
修正后的代码
import discord from discord.ext import commands from datetime import datetime from discord import Option class Secondary(commands.Cog): def __init__(self, client): self.client = client @commands.slash_command(description="查看指定用户的头像") async def avatar(self, ctx, user: Option(discord.Member, "选择要查看头像的用户")): AvatarEmbed = discord.Embed( title=f"{user}的头像", color=discord.Colour.dark_green() ) AvatarEmbed.set_image(url=user.avatar.url) AvatarEmbed.timestamp = datetime.utcnow() await ctx.respond(embed=AvatarEmbed, ephemeral=False) def setup(client): client.add_cog(Secondary(client))
关键修改点
- 将命令从
__init__方法中移出,作为Cog类的独立方法 - 把
@client.slash_command替换为@commands.slash_command,这是Cog中定义斜杠命令的正确方式 - 给命令补充了描述文本(之前为空,不符合Discord命令规范)
- 方法第一个参数改为
self(Cog类方法的必备参数),之后才是ctx上下文参数
这样修改后,discord.py就能正确识别ctx是命令上下文,不会再把它当成用户需要输入的选项了。
内容的提问来源于stack exchange,提问作者Akio_
相关产品推荐
相关产品推荐

