【发布时间】:2021-06-16 08:00:35
【问题描述】:
我一直在尝试使用 discord.py 创建一个简单的不和谐机器人,我也开始使用 mongodb 来存储数据并在我的笔记本电脑关机时保持我的机器人在线。我使用下面发布的代码的目标是,当任何人输入“python”这个词时,它会返回“accepted”这个词。但是,当我运行此代码时,它会显示错误:
collection.update_one(update)
NameError: name 'update' is not defined
这个问题底部显示的代码是我试图让它工作的尝试,我之前曾向人们寻求帮助,这就是 DuplicateKeyError 部分的来源。在添加之前,每当在公会中说出单词 python 时,数据库不会更新并显示重复键错误。此错误消息仍然显示,但它现在作为异常处理:(错误消息如下所示,我将实际用户 ID 替换为 USER_ID。)
raise DuplicateKeyError(error.get("errmsg"), 11000, error)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: Bot.Main index: _id_ dup key: { _id: USER_ID }, full error: {'index': 0, 'code': 11000, 'keyPattern': {'_id': 1}, 'keyValue': {'_id': USER_ID}, 'errmsg': 'E11000 duplicate key error collection: Bot.Main index: _id_ dup key: { _id: USER_ID }'}
主要错误来自 collection.update_one 行,因为它说 update 未定义。
@client.event
async def on_message(ctx):
print(f"{ctx.channel}: {ctx.author}: {ctx.author.name}: {ctx.content}")
if "python" in str(ctx.content.lower()):
post = {"_id": ctx.author.id, "score": 1}
try:
collection.insert_one(post)
except DuplicateKeyError:
collection.update_one(update)
await ctx.channel.send('accepted!')
对此的任何帮助将不胜感激。提前致谢
【问题讨论】:
标签: python database mongodb discord discord.py