简体   繁体   English

如何安排 python 电报机器人在特定时间/之后发送消息?

[英]How do I schedule python telegram bot to send message at/after certain time?

I'm making a telegram bot using telepot to serve as a "medical" survey.我正在使用 Telepot 制作一个电报机器人作为“医疗”调查。 I've done up the bot and it is working.我已经完成了机器人并且它正在工作。 Now I want this bot to send a message automatically at certain times of the day or after 24hrs to remind the user to start the survey.现在我希望这个机器人在一天中的特定时间或 24 小时后自动发送消息,以提醒用户开始调查。 Or even better, to just start the survey automatically for the user at certain timing of the day.或者更好的是,在一天中的某个时间自动为用户启动调查。 But I'm stuck at scheduling the messages...但是我一直在安排消息...

I'm getting about 10 messages at once for some odd reasons...由于一些奇怪的原因,我一次收到大约 10 条消息......

I am using apscheduler package.我正在使用 apscheduler package。 I did manage to automate the reminder message but because of the way telepot works, each response from the user is fed into the function causing the reminder message to appear more than once after the survey ends.我确实设法自动化了提醒消息,但由于 Telepot 的工作方式,用户的每个响应都被输入 function 导致提醒消息在调查结束后出现不止一次。 I want the reminder message to appear only once a day to remind the user to start the survey.我希望提醒消息每天只出现一次,以提醒用户开始调查。 I would be happy if someone could help me fix the scheduling.如果有人可以帮助我解决日程安排,我会很高兴。 Thank you in advance.先感谢您。

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.background import BackgroundScheduler

## Load token
TOKEN = 'klaghklsfhglka'

# The main body


class main(telepot.helper.ChatHandler): # Implement continuous dialogue with user using DelegatorBot
    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'])

        schedule = BackgroundScheduler()

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

        schedule.add_job(repeat_message, 'interval', minutes=1)
        schedule.start()  # Initiates the scheduler to send automated message.

        # Survey function
        def survey():

    # Symptoms

            if self.indicator == 'choose_symptom':
                # show custom keyboard
                mark_up = ReplyKeyboardMarkup(keyboard=[['Pain'], ['Trouble with Breathing'], ['Tiredness'], ['Appetite'], ['Feeling sick'], ['Vomitting'], ['Bowel upset'], ['Hair loss']], one_time_keyboard=True)
                # keyboard options are defined in the form of arrays. Text of each array element will appear on keyboard.
                bot.sendMessage(chat_id, text='Was there any discomfort today?', reply_markup=mark_up)  # Ask user question
                self.indicator = 'rate_symptom' # move to next question

            elif self.indicator == 'rate_symptom':
                self.data['symptoms'] = msg['text'] # after moving to next section, this line of code stores the previous reply to the self.data dictionary.
                mark_up = ReplyKeyboardMarkup(keyboard=[['Not at all'],['A little'],['Somewhat'],['Very much']], one_time_keyboard=True)
                bot.sendMessage(chat_id, text='Please rate the feeling.', reply_markup=mark_up)
                self.indicator = 'set_data' # move to next section



    # Set data
    # Store data in json file. This chunk of code should be at the end of everything.

            elif self.indicator == 'set_data':
                self.data['symptoms_score'] = msg['text']
                self.data['date'] = time.ctime(msg['date']) # convert the time from long to normal format
                with open('data.json', 'a') as handle: # stores all input into a .json file.
                    json.dump(self.data, handle)
                    handle.write("\n")
                    handle.close()
                bot.sendMessage(chat_id, text='Thank you for feedback.')
         

            return


        # Detect start messages.
        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.',
                            parse_mode='Markdown')

        elif msg['text'] == '/survey':  # /survey initiates survey.
            self.indicator = 'choose_symptom'
            print("Survey started...")

        survey() #starts survey


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

MessageLoop(bot).run_as_thread() 
print('Listening...')
while 1:
    time.sleep(10)

You could look at using Task Scheduler in Windows to run the py file via cmd.您可以查看在 Windows 中使用任务计划程序通过 cmd 运行 py 文件。

Turns out I have to use a lot of counters to split the user input into different baskets... if that makes sense?原来我必须使用很多计数器将用户输入分成不同的篮子......如果这有意义吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何安排电报机器人发送消息? - how to schedule a telegram bot to send a message? 如何让我的 python 电报机器人每天在特定时间发送消息? - how to make my python telegram bot to send message at certain time every day? 用 Python 编写 Discord 机器人 - 如何让它每天在特定时间发送消息? - Programming a Discord bot in Python- How do I make it send a message every day at a certain time? 如何使用带有 python selenium 的电报机器人发送消息 - How I can send message using telegram bot with python selenium 如何通过python电报机器人库在固定时间或间隔时间从机器人向用户发送消息? - How to send message from bot to user at a fixed time or at intervals through python telegram bot library? 如何在 python 中使用 cron 和 smtp 安排电子邮件在特定时间发送? - How do I schedule an email to send at a certain time using cron and smtp, in python? 电报机器人。 如何在电报消息中打印 DataFrame? - Telegram bot. How do I print DataFrame in telegram message? 如何使用 Python 向 Telegram 中的私人链接组发送消息? - How Do I Send a Message to a Privately Linked Group in Telegram with Python? Python-telegram-bot api 'update.message.date' 返回错误的时间。 我该如何解决? - Python-telegram-bot api 'update.message.date' is returning the wrong time. how do i fix this? 如果Python脚本异常,如何从Telegram机器人发送消息? - How to send a message from a Telegram bot in case of python script exception?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM