首页 > 解决方案 > 当我尝试执行“.author”时,它不断返回错误

问题描述

这是命令的开头

@client.command()
async def rps(ctx, *, message):
    ai_choices = ['rock', 'paper', 'scissors']
    ai_choice = random.choice(ai_choices)

    message.lower()

这是逻辑语句

    if ai_choice == message:
        ctx.send(f'{message.author}, you played {message}, and Miska played {ai_choice}, so {message.author}it\'s a tie!')
    elif ai_choice == 'rock' and message == 'paper':
        ctx.send(f'{message.author}, you played paper, Miska played rock, so {message.author} YOU WIN!!')
    elif ai_choice == 'paper' and message == 'scissors':
        ctx.send(f'{message.author}, you played paper, Miska played rock, so {message.author} YOU WIN!!')
    elif ai_choice == 'scissors' and message == 'rock':
        ctx.send(f'{message.author}, you played rock, Miska played scissors, so {message.author} YOU WIN!!')
    elif ai_choice == 'rock' and message == 'scissors':
        ctx.send(f'{message.author}, you played scissors, Miska played rock, so MISKA WINS')
    elif ai_choice == 'paper' and message == 'rock':
        ctx.send(f'{message.author}, you played rock, Miska played paper, so MISKA WINS')
    elif ai.choice == 'scissors' and message == 'paper':
        ctx.send(f'{message.author}, you played paper, Miska played scissors, so MISKA WINS')
    else:
        ctx.send('Miska says, "You entered an invalid input please try entering ROCK, PAPER, or SCISSORS"')

这是省略了硬盘驱动器路径的错误日志

Ignoring exception in command rps:
Traceback (most recent call last):
  File "core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 61, in rps
    ctx.send(f'{message.author}, you played {message}, and Miska played {ai_choice}, so {message.author}it\'s a tie!')
AttributeError: 'str' object has no attribute 'author'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'author'

此外,我想不出更好的方法来让我的代码对所有 if、elifs 和 else 更有效,所以如果你有任何方法可以帮助提高效率,请告诉我,因为我对编程很陌生。

标签: pythondiscorddiscord.py

解决方案


在您的情况下,参数message实际上是一个字符串,因此错误说'str' object has no attribute 'author'.

通过您的上下文参数获取消息的作者姓名。
ctx.message.author.name.


推荐阅读