python - 如何每...分钟运行一次(pyTelegramBotAPI)
问题描述
我需要在 pyTelegramBotAPI 中每 x 分钟执行一次代码,我需要怎么做?
import telebot
from datetime import timedelta, datetime
@bot.message_handler(commands=['start'])
def start_message(message):
???
解决方案
time.sleep
并threading
创造奇迹。假设你的机器人的受众是那些经常忘记买胡萝卜的人。你想每分钟都提醒他们。
在以下代码中,该send_reminder
函数每 60 秒向所有机器人用户发送一次提醒(该变量delay
负责秒数)。要运行该函数,我们使用线程,要创建延迟,我们使用time.sleep(delay)
. threading
需要这样才能time.sleep()
仅停止目标功能,而不是整个机器人。
该函数使用无限循环,其中机器人首先从 向所有用户发送提醒ids
,然后等待 1 分钟,一切都将再次重复。
import telebot
import threading
from time import sleep
bot = telebot.TeleBot('token')
delay = 60 # in seconds
ids = []
@bot.message_handler(commands=['start'])
def start_message(message):
global ids
id = message.from_user.id
ids.append(id)
bot.send_message(id, 'Hi!')
def send_reminder():
global ids
while True:
for id in ids:
bot.send_message(id, 'Buy some carrots!')
sleep(delay)
t = threading.Thread(target=send_reminder)
t.start()
while True:
try:
bot.polling(none_stop=True, interval=0)
except:
sleep(10)
推荐阅读
- html - 如何在css中使用父容器大小缩放图像大小?
- python-3.7 - 如何在 2 个单独的 python 列表中找到匹配项?
- javascript - 在 Aurelia 中根据 InnerHtml 更改背景颜色
- mysql - 为什么 Flask 从 Gunicorn 提供服务时拒绝关闭与数据库的连接?
- java - Activiti 的 RuntimeServiceImpl::startProcessInstanceByKey 在并发环境中无法正常工作
- mongodb - 根据另一个集合数据更新 mongo 字段
- php - PHP:如何在执行数组后从 HTML 输入标签中回显描述
- c++ - “新”创建实例的所有成员变量是否都存在于堆上而不是堆栈上?
- python - 通过字典中的 HTML 进行解析
- c++ - 在我的 c++ 应用程序中可以使用多少个线程