diff --git a/.gitignore b/.gitignore index 786dfee..996f484 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ *.sqlite3 -.env \ No newline at end of file +.env + +*.pyc \ No newline at end of file diff --git a/main.py b/main.py index 30d2a69..3642d62 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,4 @@ +from pprint import pprint import logging import os import sqlite3 @@ -39,7 +40,7 @@ class Bot: @property def db(self): - return sqlite3.connect(self.settings.db) + return sqlite3.connect(self.settings.db, detect_types=sqlite3.PARSE_DECLTYPES) def _init_db(self): with self.db as db: @@ -49,8 +50,8 @@ class Bot: id INTEGER PRIMARY KEY AUTOINCREMENT, link TEXT, user_id TEXT, - read_at DATETIME, - added_at DATETIME + read_at TIMESTAMP, + added_at TIMESTAMP ); """) @@ -62,11 +63,19 @@ class Bot: def cmd_test(self, update: Update, context: CallbackContext): l = Link( link="2137", - user_id="papiez" + 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() diff --git a/models.py b/models.py index df83d9a..21ed878 100644 --- a/models.py +++ b/models.py @@ -1,6 +1,8 @@ +from os import read import sqlite3 from dataclasses import dataclass from datetime import datetime +from typing import Tuple @dataclass @@ -23,3 +25,24 @@ class Link: assert len(r[0]) == 1 assert int(r[0][0]) self.id = r[0][0] + + @classmethod + def _from_tuple(cls, tuple) -> 'Link': + id, link, user_id, read_at, added_at = tuple + return cls( + id=id, + link=link, + user_id=user_id, + read_at=read_at, + added_at=added_at + ) + + @classmethod + def _get(cls, db: sqlite3.Connection, where: str, values: Tuple = ()) -> 'Link': + cur = db.cursor() + rows = cur.execute(f"SELECT * FROM links WHERE {where}", values) + return map(cls._from_tuple, rows) + + @classmethod + def get_unread(cls, db: sqlite3.Connection, user_id: str): + return cls._get(db, "user_id = ? AND read_at IS NULL", (user_id,))