为了账号安全,请及时绑定邮箱和手机立即绑定

Discord.py 如何将 ctx 作为默认参数传递

Discord.py 如何将 ctx 作为默认参数传递

翻阅古今 2023-05-23 10:33:17
我正在使用 Discord.py 编写配置文件命令,它打印出有关指定用户的信息。我想将消息作者作为默认参数传递,因此如果用户只写命令而没有其他任何内容,机器人将发送他们的个人资料。@bot.command()async def profile(ctx, *, user: discord.Member = ctx.message.author):上面的代码不起作用。它因以下错误而出错:Traceback (most recent call last):  File "bot.py", line 50, in <module>    async def profile(ctx, *, user: discord.Member = ctx.message.author.name):NameError: name 'ctx' is not defined谁能告诉我我做错了什么以及如何让我的代码工作?编辑:我有点绕过了这个问题:@bot.command()async def profile(ctx, *, user: discord.Member=None):        if(user == None):                user = ctx.message.author我的问题仍然存在,有没有办法将 ctx 作为默认参数传递?
查看完整描述

2 回答

?
MM们

TA贡献1886条经验 获得超2个赞

你可以用这个 -

user = ctx.author if not user else user

代替 -

if(user == None):
                user = ctx.message.author


查看完整回答
反对 回复 2023-05-23
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

简短的回答是你不能这样做,因为你会改变函数的签名。命令被称为期待这个签名:

async def my_command(ctx, *args, **kwargs):

ctx不是给定值,只是第一个参数的名称。您不能对将要使用的内容做出假设。

您可以做的是假设参数的数量,按照 discord.py 文档中的示例,您可以执行以下操作:

async def profile(ctx, *, user:discord.Member):
    member = user or ctx.message.author

在此代码中,您可以假设member它始终是一个成员,除非在私人频道中它是一个用户。


查看完整回答
反对 回复 2023-05-23
  • 2 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信