Question for implementing Python schedule and dispatcher integration.

Asked 2 years ago, Updated 2 years ago, 112 views

import telegram
import schedule
import time
import sys
from telegram.ext import Updater, MessageHandler, Filters
from bs4 import BeautifulSoup
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from requests.exceptions import RequestException, ConnectionError, HTTPError, URLRequired, Timeout, TooManyRedirects

global cnt
cnt = 0
i = 0

token = ""
bot = telegram.Bot(token)
updater = Updater(token=token)
dispatcher = updater.dispatcher
updater.start_polling()

exceptions = (RequestException, ConnectionError, HTTPError, URLRequired, Timeout, TooManyRedirects)



def handler(update, context):
    global cnt
    try:
        text = update.message.text.lower()
        chat_id = update.message.chat_id

        if "?" in text:
          bot.send_message(chat_id=chat_id, text='hello!')

        if i < len(text):
          cnt += 1
          print(cnt)
          if cnt % 3 == 0:
            bot.send_message(chat_id=chat_id, text='hello!')

    except exceptions as e:
        print('>>> Network Error <<<')


def exit():
  sys.exit(0)

schedule.every().day.at("18:00").do(handler)
schedule.every().day.at("09:00").do(exit)


while True:
  schedule.run_pending()
  time.sleep(1)

echo_handler = MessageHandler(Filters.text, handler)
dispatcher.add_handler(echo_handler)

The function of sending messages unilaterally at a fixed time using a bot is easily implemented using the schedule

If dispatcher is entered, the schedule module does not seem to run normally due to duplicate use.

Make the whileTrue statement a function

def test():
    while True:
        schedule.run_pending()
        time.sleep(1)

echo_handler = MessageHandler(Filters.text, test)
dispatcher.add_handler(echo_handler)

I tried to implement it like this, but it doesn't work. I'm asking for advice from Python masters!

python telegram

2022-09-20 11:19

1 Answers

Put all the variables into the function.

This is cumbersome because you have to check where the loop is coming from, regardless of the process. Try to organize the code.

Why do you use the sys.exit() function?

The code ends when all the commands are executed anyway, so it doesn't matter if you break the loop.

This is how I would organize the code.

def Telegram function:

def Functions that wait until a specific time:


if __name__ == '__main__':
    while 1:
        Standby function operation
        Telegram Function Operation


2022-09-20 11:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.