更改作者用户名 Discord.py(AFK 命令)

时间:2021-07-02 04:20:26

标签: python discord.py

我试图用这个代码制作 AFK 命令:

@bot.command(name="afk")
async def afk(ctx, username: str):
    username = ctx.message.author.name
    await ctx.author.edit(nick = f"[AFK]" + username)
    await ctx.send("Now You're in AFK Mode!")

但是我对这些代码有问题,当我运行命令时,它显示如下:

Traceback (most recent call last):
  File "C:\Users\Stawa\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Stawa\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\Stawa\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\Stawa\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\Stawa\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: username is a required argument that is missing.

1 个答案:

答案 0 :(得分:1)

我认为您使用了这样的命令:!afk
但是你应该这样使用它:!afk someName,因为你说 username 是一个必需的参数

此外,您并没有真正使用 username 参数,因为您将其替换为 ctx.auhtor.name
有一些方法可以改变这种情况:

  1. 只需删除 username 参数
@bot.command(name="afk")
async def afk(ctx):   # <--- 
    username = ctx.author.name
  1. 使用 = None 设置默认值,因此不再需要 username
    然后您可以使用 !afk
  2. 运行此命令
@bot.command(name="afk")
async def afk(ctx, username: str = None):   # <--- 
    username = ctx.author.name
  1. 检查是否给出了username,否则使用他的正常名字
    该命令可以与 !afk!afk someName
  2. 一起使用
@bot.command(name="afk")
async def afk(ctx, username: str = None):   # <--- 
    if username is None:                    # <---
        username = ctx.author.name          # <---
    #   username =  ctx.author.display_name # <- this will use the old nick, if there is one, else the name
    await ctx.author.edit(nick = f"[AFK] {username}")
    await ctx.send("Now You're in AFK Mode!")