首页 > 解决方案 > {discord.py-rewrite} 编写用户名和数字的排行榜

问题描述

如果标题没有多大意义,我很抱歉。所以我有一个我想要的不和谐机器人,所以每次有人说“鸡蛋”时,它都会给他们一分。如果他们不说鸡蛋,它会将他们的分数设置为之前分数的一半,并四舍五入,所以它没有小数。我尝试使用 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)

我知道这是非常随机的。我的最终目标是拥有所有说鸡蛋的用户的文件,以及他们当前的分数。如果你不想说如何给他们分数,我也许能弄清楚。如果您有任何问题,我会尽力回答。

标签: pythonpython-3.xdiscorddiscord.pydiscord.py-rewrite

解决方案


我能够弄清楚这一点。

我使用的库是

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)

我是如何更新排行榜的

我能够使用此代码对每条“鸡蛋”消息进行排行榜更新的方式。 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)

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


推荐阅读