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)
time.sleep
和threading
创造奇迹。假设你的机器人的受众是那些经常忘记买胡萝卜的人。你想每分钟都提醒他们在下面的代码中,
send_reminder
函数每60秒向所有bot用户发送一次提醒(变量delay
负责秒数)。为了运行函数,我们使用线程,为了创建延迟,我们使用time.sleep(delay)
threading
是必需的,因此time.sleep()
只停止目标函数,而不是整个bot该函数使用一个无限循环,在该循环中,bot首先从
ids
向所有用户发送提醒,然后等待1分钟,然后所有内容再次重复相关问题 更多 >
编程相关推荐