Discord.py memorizzazione di comando tempo di recupero

0

Domanda

Im cercando di impostare il tempo di recupero per i miei comandi, ma quando riavvio il bot, il tempo di recupero sono perso. Sto cercando di trovare un modo per memorizzare il tempo di recupero e il riutilizzo di loro, ma non ho potuto ottenere osservando 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)

trovato questo codice sullo Stack, ma non funziona... qualsiasi aiuto sarà apprezzato

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

Migliore risposta

0

Ho fatto un sistema come questo prima. Quello che posso fare è memorizzare una grande dizionario JSON-file. Le chiavi di essere user-id, e il valore di essere un timestamp di quando usate il comando.

Il codice per il comando di per sé è qui:

@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 il timedelta(hours=1) è il timedelta del tempo di recupero.

get_last_used e set_last_used sono definiti come:

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

In altre lingue

Questa pagina è in altre lingue

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