如何使用discord.py中的任务?

How to use tasks in discord.py?

我希望机器人在指定时间 运行 执行一项功能。在尝试了 100 种不同的东西之后,我写了这个:

@tasks.loop(seconds=5)
async def checkTime():

    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)

    if current_time == '16:41:00':  
        channel = bot.get_channel(746339276983238677)
        await channel.send("It's time.")
        print('its time')
checkTime.start()

它每 5 秒后在控制台中打印 current_time,但它不会向频道发送任何消息,也不会在指定的时间在控制台中打印 it's time。它不会抛出任何错误,所以我不知道出了什么问题。 可以的话请回答。

current_time = now.strftime("%H:%M:%S") returns 你 datetime 键入,而不是 str。所以你不能比较 datetimestr。您必须将 datetime 转换为 str.

因此,如果您执行 current_time = str(now.strftime("%H:%M:%S"))if str(current_time) == '16:41:00':,它就会成功。

编辑

要获取日期的名称,可以使用%A,例如:

today = datetime.datetime.now()
day_name = today.strftime('%A')
if day_name == 'Sunday':
    #do whatever you want