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

我正在使用 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 作为默认参数传递?


翻阅古今
浏览 133回答 2
2回答

MM们

你可以用这个 -user&nbsp;=&nbsp;ctx.author&nbsp;if&nbsp;not&nbsp;user&nbsp;else&nbsp;user代替 -if(user&nbsp;==&nbsp;None): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user&nbsp;=&nbsp;ctx.message.author

慕码人2483693

简短的回答是你不能这样做,因为你会改变函数的签名。命令被称为期待这个签名:async&nbsp;def&nbsp;my_command(ctx,&nbsp;*args,&nbsp;**kwargs):ctx不是给定值,只是第一个参数的名称。您不能对将要使用的内容做出假设。您可以做的是假设参数的数量,按照 discord.py 文档中的示例,您可以执行以下操作:async&nbsp;def&nbsp;profile(ctx,&nbsp;*,&nbsp;user:discord.Member): &nbsp;&nbsp;&nbsp;&nbsp;member&nbsp;=&nbsp;user&nbsp;or&nbsp;ctx.message.author在此代码中,您可以假设member它始终是一个成员,除非在私人频道中它是一个用户。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python