diff --git a/.gitignore b/.gitignore index f8b73e7..5dbde78 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ -# ---> Python +*.db +*.swp # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/counter_bot.py b/counter_bot.py new file mode 100644 index 0000000..fd90f65 --- /dev/null +++ b/counter_bot.py @@ -0,0 +1,65 @@ +import sqlite3 +from typing import List, Tuple + + +class CounterBot: + def __init__(self, db_name: str) -> None: + self.con = sqlite3.connect(db_name) + self.con.row_factory = sqlite3.Row + self.try_create_tables() + + def try_create_tables(self) -> bool: + try: + with self.con: + self.con.execute( + "CREATE TABLE presence (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME VARCHAR UNIQUE, IS_PRESENT BOOL)" + ) + print("Creating new table") + except sqlite3.OperationalError: + print("Table already exists in database, nothing to create.") + return True + + def update_presence(self, name: str, is_present: bool) -> bool: + present_int = 1 if is_present else 0 + with self.con: + self.con.execute( + f"INSERT INTO presence (NAME, IS_PRESENT) VALUES ('{name}', '{present_int}') ON CONFLICT(name) DO UPDATE SET is_present=excluded.is_present" + ) + return True + return False + + def get_full_entries(self) -> List[Tuple]: + with self.con: + return [ + (x["name"], x["is_present"]) + for x in self.con.execute( + "SELECT name, is_present FROM presence ORDER BY name" + ) + ] + + def get_present_names(self) -> List[str]: + with self.con: + return [ + x["name"] + for x in self.con.execute( + "SELECT name FROM presence WHERE is_present ORDER BY name" + ) + ] + + def get_present_count(self) -> int: + with self.con: + return self.con.execute( + "SELECT COUNT(name) FROM presence WHERE is_present" + ).fetchone()[0] + + def clear_rows(self) -> None: + with self.con: + self.con.execute("DELETE FROM presence") + + +def main() -> None: + counter_bot = CounterBot("counter.db") + + +if __name__ == "__main__": + main() diff --git a/test_counter_bot.py b/test_counter_bot.py new file mode 100644 index 0000000..8fd73bd --- /dev/null +++ b/test_counter_bot.py @@ -0,0 +1,17 @@ +import sqlite3 +from .counter_bot import CounterBot + +TEST_DB_NAME = "test.db" + +counter_bot = CounterBot(TEST_DB_NAME) +counter_bot.clear_rows() + +def test_get_present_count() -> None: + counter_bot.update_presence("Alice", True) + counter_bot.update_presence("Bob", True) + counter_bot.update_presence("Bob", False) + counter_bot.update_presence("Bob", True) + assert counter_bot.get_present_count() == 2 + +def test_present_names() -> None: + assert counter_bot.get_present_names() == ["Alice", "Bob"]