如何将等级添加到 discord.py 机器人的经验升级系统?

Posted

技术标签:

【中文标题】如何将等级添加到 discord.py 机器人的经验升级系统?【英文标题】:How do I add ranks to experience leveling system to discord.py bot? 【发布时间】: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 级别并返回他们在服务器中的其他排名 也请随时指出我的代码中的任何错误,我们将不胜感激。

【问题讨论】:

【参考方案1】:

索引 JSON 构建的数据库并简单地对数据进行排序非常简单。在我的示例中,我使用一个类来轻松访问每个用户的 exp。

import discord
import json

@client.command()
async def level(ctx):
    await open_account_level(ctx.author)

    users = await get_level_data()

    class LeaderBoardPosition:
        def __init__(self, id, exp):
            self.id = id
            self.exp = exp

    leaderboard = []

    for user in users:
        leaderboard.append(LeaderBoardPosition(user, users[user]["exp"]))

    top = sorted(leaderboard, key=lambda x: x.exp, reverse=True)

    for user in top:
        if user.id == str(ctx.author.id):
            ranking = top.index(user) + 1

    exp_level = users[str(ctx.author.id)]["exp"]
    bank_amt = users[str(ctx.author.id)]["exp_level"]

    embed = discord.Embed(title=f"ctx.author.name's Balance", 
                          color=discord.Color.red())
    
    embed.add_field(name="EXP", value=exp_level, inline=True)
    embed.add_field(name="EXP Level", value=bank_amt, inline=True)
    embed.add_field(name="Ranking", value=ranking, inline=True)

    await ctx.send(embed=embed)

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 file:
        json.dump(users, file)

    return True

async def get_level_data():
    with open("users.json", "r") as file:
        return json.load(file)

【讨论】:

以上是关于如何将等级添加到 discord.py 机器人的经验升级系统?的主要内容,如果未能解决你的问题,请参考以下文章

公会加入事件打印机器人被邀请 - Discord.py

Discord.py 等级卡添加文字(枕头)

Discord.py bot 在添加反应时将消息重新发送到另一个频道中断

如何在 discord.py 机器人加入语音通道之间添加暂停?

如何让不和谐机器人使用 discord.py 向消息添加表情符号反应?

如何在 discord.py 库中设置多个前缀或使前缀不区分大小写?