From 8f2ec2c3f9457c7fe3734a84b8c4ce727d610a20 Mon Sep 17 00:00:00 2001 From: Wojciech Kwolek Date: Sat, 16 Oct 2021 18:19:12 +0200 Subject: [PATCH] support updates --- .env.sample | 3 ++- db.sqlite3 | Bin 0 -> 12288 bytes main.py | 69 +++++++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 60 insertions(+), 12 deletions(-) create mode 100644 db.sqlite3 diff --git a/.env.sample b/.env.sample index 2150ebf..3105f7f 100644 --- a/.env.sample +++ b/.env.sample @@ -1,3 +1,4 @@ SZYNOWO_TOKEN= SZYNOWO_CHAT= -SZYNOWO_FORWARD_TO= \ No newline at end of file +SZYNOWO_FORWARD_TO= +SZYNOWO_DB= \ No newline at end of file diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000000000000000000000000000000000000..7ce44f43f3554255c7c82f4998ad79b6b7421eef GIT binary patch literal 12288 zcmeI&O-jQ+6bJB`Hrfv`qlicmVV0H_=`@W=c2)^e)K+T*yQ)z~5z#=5H^ORaLO=il5P$##AOHafKmY;|fB*#kT3{zOIiJhX zM(7^}vUeG%PPo~VmshfVJeu%X|xmRA>a`{m0QrmCIygHe^S*D5kOorZCA9u=Y z*$#XCIrig*{vKaS^PxCD;gzcAZn$;6Q?G27>kYo?Hh6j8t5vG%ify;*<@w05V?U7X z6TjP3=RNnp%a2rqGLUCoztz0x1i_#z8};T%c1PGNdtuM)i9NChcCR)N5P$##AOHaf zKmY;|fB*y_009V$T|iH2WMQ^slx(YDijv6^8d;nb1>3M3(-wxIPeuiHX+@Z}BZ@+w zh;rdrX3;JPVd&cTykJhnRX+3i-m%g#jm*syg<;uFntrWC)c;fVs`~%2e-bW)00bZa d0SG_<0uX=z1Rwwb2teQ;1=2L0q5U5alJ8JLaJT>f literal 0 HcmV?d00001 diff --git a/main.py b/main.py index a306d4d..d0710ed 100644 --- a/main.py +++ b/main.py @@ -1,9 +1,11 @@ from datetime import datetime +import sqlite3 from typing import Optional, Tuple from telegram.ext import Updater, CommandHandler, CallbackContext from telegram import Update, ParseMode import os import logging +import random from dotenv import load_dotenv load_dotenv() @@ -13,21 +15,37 @@ logging.basicConfig(level=logging.DEBUG, class Bot: - def __init__(self, token, chat, forward_to=None): + def __init__(self, token, db, chat, forward_to=None): self.chat = chat + self.db_path = db + self._init_db() self.forward_to = forward_to or [] self.updater = Updater(token=token, use_context=True) self.dispatcher = self.updater.dispatcher + self._lastid = None for f in dir(self): if f.startswith("cmd_"): self.dispatcher.add_handler( CommandHandler(f[4:], getattr(self, f))) + def db(self): + return sqlite3.connect(self.db_path) + + def _init_db(self): + with self.db() as db: + cur = db.cursor() + cur.execute(""" + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + calendar_id TEXT, + telegram_poll_id TEXT); + """) + def cmd_start(self, update: Update, context: CallbackContext): context.bot.send_message(chat_id=update.effective_chat.id, text=f'Hi! effective_chat.id={update.effective_chat.id}') - def send_event(self, date: datetime, header: str, description: str, location: str, latlong: Optional[Tuple[float, float]] = None, is_new: bool = True): + def send_event(self, id: str, date: datetime, header: str, description: str, location: str, latlong: Optional[Tuple[float, float]] = None, is_new: bool = True): messages = [] d = date.strftime("%Y-%m-%d %H:%M") text = f"""\ @@ -42,24 +60,52 @@ _{d}, {location}_ m = self.updater.bot.send_location( self.chat, latitude=latlong[0], longitude=latlong[1]) messages.append(m) - m = self.updater.bot.send_poll( - self.chat, - f'Wpadasz? ({header})', - ['Będę', 'Nie będę', '🍆'], - is_anonymous=False, - allows_multiple_answers=False, - ) - messages.append(m) + poll_id = None + if is_new: + m = self.updater.bot.send_poll( + self.chat, + f'Wpadasz? ({header})', + ['Będę', 'Nie będę', '🍆'], + is_anonymous=False, + allows_multiple_answers=False, + ) + poll_id = m.message_id + with self.db() as db: + cur = db.cursor() + cur.execute( + "INSERT INTO events(calendar_id, telegram_poll_id) VALUES (?, ?)", (str(id), str(poll_id))) + else: + with self.db() as db: + cur = db.cursor() + rows = list(cur.execute( + "SELECT * FROM events WHERE calendar_id = ?;", (str(id),))) + if len(rows) != 1: + raise Exception( + f"None/multiple events with id {id} found in the database") + id, calendar_id, telegram_poll_id = rows[0] + poll_id = telegram_poll_id for chat in self.forward_to: for msg in messages: msg.forward(chat) + self.updater.bot.forward_message( + chat_id=chat, from_chat_id=self.chat, message_id=poll_id) def cmd_test(self, update: Update, context: CallbackContext): context.bot.send_message(chat_id=self.chat, text="Test") - self.send_event(datetime.now(), "Header", + id = str(random.randrange(2137, 19823198)) + self._lastid = id + + self.send_event(id, datetime.now(), "Header", "Description", "Szynowa 18", (51.060938, 17.057193)) + def cmd_update(self, update: Update, context: CallbackContext): + context.bot.send_message(chat_id=self.chat, text="Test") + id = self._lastid + + self.send_event(id, datetime.now(), "Header2", + "Description2", "new location", (51.060938, 10), is_new=False) + def cmd_location(self, update: Update, context: CallbackContext): print(type(update)) context.bot.send_location( @@ -76,6 +122,7 @@ if __name__ == '__main__': b = Bot( token=os.environ['SZYNOWO_TOKEN'], chat=os.environ['SZYNOWO_CHAT'], + db=os.environ['SZYNOWO_DB'], forward_to=[s.strip() for s in os.environ.get( 'SZYNOWO_FORWARD_TO', '').split(',')], )