python - 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'”我该如何解决?
解决方案
默认情况下,命令的所有参数都是字符串。如果您希望库为您转换它们,您必须通过提供带有类型注释的转换器来告诉它您希望它转换为什么类型。如果你想引用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
字典,该字典加载一次,然后在您修改它时保存。
推荐阅读
- angularjs - 如何禁用 ag-grid 中的整个列
- wordpress - 如何在 IIS 上使用 Word Press 修复添加插件错误?
- android - CoordinatorLayout (Toolbar+NestedScrollView+BottomNavigationView) 问题
- java - textinputlayout 密码切换图标被阻止
- java - 在Java中的另一个模型类中注入MVC模型类
- javascript - 在javascript中使.value值为0而不是null
- swift - 如何将本地 HTML 加载到我的 WebView 中?
- java - 如何让我的 SWT 应用程序在 Java 32 位和 Java 64 位机器上运行
- jekyll - jekyll 类别多词输出没有空格
- javascript - scrollTop addclass 跳转