{discord.py-rewrite} 编写用户名和数字排行榜

{discord.py-rewrite} Writing a leader board of user's names, and numbers

如果标题没有多大意义,我很抱歉。所以我有一个不和谐的机器人,我想拥有它,所以每次有人说“鸡蛋”时,它都会给他们一分。如果他们不说鸡蛋,它会将他们的分数设置为之前分数的一半,并四舍五入,因此它没有小数。我曾尝试使用 Pickle 库保存到文件,但它看起来不对,好像它的组织方式与我的不同,它似乎只保存了它能保存的最少内容。这是我的代码目前的样子。

import discord
from discord.ext import commands
TOKEN = 'token'
bot = commands.Bot(command_prefix='!')


@bot.event
async def on_ready():
    print(f'Logged in as: {bot.user.name}')
    print(f'With ID: {bot.user.id}')

@bot.command()
async def ping(ctx):
    await ctx.send('Pong! Latency: {0}'.format(round(bot.latency, 1)))

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.channel.id == channel_id:
        if message.author == bot.user:
            return
        else:

            if ''.join(message.content.split()).lower() == "egg":
                return
            else:
                await message.channel.send(
                    "{} You fool. You absolute buffoon, it is illegal to say anything other than 'egg' in this server. I hope you feel the shame in side you. Us only saying 'egg' in this channel brings peace to our server, and you thinking your above everyone? above ME? You {}, have messed up. I want you to take a long time to reflect on your self.".format(message.author.mention, message.author.mention))
    else:
        return
    
bot.run(TOKEN)

我知道这是非常随机的。我的最终目标是拥有一个包含所有说了 egg 的用户及其当前分数的文件。如果你不想说怎么给他们加分,我也许能想出来。如果大家有什么问题,我会尽力解答的。

我想通了。

我使用的库是

import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.utils import get
import itertools
import json
from json import loads
import os

包含分数的 json 文件如下所示 https://hastebin.com/xicihepope.json {"<userID>": 46, "<userID>": 13, "<userID>": 35}

我获得单个用户分数的方法是使用此命令 https://hastebin.com/eyoleduzar.py

@bot.command()
async def eggscore(ctx, user: discord.Member=None):
    os.chdir(r'Directory_Of_Json_File')
    user = user or ctx.author
    with open('EggData.json', 'r') as file:
        data = loads(file.read())
    score = data[user.mention]
    await ctx.send(score)

我是如何更新排行榜的

我能够使用此代码对每条“egg”消息进行排行榜更新的方式。 https://hastebin.com/utakorecuc.py

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.channel.id == 783032255802245170:
        if message.author == bot.user:
            return
        else:

            if ''.join(message.content.split()).lower() == "egg":
                os.chdir(r'Directory_Of_Json_File')
                with open('EggData.json', 'r') as file:
                    data = loads(file.read())
                try:
                    author = message.author.mention
                    usernameList = data
                    authorsAmount = usernameList[author]
                    print(authorsAmount)
                    usernameList[author] += 1
                    print(usernameList[author])
                    print(usernameList)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(usernameList, outfile)
                    return
                except:
                    author = message.author.mention
                    usernameList = data
                    addUsersID = {f"{author}" : 1}
                    whatToAdd = usernameList
                    whatToAdd.update(addUsersID)
                    with open('EggData.json', 'w') as outfile:
                        json.dump(whatToAdd, outfile)
                    return
            else:
                await message.channel.send("{} You fool. You absolute buffoon, it is illegal to say anything other than 'egg' in this channel. I hope you feel the shame in side you. Us only saying 'egg' in this channel brings peace to our server, and you thinking your above everyone? above ME? You {}, have messed up. I want you to take a long time to reflect your self.".format(message.author.mention, message.author.mention))
    else:
        return

极度低效但工作排序排行榜的代码

我相信有更好的方法可以做到这一点,但我就是这样做的。 https://hastebin.com/ikagajimev.py

@bot.command()
async def eggboard(ctx, user: discord.Member=None):
    os.chdir(r'Directory_Of_Json_File')
    user = user or ctx.author
    with open('EggData.json', 'r') as file:
        data = loads(file.read())
    boardData = data
    N = 3
    out = dict(itertools.islice(data.items(), N))
    SortedTop3 = sorted(out)
    print(SortedTop3) ## THIS IS A LIST ##
    print(out) ## THIS IS A DICTIONARY ##
    print(type(SortedTop3))
    print(type(out))
    FirstPlaceThing = SortedTop3[0]
    SecondPlaceThing = SortedTop3[1]
    ThirdPlaceThing = SortedTop3[2]
    FirstPlace = out[FirstPlaceThing]
    SecondPlace = out[SecondPlaceThing]
    ThirdPlace = out[ThirdPlaceThing]
    boardList = [SortedTop3[0],FirstPlace, SortedTop3[1],SecondPlace, SortedTop3[2], ThirdPlace]
    print(boardList)
    sorted_values = sorted(out.values())
    sorted_dict = {}

    for i in sorted_values:
        for k in out.keys():
            if out[k] == i:
                sorted_dict[k] = out[k]
                break
    sorted_dict_keys = []
    for key in sorted_dict.keys():
        sorted_dict_keys.append(key)
    sorted_dict_keys_1 = sorted_dict_keys[0]
    sorted_dict_keys_2 = sorted_dict_keys[1]
    sorted_dict_keys_3 = sorted_dict_keys[2]
    print(sorted_dict)
    embed=discord.Embed(title="Egg Leaderboard")
    embed.add_field(name="First Place", value=f"{sorted_dict_keys[2]} has an egg score of {sorted_dict[sorted_dict_keys_3]}", inline=False)
    embed.add_field(name="Second Place", value=f"{sorted_dict_keys[1]} has an egg score {sorted_dict[sorted_dict_keys_2]}", inline=False)
    embed.add_field(name="Third Place", value=f"{sorted_dict_keys[0]} has an egg score of {sorted_dict[sorted_dict_keys_1]}", inline=False)
    await ctx.send(embed=embed)

如果您对如何提高效率有任何想法,请告诉我,