【问题标题】:discord.py AttributeError: 'str' object has no attribute 'id'discord.py AttributeError:“str”对象没有属性“id”
【发布时间】:2019-05-23 00:12:05
【问题描述】:

所以问题是,我正在使用 python.py 在 python 中制作一个不和谐的机器人,并且我正在通过将某人的用户 ID 放在一个 json 文件中来发出一个命令来静音。

@client.command()
async def mute(user):
with open("muted.json", 'r') as f:
    data = json.load(f)
if not user.id in data:
    data[user.id] = {}
else:
    await client.send_message(message.channel, "The user is already muted")

在“if not user.id in data:”中说“AttributeError: 'str' object has no attribute 'id'” 我该如何解决?

【问题讨论】:

  • 尝试使用'user.id' 而不是user.id(在这两种情况下)。

标签: python string discord.py


【解决方案1】:

默认情况下,命令的所有参数都是字符串。如果您希望库为您转换它们,您必须通过提供带有类型注释的converter 来告诉它您希望它转换为什么类型。如果您想引用调用命令的message,您还必须告诉库将invocation context 传递给命令回调。

@client.command(pass_context=True)
async def mute(ctx, user: discord.User):
    with open("muted.json", 'r') as f:
        data = json.load(f)
    if not user.id in data:
        data[user.id] = {}
    else:
        await client.send_message(message.channel, "The user is already muted")

值得注意的是,这个命令实际上并没有做任何事情。它从文件中创建一个字典,对其进行修改,然后在函数结束时将其丢弃。相反,您应该有一个模块级别的 data 字典,该字典加载一次,然后在您修改它时保存。

【讨论】:

    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2021-10-04
    • 2019-12-02
    • 2021-09-25
    • 2014-03-04
    相关资源
    最近更新 更多