问题
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