ReadLater/main.py

91 lines
2.4 KiB
Python

from pprint import pprint
import logging
import os
import sqlite3
from dataclasses import dataclass
from datetime import datetime
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import CallbackContext, CommandHandler, Updater
from models import Link
load_dotenv()
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
@dataclass
class BotSettings:
token: str
db: str
class Bot:
def __init__(self, settings: BotSettings):
self.settings = settings
self._init_db()
self.updater = Updater(token=self.settings.token, use_context=True)
self.dispatcher = self.updater.dispatcher
self._register_commands()
def _register_commands(self):
for f in dir(self):
if f.startswith("cmd_"):
self.dispatcher.add_handler(
CommandHandler(f[4:], getattr(self, f)))
@property
def db(self):
return sqlite3.connect(self.settings.db, detect_types=sqlite3.PARSE_DECLTYPES)
def _init_db(self):
with self.db as db:
cur = db.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
link TEXT,
user_id TEXT,
read_at TIMESTAMP,
added_at TIMESTAMP
);
""")
def cmd_start(self, update: Update, context: CallbackContext):
context.bot.send_message(chat_id=update.effective_chat.id, text='Hi!')
# TODO: timezones
# TODO: ask to set time or something
def cmd_test(self, update: Update, context: CallbackContext):
l = Link(
link="2137",
user_id=update.effective_user.id
)
with self.db as db:
l.create(db)
def cmd_unread(self, update: Update, context: CallbackContext):
# TODO: ignore messages from group
user_id = update.effective_user.id
with self.db as db:
links = Link.get_unread(db, user_id)
pprint(list(links))
def run(self):
self.updater.start_polling()
if __name__ == '__main__':
s = BotSettings(
token=os.environ['READLATER_TOKEN'],
db=os.environ.get('READLATER_DB', './db.sqlite3'),
)
b = Bot(s)
b.run()