-2

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

ZIKEY
  • 1
  • 1
    Where do you store the first timestamp? In general: How do you want to save the time/tell the bot that the command was executed twice and that it should count the time? – Dominik Jul 21 '21 at 18:19
  • you have to keep time in global variable - outside function. For many users you may have to keep it as global dictionary - `data[user_id] = now` – furas Jul 22 '21 at 03:35

1 Answers1

0

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}')
furas
  • 134,197
  • 12
  • 106
  • 148