파이썬 schedule과 dispatcher 통합 구현 질문입니다.
조회수 855회
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)
봇을 이용해 정해진 시간이 됐을 때 일방적으로 바로 메시지를 보내는 기능은 schedule을 이용하면 쉽게 구현이 되는데
dispatcher가 들어가면 중복 사용으로 schedule 모듈이 정상적으로 실행이 안 되는 것 같습니다.
while True 문을 함수로 만들어서
def test():
while True:
schedule.run_pending()
time.sleep(1)
echo_handler = MessageHandler(Filters.text, test)
dispatcher.add_handler(echo_handler)
이렇게도 구현해보았으나 작동이 안 되네요.. 파이썬 고수님들 자문을 구합니다!
1 답변
-
변수를 모조리 함수 안에 집어넣어보세요.
이런건 작업과정 하나하나마나 어디서 루프가 걸리는지 확인해야하기 때문에 번거롭습니다. 코드를 정리해보세요.
sys.exit() 함수는 왜 쓰는 건가요??
어차피 코드는 명령을 모두 수행하면 종료되기 때문에 루프에 break를 걸어줘도 상관없어 보입니다.
저라면 이런 식으로 코드를 구성할 겁니다.
def 텔레그램 함수: def 특정 시간까지 대기하는 함수: if __name__ == '__main__': while 1: 대기 함수 작동 텔레그램 함수 작동
댓글 입력