如何使用远程机器人让机器人在特定时间发送一次消息?

问题描述 投票:0回答:1

我正在使用远程机器人编写一个机器人,机器人需要提醒用户他的离开。我已经确定了出发日期,我需要在出发前一天发送消息。我只需要发送一次。

我尝试了

shedule
python 模块并理解,它不能发送消息一次,并且不能在下个月发送消息,或者我不明白如何让它这样做。你能解释一下吗,还有其他方法可以做到这一点或者如何让调度程序满足我的需要吗?

python telegram telebot
1个回答
0
投票

请检查下面的代码。它运行一个每秒执行一次的线程,您可以在特定时间或每

n
秒编写一个操作。

请注意,您必须指定

chat_id

#this timer can be used to execute tasks from time to time or at a specific time

import telebot
import time, datetime
import threading 

bot = telebot.TeleBot('TOKEN')


chat_id = None

def tic_tac():

    i = 0

    while True:

        this_moment = datetime.datetime.now()

        #Executes each 60 secondss
        if ((i % 60) == 0):
            if chat_id:
                bot.send_message(chat_id, "Hello! How are you?")

        #Check if it is 12:00:00; if it is true sends the message
        if this_moment.hour == 12 and this_moment.minute == 0 and this_moment.second == 0:
            if chat_id:
                bot.send_message(chat_id, "It is the noon!")

        i += 1
        time.sleep(1)

#Needs to be started to know the chat id to send messages
@bot.message_handler(commands=['start'])
def save_chat_id(message):
    global chat_id
    chat_id = message.chat.id 
    bot.send_message(chat_id, 'I got it', reply_to_message_id=message.message_id)



timThr = threading.Thread(target=tic_tac)
timThr.start()
bot.polling(none_stop=True)```
© www.soinside.com 2019 - 2024. All rights reserved.