From f8901d7eb97d5a03a01aae4e0593e7f61104c23c Mon Sep 17 00:00:00 2001 From: bucolucas Date: Sun, 18 Aug 2024 18:16:19 -0500 Subject: [PATCH] Add SQLite database handler --- database.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 database.py diff --git a/database.py b/database.py new file mode 100644 index 0000000..5429bee --- /dev/null +++ b/database.py @@ -0,0 +1,42 @@ +import sqlite3 +import json +from typing import List, Dict, Any + +class Database: + def __init__(self, db_file='telegram_bot.db'): + self.db_file = db_file + self.conn = sqlite3.connect(self.db_file) + self.create_tables() + + def create_tables(self): + with self.conn: + self.conn.execute(''' + CREATE TABLE IF NOT EXISTS conversations ( + user_id INTEGER PRIMARY KEY, + history TEXT + ) + ''') + + def save_conversation(self, user_id: int, history: List[Dict[str, Any]]): + with self.conn: + self.conn.execute(''' + INSERT OR REPLACE INTO conversations (user_id, history) + VALUES (?, ?) + ''', (user_id, json.dumps(history))) + + def get_conversation(self, user_id: int) -> List[Dict[str, Any]]: + cursor = self.conn.execute('SELECT history FROM conversations WHERE user_id = ?', (user_id,)) + result = cursor.fetchone() + if result: + return json.loads(result[0]) + return [] + + def clear_conversation(self, user_id: int): + with self.conn: + self.conn.execute('DELETE FROM conversations WHERE user_id = ?', (user_id,)) + + def close(self): + self.conn.close() + +# Create a global instance of the Database class +db = Database() \ No newline at end of file