我怎么能让它在每次用python制作的Discord机器人发送消息时都添加exp呢

我怎么能让它在每次用python制作的Discord机器人发送消息时都添加exp呢,python,python-3.x,discord,discord.py,Python,Python 3.x,Discord,Discord.py,代码(如下所示)应该在discord上为用户添加exp点。问题是,它将exp添加了1次,但再也不会添加。该用户的exp值保持在10 import discord import json import os from discord.ext import commands token = "" client = commands.Bot(command_prefix="-") os.chdir(r'C:\Users\aryaa\Desktop\testing') @client.event

代码(如下所示)应该在discord上为用户添加exp点。问题是,它将exp添加了1次,但再也不会添加。该用户的exp值保持在10

import discord
import json
import os
from discord.ext import commands

token = ""
client = commands.Bot(command_prefix="-")
os.chdir(r'C:\Users\aryaa\Desktop\testing')


@client.event
async def on_ready():
    print('Bot Is Ready')
    print('------')


@client.event
async def on_member_join(member):
    with open('users.json', 'r') as f:
        users = json.load(f)
    await update_data(users, member)
    with open('users.json', 'w') as f:
        json.dump(users, f)


@client.event
async def on_message(message):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, message.author)
    await add_experience(users, message.author, 10)
    await level_up(users, message.author, message.channel)

    with open('users.json', 'w') as f:
        json.dump(users, f)

async def update_data(users, user):
    if not user.id in users:
        users[user.id] = {}
        users[user.id]['experience'] = 0
        users[user.id]['level'] = 1

async def add_experience(users, user, exp):
    users[user.id]['experience'] += exp

async def level_up(users, user, channel):
    experience = users[user.id]['experience']
    lvl_start = users[user.id]['level']
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send(channel, '{} has leveled up to level {}'.format(user.mention, lvl_end))
        users[user.id]['level'] = lvl_end

client.run(token)

我发现了你的问题。所以基本上你的
用户
字典有整数作为键。问题是JSON不支持整数键,因此当您使用
JSON.dump
时,所有整数键都会转换为字符串。现在很明显,整数键与字符串键不同,因此您总是覆盖用户的数据,就好像他们是新用户一样

这可以通过创建一个新函数来解决,该函数在
json.load
之后,再次生成整数的所有键:

def int_键(用户):
新用户={}
对于键,users.items()中的值:
新用户[int(key)]=值
返回新用户
@客户端事件
异步def on_消息(消息):
打印(信息)
将open('users.json','r')作为f:
users=json.load(f)
用户=整数密钥(用户)
等待更新_数据(用户,message.author)
等待添加体验(用户,message.author,10)
等待级别(用户、message.author、message.channel)
将open('users.json','w')作为f:
json.dump(用户,f)
另外,如果可以的话,我建议使用discord.py重写。它使很多事情变得简单

编辑:还将其添加到成员加入脚本:

@client.event
成员加入时的异步定义(成员):
将open('users.json','r')作为f:
users=json.load(f)
用户=整数密钥(用户)
等待更新_数据(用户、成员)
将open('users.json','w')作为f:
json.dump(用户,f)

其他一切正常吗?bot是否对消息等做出反应。您正在运行哪个版本的discord.py?此代码是我在另一个文件中测试的主要bot代码的一小部分。用于其他交互的主bot的代码工作良好,并且使用相同的结构。另外,我的discord.py版本是1.3.1,它修复了主要错误,但是现在在我的代码中,我得到了一些错误,声明TypeError:object NoneType不能用于'await'表达式。我需要导入aysyncio吗?这与我添加的代码无关,因为我从未在任何地方添加等待表达式。我在测试添加到脚本中的内容时也从未遇到过这个错误。回溯看起来像什么?错误在哪一行?@Ary_2121我很乐意帮忙:)json.dump只是将整数转换成字符串而没有引起错误,这太愚蠢了。@Ary_2121现在一切都好了吗?问题解决了吗?因为你从来没有真正关闭过线程。
{"431524570131070988": {"experience": 10, "level": 1}}