Discord.py o armazenamento de comando recargas

0

Pergunta

Estou tentando definir o tempo de recarga para os meus comandos, mas quando eu reiniciar o bot os tempos de recarga são perdidas. Eu estou tentando encontrar uma maneira de armazenar os tempos de recarga e reutilizá-los, mas eu não poderia obter de busca do google docs

import discord 
from discord.ext import commands
cooldown_info_path = "cd.pkl"
class Bot(commands.Bot):

    async def start(self, *args, **kwargs):
        import os, pickle
        if os.path.exists(cooldown_info_path):  # on the initial run where "cd.pkl" file hadn't been created yet
            with open(cooldown_info_path, 'rb') as f:
                d = pickle.load(f)
                for name, func in self.commands.items():
                    if name in d:  # if the Command name has a CooldownMapping stored in file, override _bucket
                        self.commands[name]._buckets = d[name]
        return await super().start(*args, **kwargs)

    async def logout(self):
        import pickle
        with open(cooldown_info_path, 'wb') as f:
            # dumps a dict of command name to CooldownMapping mapping
            pickle.dump({name: func._buckets for name, func in self.commands.items()}, f)
        return await super().logout()

client = Bot(command_prefix=">")


@client.event
async def on_ready():
    print("Ready!")


@client.command()
@commands.cooldown(1, 3600, commands.BucketType.user)
async def hello(ctx):
    await ctx.send("HEY")

class ACog(commands.Cog):
    def __init__(self, client):
        self.bot = client

    @commands.command()
    @commands.cooldown(1, 600, commands.BucketType.user)
    async def ping(self, ctx):
        msg = "Pong {0.author.mention}".format(ctx)
        await ctx.send(msg)


client.add_cog(ACog(client))
client.run(token)

encontrei este código na Pilha, mas ele não funciona... qualquer ajuda será bem vinda.

discord.py
2021-11-23 15:52:34
1

Melhor resposta

0

Eu fiz um sistema como este antes. O que eu faço é armazenar uma grande dicionário em um JSON-arquivo. As chaves sendo o user-id, e o valor a ser um carimbo de data / hora do momento em que o último usado o comando.

O código para o comando em si é aqui:

@client.command()
async def hello(ctx):
    last_used_time = get_last_used(ctx.author.id)
    available_time = last_used_time + timedelta(hours=1)
    if not available_time < datetime.utcnow():
        return

    await ctx.send("HEY")

    set_last_used(ctx.author.id)

Nota o timedelta(hours=1) é o timedelta da recarga.

get_last_used e set_last_used são definidos como:

def get_last_used(user_id: int):
    with open('data/TimelyCooldowns.json') as cooldowns_file:
        cooldowns = json.loads(cooldowns_file.read())

    time_string = cooldowns.get(str(user_id))
    if time_string is not None:
        return datetime.strptime(time_string, fmt)
    else:
        return datetime.min
def set_last_used(user_id: int):
    with open('data/TimelyCooldowns.json') as cooldowns_file:
        cooldowns = json.loads(cooldowns_file.read())

    cooldowns[str(user_id)] = datetime.strftime(datetime.utcnow(), fmt)
    with open('data/TimelyCooldowns.json', 'w') as cooldowns_file:
        cooldowns_file.write(json.dumps(cooldowns, indent=4))
2021-11-26 11:59:49

Em outros idiomas

Esta página está em outros idiomas

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................