Discord.py 我不能在 python 中使用 dict 来保存用户数据
Posted
技术标签:
【中文标题】Discord.py 我不能在 python 中使用 dict 来保存用户数据【英文标题】:Discord.py I cant use dict in python to save user data 【发布时间】:2021-09-09 15:41:48 【问题描述】:我的代码需要您的帮助。我正在尝试编写一个平衡系统,用户可以在其中提高写作水平。但我无法将用户信息保存到字典中。
“.setuplevel”命令应该将公会中的每个成员都写入字典中,除了机器人之外,并给出值 [0] = 0 和 [1] = 0。[0] 是玩家的经验,[1]是实际水平。
谁能帮帮我?
代码:
users =
async def add_experience(self, user, users):
client.users[f'user.id'][0] += 500
with open('users.yml', 'w') as outfile:
yaml.dump(client.users, outfile, default_flow_style=False)
if ((client.users[user.id][1] + 1) * 300) < client.users[user.id][0]:
print("levelup")
def saveUser(self, user_id):
print(user_id)
client.users[f'user_id'] =
client.users[f'user_id'][0] = 0
client.users[f'user_id'][1] = 0
with open('users.yml', 'w') as outfile:
yaml.dump(client.users, outfile, default_flow_style=False)
async def on_ready(self):
with open("users.yml", 'r') as stream:
client.users = yaml.safe_load(stream)
async def on_message(self, message):
if message.author == client.user:
return
elif message.content == ".setuplevel":
await message.delete()
print(message.guild.members)
for user in message.guild.members:
if not user == client.user:
print(user.id)
client.saveUser(message.author.id)
elif message.author.id not in client.last_message:
client.last_message[message.author.id] = message.created_at
else:
if (message.created_at - client.last_message[message.author.id]).total_seconds() > 25:
await client.add_experience(message.author, client.users)
这是我在调用“.setuplevel”后得到的错误:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\sanel\PycharmProjects\Log-Host\venv\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:/Users/sanel/PycharmProjects/Log-Host/main.py", line 306, in on_message
if not user == client.user:
File "C:/Users/sanel/PycharmProjects/Log-Host/main.py", line 79, in saveUser
client.users[f'user_id'] =
TypeError: 'NoneType' object does not support item assignment
【问题讨论】:
【参考方案1】:正如回溯所暗示的,“NoneType”对象不支持项目分配。这意味着 userid 的值为 None 并且您正在尝试使用 None 作为字典中的键。
【讨论】:
其实就是.users
是None
,而不是user_id
。后者是None
不会出错。
我该如何避免呢?我在代码中设置了users = ,哪里出错了?
@SanelTrnka yaml.safe_load
必须返回 None
,因为这是您设置 users
的位置。仔细检查文档以了解该方法的含义。
@Carcigenicate 是的,你是对的!非常感谢您的帮助。爱你:)以上是关于Discord.py 我不能在 python 中使用 dict 来保存用户数据的主要内容,如果未能解决你的问题,请参考以下文章
C-Python asyncio:在线程中运行 discord.py
如何在 discord.py 库中设置多个前缀或使前缀不区分大小写?