首页 > 解决方案 > discord.py AttributeError:“str”对象没有属性“id”

问题描述

所以问题是,我正在使用 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")

它在“如果不是 user.id in data:”中说“AttributeError:'str'对象没有属性'id'”我该如何解决?

标签: pythonstringdiscord.py

解决方案


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

@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字典,该字典加载一次,然后在您修改它时保存。


推荐阅读