Update bot.py

This commit is contained in:
DerrtSML 2025-06-23 20:05:07 +03:00 committed by GitHub
parent f10f275d34
commit c727bcbc96
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

87
bot.py
View File

@ -242,7 +242,94 @@ async def start_torrent_callback(update: Update, context: ContextTypes.DEFAULT_T
except Exception as e:
logger.error(f"An unexpected error occurred during torrent resuming: {e}")
await query.edit_message_text(f"Произошла непредвиденная ошибка: {e}")
# --- Команда /status (добавляем логирование) ---
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.message is None:
logger.warning("Received an update without a message object in status handler.")
return
logger.info(f"Received /status command from {update.effective_user.id}")
if not init_qbittorrent_client():
await update.message.reply_text(
"Не удалось подключиться к qBittorrent. Проверьте переменные окружения и доступность сервера."
)
return
try:
torrents = qb.torrents_info()
if not torrents:
await update.message.reply_text("Загрузок не найдено.")
return
for torrent in torrents:
# --- ВРЕМЕННОЕ ЛОГИРОВАНИЕ ---
logger.info(f"Torrent '{torrent.name}' has state: '{torrent.state}'")
# --- КОНЕЦ ВРЕМЕННОГО ЛОГИРОВАНИЯ ---
download_speed = torrent.dlspeed / (1024 * 1024) if torrent.dlspeed >= (1024 * 1024) else torrent.dlspeed / 1024
upload_speed = torrent.upspeed / (1024 * 1024) if torrent.upspeed >= (1024 * 1024) else torrent.upspeed / 1024
dl_unit = "MB/s" if torrent.dlspeed >= (1024 * 1024) else "KB/s"
up_unit = "MB/s" if torrent.upspeed >= (1024 * 1024) else "KB/s"
eta_str = ""
if torrent.eta == 8640000:
eta_str = ""
elif torrent.eta > 0:
hours, remainder = divmod(torrent.eta, 3600)
minutes, seconds = divmod(remainder, 60)
if hours > 0:
eta_str = f"{int(hours)}ч {int(minutes)}мин"
elif minutes > 0:
eta_str = f"{int(minutes)}мин {int(seconds)}с"
else:
eta_str = f"{int(seconds)}с"
else:
eta_str = "Завершено"
message_text = (
f"📊 *{torrent.name}*\n"
f" Состояние: {torrent.state}\n"
f" Прогресс: {torrent.progress:.2%}\n"
f" ⬇️ {download_speed:.2f} {dl_unit} ⬆️ {upload_speed:.2f} {up_unit}\n"
f" ETA: {eta_str}\n"
f" Размер: {(torrent.size / (1024*1024*1024)):.2f} ГБ"
)
keyboard = []
active_states = ['downloading', 'stalledDL', 'uploading', 'checkingQT', 'queuedDL', 'checkingUP', 'queuedUP']
# Здесь пока не меняем, чтобы увидеть, что попадет в "else"
paused_states = ['pausedDL', 'pausedUP', 'Stopped', 'Completed']
if torrent.state in active_states:
keyboard.append(InlineKeyboardButton("🔴 Остановить", callback_data=f"stop_hash_{torrent.hash}"))
elif torrent.state in paused_states:
keyboard.append(InlineKeyboardButton("▶️ Запустить", callback_data=f"start_hash_{torrent.hash}"))
elif torrent.state == 'metaDL':
pass
else:
# Если торрент не в активных и не в явных "пауза/остановлено", то "Инфо"
keyboard.append(InlineKeyboardButton(" Инфо", callback_data=f"info_hash_{torrent.hash}"))
reply_markup = InlineKeyboardMarkup([keyboard]) if keyboard else None
await update.message.reply_text(
message_text,
parse_mode="Markdown",
reply_markup=reply_markup
)
except APIError as e:
logger.error(f"Error getting torrent status: {e}")
await update.message.reply_text(f"Ошибка при получении статуса торрентов: {e}")
except Exception as e:
logger.error(f"An unexpected error occurred in status command: {e}")
await update.message.reply_text(f"Произошла непредвиденная ошибка: {e}")
# ... (Остальной код бота без изменений) ...
# --- Обработка magnet-ссылок и URL ---
async def handle_url(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: