1

我正在编写一个电报机器人,我想安排它每天在特定时间发送自动消息,cron 样式。我正在使用 apscheduler 来执行此操作,但我无法让 cron 函数工作。间隔调度工作正常,但这不是我想要的。

我不想在外面执行 .py 文件,因为我需要电报机器人来检测用户的 /start 消息。

所以我想做的是检测用户的 /start 消息,然后启动调度程序。此后,该机器人将每天晚上 8 点向用户发送一条消息。

Cron 调度没有启动,我不知道为什么。我怀疑这是因为它不能在我正在运行的主线程中运行?任何意见将是有益的!谢谢你。

import time
import telepot
import json
from telepot.loop import MessageLoop
from telepot.namedtuple import ReplyKeyboardMarkup # for custom keyboard
from telepot.delegate import pave_event_space, per_chat_id, create_open
from apscheduler.schedulers.blocking import BlockingScheduler

## Load token
TOKEN = 'TOKEN NUMBER'

# The main body
class main(telepot.helper.ChatHandler): # Implement continuous dialogue with user using DelegatorBot

    global counter1
    counter1 = 0

    global counter2
    counter2 = 0

    def __init__(self, *args, **kwargs):
        super(main, self).__init__(*args, **kwargs)

        # Initialize and create empty dictionary for storing data.
        self.indicator = '0'
        self.data = {} # initialize an empty dictionary for storing data.



    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg) # this is very important.
        # Debugging
        print(content_type, chat_type, chat_id)
        print(msg['text'])
        global counter1
        global counter2
        scheduler = BackgroundScheduler()
        #scheduler_cron = BlockingScheduler()

        # Survey function
        def survey():...
   
            return

        def repeat_message():
            bot.sendMessage(chat_id, text='type /survey to repeat survey.')
            print("Reminder sent.")

        scheduler_cron.add_job(repeat_message, 'cron', day='*', week='*', day_of_week='*', hour=20, minute=00)

     

        # Detect start messages.
        while True:
            if counter2 == 11: # If survey ends AKA 11 Qns done. Restart the counters.
                counter1 = 0
                counter2 = 0

            # once bot starts, ask user to repeat survey at a specific time of the day.

            if counter1 == 0: # If survey ends or at the very beginning of using the bot.
                # Start message.
                if msg['text'] == '/start':  # /starts initiates bot. User gets greeted with a welcome message describing what the bot will do.
                    bot.sendMessage(chat_id,
                                    text='Hello there.',
                                    parse_mode='Markdown')


                    
                    scheduler_cron.start()
                    print("Scheduler started.")

                # Start survey after initializing the bot
                elif msg['text'] == '/survey':  # /survey initiates survey.
          
                    print("Survey started...")
                    #counter1 = 0
                    counter1 += 1 

                else:
                    bot.sendMessage(chat_id, text='I do not recognise your message.')
                    msg['text'] = '' # resets msg.

            
            # User starts survey
            if counter1 == 1: # if user types /survey, counter1 +=1 and when counter1 == 1, run survey function.
                survey() # starts survey
                counter2 += 1 

      
            break



bot = telepot.DelegatorBot(TOKEN, [pave_event_space()(per_chat_id(), create_open, main, timeout=60),]) 

MessageLoop(bot).run_as_thread() # Initiates the bot on telegram. Listens for user's response. If this is stopped, the entire bot stops.
print('Listening...')
while True:
    time.sleep(1)

编辑:我发现如果我有另一个线程在后台运行,如他们的文档中所述,则 apscheduler 的 cron 不起作用:

BlockingScheduler: use when the scheduler is the only thing running in your process
BackgroundScheduler: use when you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application

所以这意味着我不能使用 apscheduler 来让我的机器人工作。任何人都知道任何类似 cron 的替代方案,可以让我安排我的电报机器人在一天中的特定时间向用户发送消息?最好它必须是与电报 API 一起使用的东西。

4

0 回答 0