How to set a default using context with context defined in same line?

老子叫甜甜 提交于 2021-02-05 11:26:05

问题


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.

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))

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."


回答1:


You can mark the parameter Optional, then check if it is None in the body of the coroutine:

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))


来源:https://stackoverflow.com/questions/58673426/how-to-set-a-default-using-context-with-context-defined-in-same-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!