【发布时间】:2021-12-21 00:08:49
【问题描述】:
如何将等级添加到 discord.py 机器人的经验升级系统。这是我一直在使用的代码,任何帮助将不胜感激
import discord
from discord.ext import commands
from discord.utils import get
import json
client = commands.Bot(command_prefix="!")
@client.event
async def on_message(message):
if not message.author.bot:
await open_account_level(message.author)
users = await get_level_data()
await add_experience(users, message.author, 5)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await client.process_commands(message)
#command to check your level details
@client.command()
async def level(ctx):
await open_account_level(ctx.author)
users = await get_level_data()
user = ctx.author
exp_level = users[str(user.id)]["Exp"]
bank_amt = users[str(user.id)]["Exp Level"]
em = discord.Embed(title=f"{ctx.author.name}'s balance", color=discord.Color.red())
em.add_field(name="Exp", value=exp_level)
em.add_field(name="Exp Level", value=bank_amt)
await ctx.send(embed=em)
#adds exp to your account
async def add_experience(users, user, exp):
users[f'{user.id}']['Exp'] += exp
#levels you up after an exp limit
async def level_up(users, user, message):
with open('users.json', 'r') as g:
levels = json.load(g)
experience = users[f'{user.id}']['Exp']
lvl_start = users[f'{user.id}']['Exp Level']
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f'{user.mention} has leveled up to level {lvl_end}')
users[f'{user.id}']['Exp Level'] = lvl_end
#creates an account for you in a json file
async def open_account_level(user):
users = await get_level_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["Exp"] = 0
users[str(user.id)]["Exp Level"] = 0
with open("users.json", "w") as f:
json.dump(users, f)
return True
async def get_level_data():
with open("users.json", "r") as f:
users = json.load(f)
return users
TOKEN = 'token'
client.run(TOKEN)
我想要排名,以便它显示最高 exp 级别并返回他们在服务器中的其他排名 也请随时指出我的代码中的任何错误,我们将不胜感激。
【问题讨论】:
标签: python discord discord.py bots