【问题标题】:{discord.py-rewrite} Writing a leader board of user's names, and numbers{discord.py-rewrite} 编写用户名和数字的排行榜
【发布时间】:2020-12-25 09:55:07
【问题描述】:

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

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

【问题讨论】:

  • 您可以尝试SQLite 之类的库或yamljsontxt 之类的文件。对于这个程序,我更喜欢 SQLitejson
  • @Nurqm 感谢您的评论,我会研究 SQLite 和 json。
  • @Nurqm 我用 json 做实验,但我似乎无法理解它,我无法理解 SQLite,所以我不知道如何使用这些库达到我的最终目标.如果你能,你能回答这个问题吗?可能解释我需要做什么,或者怎么做?
  • 您应该使用其中之一。我不能从一开始就教你整个图书馆。
  • 我也推荐 SQLite 和 MySQL。它们非常简单高效。 MySQL 数据库是我目前用来存储玩家信息的数据库。它们与 RPG 不和谐机器人配合得非常好。

标签: python python-3.x discord discord.py discord.py-rewrite


【解决方案1】:

我能够弄清楚这一点。

我使用的库是

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)

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

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 2021-09-14
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 2014-08-28
    • 2021-04-20
    相关资源
    最近更新 更多