Discord.py le stockage de commande de temps de récupération

0

La question

Im essayant de définir le temps de recharge pour mes commandes, mais lorsque je redémarre le bot le temps de recharge sont perdus. J'essaie de trouver un moyen de stocker les temps de récupération et de réutilisation, mais je ne pouvais pas l'atteindre en regardant 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)

trouvé ce code sur la Pile, mais il ne fonctionne pas... toute aide sera appréciée

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

La meilleure réponse

0

J'ai fait un système comme ça avant. Ce que je fais est de stocker un grand dictionnaire dans un JSON-fichier. Les clés de l'identifiant de l'utilisateur, et la valeur de type timestamp de la dernière fois qu'ils utilisé la commande.

Le code de la commande en elle-même est ici:

@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)

Remarque l' timedelta(hours=1) est le timedelta de la recharge.

get_last_used et set_last_used sont définies comme suit:

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

Dans d'autres langues

Cette page est dans d'autres langues

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