当我在数据库中将赢数增加1并返回用户所拥有的赢数时,它总是关闭1。
例如下面的代码:
import discord
import pymongo
client = discord.Client()
mongo = MongoClient('localhost', 27017)
db = mongo.collection
profiles = db.profiles
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!iwin'):
profile = profiles.find_one({'discordID': message.author.id})
updatewin = profiles.find_one_and_update({'discordID': message.author.id}, {"$inc":
{"wins": 1, "coins": 40}})
win_msg = "Your win has been recorded. You have {} wins!".format(profile['wins'])
如果我输入!iwin,则1胜利将记录在数据库中,但是返回的消息是Your win has been recorded. You have 0 wins!
而且,如果我再次输入!iwin,则会记录第二个胜利,共获得2个胜利,但是消息显示为Your win has been recorded. You have 1 wins!
在我看来,消息是在增量发生之前发送的,我该如何解决?
编辑 它还会影响我尝试使用wins字段添加的任何类型的操作。例如:
win_msg = "Your win has been recorded."
await message.channel.send(win_msg)
if profile['wins']%2==0:
roll = random.randint(1,809)
roll_msg = "You have won 2 games! Here is your roll: {}. Would you like to !keep or !reroll?".format(roll)
await message.channel.send(roll_msg)
它总是计算错误。因此,如果我在DB中有2场胜利,则不会出局,但如果我在DB中有1场胜利,则不会来计算出局。
答案 0 :(得分:1)
您可以在字符串格式中明确添加1。看起来像:
win_msg = "Your win has been recorded. You have {} wins!".format(int(profile['wins']) + 1)
您可能也不需要int()
,但是我通常会把它戴在身上,因此计算机和我的未来自我都清楚我的意图。
根据您的更新,似乎您的数据库实际上并未按照您期望的方式进行更新。我不确定您的find_one()
方法返回什么,但是它可能是一个静态值(将其包含在您的帖子中可能是一个好主意)。您是否尝试过使用此类打印语句进行验证? (此外,我认为您的if
块应该缩进了?)
if message.content.startswith('!iwin'):
profile = profiles.find_one({'discordID': message.author.id})
print(profile)
updatewin = profiles.find_one_and_update({'discordID': message.author.id}, {"$inc":{"wins": 1, "coins": 40}})
print(profile) # has this changed?
# maybe you need to call your find_one method again? Like
profile = profiles.find_one({'discordID': message.author.id})
print(profile) # is it updated now??