如何每…分钟生成一次函数(PyAPI)

2024-06-12 04:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在PyAPI中每x分钟执行一次代码。我需要怎么做

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

Tags: 代码fromimportmessagedatetimedefbotstart
1条回答
网友
1楼 · 发布于 2024-06-12 04:08:20

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

在下面的代码中,send_reminder函数每60秒向所有bot用户发送一次提醒(变量delay负责秒数)。为了运行函数,我们使用线程,为了创建延迟,我们使用time.sleep(delay)threading是必需的,因此time.sleep()只停止目标函数,而不是整个bot

该函数使用一个无限循环,在该循环中,bot首先从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)

相关问题 更多 >