简体   繁体   中英

Make a chronomter with discord.py

I want to make a chronometer with Discord.py. I started writing the script but I have problems with result

I want to determine the time (in hours) between two commands. But with datetime, the strftime doesn't work.

After the .deco

@bot.command()
async def jeu(ctx):
    channel = ctx.channel
    now = datetime.now()
    await ctx.send(f'Bon jeu !')

def check(m):
    return m.content == '.deco' and m.channel == channel

msg = await bot.wait_for('message', check=check)
if msg:
    then = datetime.now()
    delta = now - then
    await ctx.send(f'Temps écoulé : {delta}')

(PS : I'm French so sry for my bad english x))

You have to keep value in global variable - it means outside function - because at this moment you keep it in local variable and you can't access it outside functions.

last_executed = None  # default value at start

@bot.command()
async def jeu(ctx):
    global last_executed  # inform function that it has to assign value to external variable

    channel = ctx.channel
    last_executed = datetime.now()
    await ctx.send(f'Bon jeu !')

# ... code ..

if msg:
    if last_executed is None:
         await ctx.send('Never executed')
    else:
        current_time = datetime.now()
        delta = last_executed - current_time
        await ctx.send(f'Delta time: {delta}')

If you run it for different users then you may need dictionary - something like this (but I didn't test it so it may need some changes)

last_executed = dict()  # default value at start

@bot.command()
async def jeu(ctx):
    global last_executed  # inform function that it has to assign value to external variable

    channel = ctx.channel
    last_executed[user_id] = datetime.now()
    await ctx.send(f'Bon jeu !')

# ... code ..

if msg:
    if user_id not in last_executed:
         await ctx.send('Never executed')
    else:
        current_time = datetime.now()
        delta = last_executed[user_id] - current_time
        await ctx.send(f'Delta time: {delta}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM