首页 > 解决方案 > Discord.py Bot 每天特定时间运行功能

问题描述

我正在使用 discord.py 创建一个 discord 机器人,我需要每天在特定时间执行某些操作。我看到了这个答案:How to make a loop in discord.py rewrite? 到目前为止,我一直在使用它。

当我在 heroku 免费计划上托管我的机器人时,问题就开始了。Heroku 上的服务器每天至少重置一次,这会扰乱计时器,如该帖子所示。

我还看到了日程库。问题在于它似乎使用了无限循环。这不会阻止我在 24 小时内运行其他任何东西吗?除了每 24 小时发送一次消息外,机器人还需要能够随时响应命令。

即使服务器重置,如何每天在特定时间执行操作?先感谢您!

标签: pythonherokudiscord.pyscheduler

解决方案


您可以编写一个函数以在不同的线程上定期运行,并检查是否是发送消息的正确时间,如下例所示:

from datetime import datetime
import threading


def checkTime():
    # This function runs periodically every 1 second
    threading.Timer(1, checkTime).start()

    now = datetime.now()

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

    if(current_time == '02:11:00'):  # check if matches with the desired time
        print('sending message')


checkTime()

推荐阅读