首页 > 解决方案 > 如何每...分钟运行一次(pyTelegramBotAPI)

问题描述

我需要在 pyTelegramBotAPI 中每 x 分钟执行一次代码,我需要怎么做?

import telebot
from datetime import timedelta, datetime 
 
@bot.message_handler(commands=['start'])
def start_message(message): 
???

标签: pythontelegram

解决方案


time.sleepthreading创造奇迹。假设你的机器人的受众是那些经常忘记买胡萝卜的人。你想每分钟都提醒他们。

在以下代码中,该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)

推荐阅读