Исправление двойного ответа и улучшение системы
- Исправлен баг с двойным ответом в /getgamers (добавлена обработка ошибок) - Добавлена автоматическая миграция токенов при инициализации БД - Исправлен веб-интерфейс - теперь берет токены из user_gamers - Улучшен start.sh - создает бэкап базы перед перезапуском - Добавлен export_db.sh для экспорта базы данных - start.sh безопасно обновляет проект и сохраняет все данные
This commit is contained in:
parent
cbc5244240
commit
6cb5a9b99f
13 changed files with 186 additions and 11 deletions
|
|
@ -229,11 +229,24 @@ class LichessBot:
|
|||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
|
||||
# Edit the loading message with the results
|
||||
await loading_msg.edit_text(
|
||||
gamers_text,
|
||||
parse_mode='HTML',
|
||||
reply_markup=reply_markup
|
||||
)
|
||||
try:
|
||||
await loading_msg.edit_text(
|
||||
gamers_text,
|
||||
parse_mode='HTML',
|
||||
reply_markup=reply_markup
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error editing message: {e}")
|
||||
# If edit fails, delete the loading message and send a new one
|
||||
try:
|
||||
await loading_msg.delete()
|
||||
except:
|
||||
pass
|
||||
await update.message.reply_text(
|
||||
gamers_text,
|
||||
parse_mode='HTML',
|
||||
reply_markup=reply_markup
|
||||
)
|
||||
|
||||
async def select_gamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Handle gamer selection"""
|
||||
|
|
|
|||
|
|
@ -60,8 +60,49 @@ class Database:
|
|||
pass
|
||||
|
||||
conn.commit()
|
||||
|
||||
# Migrate tokens from gamers to user_gamers if needed
|
||||
self._migrate_tokens_from_gamers()
|
||||
|
||||
logger.info("Database initialized successfully")
|
||||
|
||||
def _migrate_tokens_from_gamers(self):
|
||||
"""Migrate tokens from old gamers table to user_gamers table if needed"""
|
||||
with sqlite3.connect(self.db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Check if there are tokens in gamers table that need migration
|
||||
cursor.execute("SELECT COUNT(*) FROM gamers WHERE token IS NOT NULL")
|
||||
gamers_with_tokens = cursor.fetchone()[0]
|
||||
|
||||
if gamers_with_tokens == 0:
|
||||
return # No tokens to migrate
|
||||
|
||||
# Check if user_gamers already has tokens
|
||||
cursor.execute("SELECT COUNT(*) FROM user_gamers WHERE token IS NOT NULL")
|
||||
user_gamers_with_tokens = cursor.fetchone()[0]
|
||||
|
||||
if user_gamers_with_tokens > 0:
|
||||
return # Migration already done
|
||||
|
||||
# Migrate tokens from gamers to user_gamers
|
||||
cursor.execute("SELECT id, token FROM gamers WHERE token IS NOT NULL")
|
||||
gamers_tokens = cursor.fetchall()
|
||||
|
||||
migrated = 0
|
||||
for gamer_id, token in gamers_tokens:
|
||||
# Update all user-gamer relationships for this gamer
|
||||
cursor.execute(
|
||||
"UPDATE user_gamers SET token = ? WHERE gamer_id = ? AND token IS NULL",
|
||||
(token, gamer_id)
|
||||
)
|
||||
migrated += cursor.rowcount
|
||||
|
||||
conn.commit()
|
||||
|
||||
if migrated > 0:
|
||||
logger.info(f"Migrated {migrated} tokens from gamers to user_gamers")
|
||||
|
||||
def add_or_get_telegram_user(self, user_id: int, username: Optional[str] = None,
|
||||
first_name: Optional[str] = None, last_name: Optional[str] = None) -> bool:
|
||||
"""Add or update Telegram user"""
|
||||
|
|
|
|||
66
LichessClientTG_bot/migrate_tokens.py
Normal file
66
LichessClientTG_bot/migrate_tokens.py
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Миграция токенов из старой таблицы gamers в новую таблицу user_gamers
|
||||
"""
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
def migrate_tokens():
|
||||
"""Migrate tokens from gamers table to user_gamers table"""
|
||||
db_path = "/app/data/lichess_bot.db"
|
||||
|
||||
try:
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверяем есть ли токены в gamers
|
||||
cursor.execute("SELECT id, username, token FROM gamers WHERE token IS NOT NULL")
|
||||
gamers_with_tokens = cursor.fetchall()
|
||||
|
||||
if not gamers_with_tokens:
|
||||
print("В базе нет токенов для миграции")
|
||||
return
|
||||
|
||||
print(f"Найдено {len(gamers_with_tokens)} игроков с токенами")
|
||||
|
||||
migrated = 0
|
||||
for gamer_id, gamer_username, token in gamers_with_tokens:
|
||||
# Находим всех пользователей, отслеживающих этого игрока
|
||||
cursor.execute("SELECT user_id FROM user_gamers WHERE gamer_id = ?", (gamer_id,))
|
||||
users = cursor.fetchall()
|
||||
|
||||
for (user_id,) in users:
|
||||
# Проверяем есть ли уже токен у этого пользователя для этого игрока
|
||||
cursor.execute(
|
||||
"SELECT token FROM user_gamers WHERE user_id = ? AND gamer_id = ?",
|
||||
(user_id, gamer_id)
|
||||
)
|
||||
existing_token = cursor.fetchone()
|
||||
|
||||
if existing_token and existing_token[0]:
|
||||
# Токен уже есть, пропускаем
|
||||
continue
|
||||
|
||||
# Переносим токен
|
||||
cursor.execute(
|
||||
"UPDATE user_gamers SET token = ? WHERE user_id = ? AND gamer_id = ?",
|
||||
(token, user_id, gamer_id)
|
||||
)
|
||||
|
||||
cursor.execute("SELECT username FROM telegram_users WHERE user_id = ?", (user_id,))
|
||||
user_data = cursor.fetchone()
|
||||
user_name = user_data[0] if user_data else f"ID:{user_id}"
|
||||
|
||||
print(f" - Перенесен токен для {gamer_username} -> пользователю @{user_name}")
|
||||
migrated += 1
|
||||
|
||||
conn.commit()
|
||||
print(f"\n✅ Миграция завершена. Перенесено {migrated} токенов")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка при миграции: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
migrate_tokens()
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue