import datetime import signal import sys import logging from os import getenv from telegram.ext import Updater, CommandHandler, Job from telegram import Update from sheets_client import authenticate_and_fetch_sheets_data from parser import process_rows chats_mem_cache = set() def _signal_handler(sig, frame): print("You pressed Ctrl+C!") updater = frame.f_locals["updater"] for chat_id in chats_mem_cache: updater.bot.send_message(chat_id=chat_id, text="HommaBot-palvelin sammutettu!") updater.stop() sys.exit(0) def _callback_alarm(context): chat_id = context.job.context logging.info(f"Authenticating and fetching data from Sheets...") rows = authenticate_and_fetch_sheets_data() logging.info(f"Processing data...") processed_data = process_rows(rows) logging.info(f"Sending sheet data to chat id {chat_id}...") message = "\n".join(map(str, processed_data)) context.bot.send_message(chat_id=chat_id, text=message) def _callback_timer(update: Update, context): chat_id = update.message.chat_id logging.info(f"Starting timer in chat id {chat_id}...") update.message.reply_text( "HommaBot startattu. Uusia hommapäivityksiä viikon välein." ) chats_mem_cache.add(chat_id) context.job_queue.run_repeating( _callback_alarm, datetime.timedelta(weeks=1), 1, # run immediately context=chat_id, ) def _stop_timer(update: Update, context): chat_id = update.message.chat_id logging.info(f"Stopping timer in chat id {chat_id}...") update.message.reply_text("HommaBot pysäytetty!") chats_mem_cache.remove(chat_id) context.job_queue.stop() def run_telegram(): tg_token = getenv("TELEGRAM_TOKEN") logging.info("Creating Telegram bot object...") updater = Updater(tg_token) logging.info("Registering Telegram bot /start handler...") updater.dispatcher.add_handler( CommandHandler("start", _callback_timer, pass_job_queue=True) ) logging.info("Registering Telegram bot /stop handler...") updater.dispatcher.add_handler( CommandHandler("stop", _stop_timer, pass_job_queue=True) ) logging.info("Starting Telegram bot (HommaBot)...") updater.start_polling() logging.info("Registering SIGINT handler...") signal.signal(signal.SIGINT, _signal_handler) logging.info("Bot started successfully. Pausing main thread... (this is expected)") signal.pause()