python - Discord.py Bot 每天特定时间运行功能
问题描述
我正在使用 discord.py 创建一个 discord 机器人,我需要每天在特定时间执行某些操作。我看到了这个答案:How to make a loop in discord.py rewrite? 到目前为止,我一直在使用它。
当我在 heroku 免费计划上托管我的机器人时,问题就开始了。Heroku 上的服务器每天至少重置一次,这会扰乱计时器,如该帖子所示。
我还看到了日程库。问题在于它似乎使用了无限循环。这不会阻止我在 24 小时内运行其他任何东西吗?除了每 24 小时发送一次消息外,机器人还需要能够随时响应命令。
即使服务器重置,如何每天在特定时间执行操作?先感谢您!
解决方案
您可以编写一个函数以在不同的线程上定期运行,并检查是否是发送消息的正确时间,如下例所示:
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()
推荐阅读
- r - 无法安装 rmarkdown 软件包
- c - Turtle Graphics 程序 (C) 上的不可读输入
- android - 从商店安装应用程序时无法加载谷歌地图
- python - 修改列表中项目的一部分
- dart - Dart - 有没有办法防止在编译时向不可变列表添加元素?
- sql-server - 从 C++ 应用程序读取 Microsoft SQL Server 数据库中 BIGINT 列的插入值的问题
- vue.js - Vue + Vuetify + Axios + Django:CRUD 数据表
- python - 创建元素大于 255 的 int32 列表的 SHA1 哈希
- node.js - 来自 expo-image-picker 的图像数据应该如何发送到 Express 和 Multer Endpoint?
- artificial-intelligence - 了解 AI 中的折线