![](/img/trans.png)
[英]How can I send a message to every server the bot is in with python discord
[英]How can i have it so it add exp every time a message is sent on a Discord bot made in python
代碼(如下所示)應該在不和諧的情況下向用戶添加 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 文件。 如您所見,它顯示了 10 個 expr。 我已經發送了大約 15 條消息,但這個值永遠不會改變,所以我不知道這不更新背后的原因是什么。
{"431524570131070988": {"experience": 10, "level": 1}}
我發現了你的問題。 所以基本上你的users
字典有整數作為鍵。 問題是JSON 不支持整數鍵,因此當您使用json.dump
所有整數鍵都會轉換為字符串。 現在顯然整數鍵與字符串鍵不同,因此您總是會覆蓋用戶的數據,就好像他們是新用戶一樣。
這是通過創建一個新函數來解決的,該函數在json.load
之后json.load
將所有鍵設為整數:
def int_keys(users):
new_users = {}
for key, value in users.items():
new_users[int(key)] = value
return new_users
@client.event
async def on_message(message):
print(message)
with open('users.json', 'r') as f:
users = json.load(f)
users = int_keys(users)
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)
另外,如果可以的話,我真的建議使用 discord.py 重寫。 它讓很多東西變得更簡單。
編輯:還將其添加到 member_join 腳本中:
@client.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)
users = int_keys(users)
await update_data(users, member)
with open('users.json', 'w') as f:
json.dump(users, f)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.