1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
import datetime
import signal
import sys
from os import getenv
from telegram.ext import Updater, CommandHandler, Job
from telegram import Update
from sheets_client import authenticate_and_fetch_sheets_data
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):
rows = authenticate_and_fetch_sheets_data()
message = "\n".join(map(str, rows))
context.bot.send_message(chat_id=context.job.context, text=message)
def _callback_timer(update: Update, context):
update.message.reply_text(
"HommaBot startattu. Uusia hommapäivityksiä viikon välein."
)
chats_mem_cache.add(update.message.chat_id)
context.job_queue.run_repeating(
_callback_alarm,
datetime.timedelta(seconds=10),
context=update.message.chat_id,
)
def _stop_timer(update: Update, context):
update.message.reply_text("HommaBot pysäytetty!")
chats_mem_cache.remove(update.message.chat_id)
context.job_queue.stop()
def run_telegram():
updater = Updater(getenv("TELEGRAM_TOKEN"))
updater.dispatcher.add_handler(
CommandHandler("start", _callback_timer, pass_job_queue=True)
)
updater.dispatcher.add_handler(
CommandHandler("stop", _stop_timer, pass_job_queue=True)
)
updater.start_polling()
signal.signal(signal.SIGINT, _signal_handler)
# while true:
# time.sleep(1)
signal.pause()
|