Telegram-Bot / content /database.py
H3y-sam's picture
Upload 54 files
94b42f2 verified
Raw History Blame Contribute Delete
9.13 kB
import sqlite3
import logging
import os
import json
import re
logger = logging.getLogger(__name__)
DB_PATH = "data/bot_data.db"
SEEN_NEWS_FILE = "data/seen_news.json"
_seen_news_cache = {}
def load_seen_news():
global _seen_news_cache
try:
from content.remote_storage import pull_from_gist
pulled = pull_from_gist("seen_news.json")
if pulled and isinstance(pulled, dict):
_seen_news_cache = pulled
logger.info(f"Loaded {len(_seen_news_cache)} seen news items from Gist.")
# Sync to SQLite
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
for t, l in _seen_news_cache.items():
cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (t, l))
conn.commit()
conn.close()
return
except Exception as e:
logger.error(f"Error loading seen news from Gist: {e}")
# Fallback to local
if os.path.exists(SEEN_NEWS_FILE):
try:
with open(SEEN_NEWS_FILE, "r") as f:
_seen_news_cache = json.load(f)
except Exception as e:
logger.error(f"Local seen news load error: {e}")
_seen_news_cache = {}
# Ensure database is initialised before calling load_seen_news
def init_db():
os.makedirs("data", exist_ok=True)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Leaderboard table
# We track scores per user per channel to keep it fair
cursor.execute("""
CREATE TABLE IF NOT EXISTS leaderboard (
user_id INTEGER,
channel_id TEXT,
username TEXT,
full_name TEXT,
score INTEGER DEFAULT 0,
streak INTEGER DEFAULT 0,
last_streak_date TEXT,
last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, channel_id)
)
""")
# News tracker table to avoid duplicates
# Uses title as unique identifier for permanent deduplication
cursor.execute("""
CREATE TABLE IF NOT EXISTS seen_news (
title TEXT PRIMARY KEY,
link TEXT UNIQUE,
fetch_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Poll tracker to know which option is correct for a given poll_id
cursor.execute("""
CREATE TABLE IF NOT EXISTS poll_tracker (
poll_id TEXT PRIMARY KEY,
channel_id TEXT,
message_id INTEGER,
correct_index INTEGER,
explanation TEXT
)
""")
conn.commit()
conn.close()
# Now load the Gist-synced cache after DB init
load_seen_news()
def update_score(user_id, channel_id, username, full_name, points=1):
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO leaderboard (user_id, channel_id, username, full_name, score)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(user_id, channel_id) DO UPDATE SET
score = score + ?,
username = ?,
full_name = ?,
last_active = CURRENT_TIMESTAMP
""", (user_id, channel_id, username, full_name, points, points, username, full_name))
conn.commit()
conn.close()
except Exception as e:
logger.error(f"DB Error (update_score): {e}")
def get_top_students(channel_id, limit=10):
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
SELECT username, full_name, score FROM leaderboard
WHERE channel_id = ?
ORDER BY score DESC, last_active DESC
LIMIT ?
""", (channel_id, limit))
rows = cursor.fetchall()
conn.close()
return rows
except Exception as e:
logger.error(f"DB Error (get_top_students): {e}")
return []
def clear_weekly_scores():
"""Reset scores for the new week (run by scheduler)"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("UPDATE leaderboard SET score = 0")
conn.commit()
conn.close()
except Exception as e:
logger.error(f"DB Error (clear_scores): {e}")
def is_news_seen(title):
"""Check if a news item with this exact title has been posted before (case & space insensitive)."""
cleaned_title = re.sub(r'\s+', ' ', title).strip().lower()
# 1. Check local cache memory
for cached_title in _seen_news_cache:
if re.sub(r'\s+', ' ', cached_title).strip().lower() == cleaned_title:
return True
# 2. Check local database
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT title FROM seen_news")
rows = cursor.fetchall()
conn.close()
for (t,) in rows:
if re.sub(r'\s+', ' ', t).strip().lower() == cleaned_title:
return True
except Exception as e:
logger.error(f"Error checking seen news in SQLite: {e}")
return False
def mark_news_seen(title, link=""):
"""Mark a news item as seen. Uses title as unique identifier."""
# Update local cache memory
_seen_news_cache[title] = link
# Save to local file
try:
os.makedirs("data", exist_ok=True)
with open(SEEN_NEWS_FILE, "w") as f:
json.dump(_seen_news_cache, f, indent=2)
except Exception as e:
logger.error(f"Error saving seen news to local JSON: {e}")
# Push to Gist
try:
from content.remote_storage import push_to_gist
push_to_gist("seen_news.json", _seen_news_cache)
except Exception as e:
logger.error(f"Error pushing seen news to Gist: {e}")
# Save to SQLite
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (title, link))
conn.commit()
conn.close()
except Exception as e:
logger.error(f"Error marking news seen in SQLite: {e}")
def track_poll(poll_id, channel_id, message_id, correct_index, explanation=None):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("INSERT INTO poll_tracker (poll_id, channel_id, message_id, correct_index, explanation) VALUES (?, ?, ?, ?, ?)",
(poll_id, channel_id, message_id, correct_index, explanation))
conn.commit()
conn.close()
def get_poll_data(poll_id):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT channel_id, message_id, correct_index FROM poll_tracker WHERE poll_id = ?", (poll_id,))
res = cursor.fetchone()
conn.close()
return res # returns (channel_id, message_id, correct_index) or None
def get_poll_explanation(poll_id):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT explanation FROM poll_tracker WHERE poll_id = ?", (poll_id,))
res = cursor.fetchone()
conn.close()
return res[0] if res else None
def update_streak(user_id, channel_id):
"""
Update user's daily streak.
Returns (new_streak, increased)
"""
from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d")
yesterday = (datetime.now().timestamp() - 86400)
yesterday_str = datetime.fromtimestamp(yesterday).strftime("%Y-%m-%d")
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Get current streak info
cursor.execute("SELECT streak, last_streak_date FROM leaderboard WHERE user_id = ? AND channel_id = ?", (user_id, channel_id))
row = cursor.fetchone()
if not row:
# New user entry will be handled by update_score, but we can init here
cursor.execute("INSERT OR IGNORE INTO leaderboard (user_id, channel_id, streak, last_streak_date) VALUES (?, ?, ?, ?)",
(user_id, channel_id, 1, today))
conn.commit()
conn.close()
return 1, True
streak, last_date = row
if last_date == today:
conn.close()
return streak, False # Already updated today
if last_date == yesterday_str:
new_streak = streak + 1
else:
new_streak = 1 # Streak broken
cursor.execute("UPDATE leaderboard SET streak = ?, last_streak_date = ? WHERE user_id = ? AND channel_id = ?",
(new_streak, today, user_id, channel_id))
conn.commit()
conn.close()
return new_streak, True
except Exception as e:
logger.error(f"DB Error (update_streak): {e}")
return 0, False