Files
telegram_bot/database_manager.py

49 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sqlite3
class DatabaseManager:
def __init__(self,db_name="bot_hafiza.db"):
self.db_name=db_name
self.tabloyu_hazirla()
def baglan(self):
return sqlite3.connect(self.db_name)
def tabloyu_hazirla(self):
sql_komutu = """
CREATE TABLE IF NOT EXISTS hafiza (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
role TEXT,
content TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
"""
with self.baglan() as conn:
cursor=conn.cursor()
cursor.execute(sql_komutu)
conn.commit()
def mesaj_kaydet(self, user_id, role, content):
"""Sohbetin her adımını veritabanına bir satır olarak ekler."""
sql = "INSERT INTO hafiza (user_id, role, content) VALUES (?, ?, ?)"
with self.baglan() as conn:
cursor = conn.cursor()
cursor.execute(sql, (user_id, role, content))
conn.commit()
def gecmisi_getir(self, user_id, limit=10 ):
"""Gemini'ye hatırlatmak için son 10 mesajı veritabanından çeker."""
sql = "SELECT role, content FROM hafiza WHERE user_id = ? ORDER BY id DESC LIMIT ?"
with self.baglan() as conn:
cursor = conn.cursor()
cursor.execute(sql, (user_id, limit))
sonuclar = cursor.fetchall()
return sonuclar[::-1]