简体   繁体   English

使用 discord.py 制作计时器

[英]Make a chronomter with discord.py

I want to make a chronometer with Discord.py.我想用 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.但是对于日期时间,strftime 不起作用。

After the .deco .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)) (PS:我是法国人,因为我的英语不好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}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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