How to set a default using context with context defined in same line?(如何使用上下文在同一行中定义的上下文设置默认值?)
问题描述
我正在创建一个不和谐机器人,并且我正在尝试使其在成员说出没有提及用户的命令时默认为他们自己.它不能内联,我需要 arg 在同一行.
I am creating a discord bot, and I am trying to make it where if a member says a command with no user mentioned, it defaults to themself. It doesn't work inline, and I need the arg in the same line.
我尝试将默认值放在同一行,但我需要 ctx ,并且 ctx 定义在同一行中,所以它不起作用.
I tried to put the default in the same line, but I need the ctx for that, and ctx is defined in the same line, so it won't work.
@bot.command(name="joined", description="Shows precisely when a member of the server joined", aliases=["entry", "jointime", "join_time"], pass_context=True)
async def joined(**ctx**, member: discord.Member = **ctx.message.author.name**):
"""Says when a member joined."""
await ctx.send('{0.name} joined in {0.joined_at}'.format(member))
我希望当您说 !joined 或 !entry 时,没有用户提及,将用户从上下文中取出并使用它.但是,它会向我抛出错误消息未定义 ctx."
I expected this, when you say !joined or !entry, with no user mention, to take the user from the context and use that instead. However, it throws me the error message "ctx is not defined."
推荐答案
可以标记参数Optional
,然后检查协程体中是否为None
:
from discord import Member
from typing import Optional
@bot.command(name="joined", description="Shows precisely when a member of the server joined", aliases=["entry", "jointime", "join_time"], pass_context=True)
async def joined(ctx, member: Optional[Member]):
"""Says when a member joined."""
member = member or ctx.author
await ctx.send('{0.name} joined in {0.joined_at}'.format(member))
这篇关于如何使用上下文在同一行中定义的上下文设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用上下文在同一行中定义的上下文设置默认值?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01