fix bug web admin panel and sort list users

This commit is contained in:
vrubelroman 2025-11-13 15:27:10 +03:00
parent e645e57f74
commit 526d36bc03
2 changed files with 136 additions and 54 deletions

View file

@ -1,8 +1,6 @@
from flask import Flask, jsonify, render_template
from flask_cors import CORS
import sqlite3
import sys
import os
from datetime import datetime, date
app = Flask(__name__)
@ -11,13 +9,93 @@ CORS(app)
# Путь к базе данных бота
DB_PATH = "/app/data/lichess_bot.db"
# Add parent directory to path to import message_counters
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'LichessClientTG_bot'))
try:
from message_counters import MessageCounters
except ImportError:
# Fallback if import fails
MessageCounters = None
def get_message_counters_stats(db_path):
"""Get message counters statistics directly from database"""
try:
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
# Check if table exists
cursor.execute('''
SELECT name FROM sqlite_master
WHERE type='table' AND name='message_counters'
''')
if not cursor.fetchone():
# Table doesn't exist, return empty stats
return {
'total_all_time': 0,
'total_today': 0,
'by_command': {}
}
# Reset daily counters if needed
today = date.today()
cursor.execute('''
SELECT command, last_reset_date FROM message_counters
''')
for row in cursor.fetchall():
cmd, last_reset = row[0], row[1]
if last_reset:
try:
last_reset_date = datetime.strptime(last_reset, '%Y-%m-%d').date()
if last_reset_date < today:
cursor.execute('''
UPDATE message_counters
SET today_count = 0, last_reset_date = ?
WHERE command = ?
''', (today.isoformat(), cmd))
except (ValueError, TypeError):
cursor.execute('''
UPDATE message_counters
SET today_count = 0, last_reset_date = ?
WHERE command = ?
''', (today.isoformat(), cmd))
else:
cursor.execute('''
UPDATE message_counters
SET last_reset_date = ?
WHERE command = ?
''', (today.isoformat(), cmd))
conn.commit()
# Get all counters
cursor.execute('''
SELECT command, total_count, today_count
FROM message_counters
ORDER BY command
''')
stats = {
'by_command': {},
'total_all_time': 0,
'total_today': 0
}
for row in cursor.fetchall():
cmd, total, today = row[0], row[1], row[2]
stats['by_command'][cmd] = {
'total': total,
'today': today
}
stats['total_all_time'] += total
stats['total_today'] += today
return {
'total_all_time': stats['total_all_time'],
'total_today': stats['total_today'],
'by_command': stats['by_command']
}
except Exception as e:
print(f"Error getting message counters: {e}")
import traceback
print(traceback.format_exc())
return {
'total_all_time': 0,
'total_today': 0,
'by_command': {}
}
@app.route('/')
def index():
@ -45,7 +123,7 @@ def get_users():
FROM telegram_users tu
LEFT JOIN user_gamers ug ON tu.user_id = ug.user_id
GROUP BY tu.user_id, tu.username, tu.first_name, tu.last_name, tu.created_at
ORDER BY COALESCE(tu.first_name, tu.username, '')
ORDER BY tu.created_at DESC
''')
rows = cursor.fetchall()
@ -71,24 +149,16 @@ def get_users():
total_gamers = cursor.fetchone()[0]
# Get message counters statistics
message_stats = {}
if MessageCounters:
try:
counters = MessageCounters(db_path=DB_PATH)
message_stats = counters.get_stats_summary()
except Exception as e:
print(f"Error getting message counters: {e}")
message_stats = {
'total_all_time': 0,
'total_today': 0,
'by_command': {}
}
else:
message_stats = {
'total_all_time': 0,
'total_today': 0,
'by_command': {}
message_stats = get_message_counters_stats(DB_PATH)
# Filter out excluded commands (same as in admin_bot)
excluded_commands = {'lang', 'resetlang', 'start'}
if message_stats.get('by_command'):
filtered_by_command = {
cmd: data for cmd, data in message_stats['by_command'].items()
if cmd not in excluded_commands
}
message_stats['by_command'] = filtered_by_command
return jsonify({
'success': True,