Update bot.py

This commit is contained in:
DerrtSML 2025-06-23 20:14:10 +03:00 committed by GitHub
parent eb12643396
commit a7ef629b48
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

20
bot.py
View File

@ -79,7 +79,7 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"Используй /help для списка команд." "Используй /help для списка команд."
) )
# --- Команда /help --- # --- Команда /help (ИСПРАВЛЕНО форматирование Markdown) ---
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.message is None: if update.message is None:
logger.warning("Received an update without a message object in help handler.") logger.warning("Received an update without a message object in help handler.")
@ -93,13 +93,13 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
"**/status** - Показать текущий статус всех активных загрузок и управлять ими.\n" "**/status** - Показать текущий статус всех активных загрузок и управлять ими.\n"
"**/stop_torrent** - Выбрать и остановить загрузку торрента (устаревает, используйте /status).\n" "**/stop_torrent** - Выбрать и остановить загрузку торрента (устаревает, используйте /status).\n"
"**/help** - Показать это справочное сообщение.\n\n" "**/help** - Показать это справочное сообщение.\n\n"
"Также вы можете отправить мне *magnet-ссылку* или *URL torrent-файла* " "Также вы можете отправить мне `magnet-ссылку` или `URL torrent-файла` " # ИСПРАВЛЕНО: Использованы обратные апострофы
"для добавления загрузки. Бот предложит выбрать категорию и директорию." "для добавления загрузки. Бот предложит выбрать категорию и директорию."
) )
await update.message.reply_text(help_text, parse_mode="Markdown") await update.message.reply_text(help_text, parse_mode="Markdown")
# --- Команда /status (ОБНОВЛЕНО с учетом точных статусов) --- # --- Команда /status ---
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
if update.message is None: if update.message is None:
logger.warning("Received an update without a message object in status handler.") logger.warning("Received an update without a message object in status handler.")
@ -120,8 +120,6 @@ async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
return return
for torrent in torrents: 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 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 upload_speed = torrent.upspeed / (1024 * 1024) if torrent.upspeed >= (1024 * 1024) else torrent.upspeed / 1024
@ -129,7 +127,7 @@ async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
up_unit = "MB/s" if torrent.upspeed >= (1024 * 1024) else "KB/s" up_unit = "MB/s" if torrent.upspeed >= (1024 * 1024) else "KB/s"
eta_str = "" eta_str = ""
if torrent.eta == 8640000: # qBittorrent returns 8640000 for "infinite" ETA if torrent.eta == 8640000:
eta_str = "" eta_str = ""
elif torrent.eta > 0: elif torrent.eta > 0:
hours, remainder = divmod(torrent.eta, 3600) hours, remainder = divmod(torrent.eta, 3600)
@ -159,7 +157,7 @@ async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
'queuedDL', 'checkingUP', 'queuedUP' 'queuedDL', 'checkingUP', 'queuedUP'
] ]
paused_states = [ paused_states = [
'pausedDL', 'pausedUP', 'stoppedUP', 'stoppedDL' # Корректные статусы из логов 'pausedDL', 'pausedUP', 'stoppedUP', 'stoppedDL'
] ]
if torrent.state in active_states: if torrent.state in active_states:
@ -167,9 +165,8 @@ async def status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
elif torrent.state in paused_states: elif torrent.state in paused_states:
keyboard.append(InlineKeyboardButton("▶️ Запустить", callback_data=f"start_hash_{torrent.hash}")) keyboard.append(InlineKeyboardButton("▶️ Запустить", callback_data=f"start_hash_{torrent.hash}"))
elif torrent.state == 'metaDL': elif torrent.state == 'metaDL':
pass # Не предлагаем кнопок, пока не начнется фактическая загрузка pass
else: else:
# Если торрент не в активных и не в явных "пауза/остановлено"
keyboard.append(InlineKeyboardButton(" Неизвестное состояние", callback_data=f"info_hash_{torrent.hash}")) keyboard.append(InlineKeyboardButton(" Неизвестное состояние", callback_data=f"info_hash_{torrent.hash}"))
@ -245,7 +242,7 @@ async def start_torrent_callback(update: Update, context: ContextTypes.DEFAULT_T
await query.edit_message_text(f"Торрент ({torrent_hash[:6]}...) успешно запущен (возобновлен).") await query.edit_message_text(f"Торрент ({torrent_hash[:6]}...) успешно запущен (возобновлен).")
except APIError as e: except APIError as e:
logger.error(f"Error resuming torrent {torrent_hash}: {e}") logger.error(f"Error resuming torrent {torrent_hash}: {e}")
await query.edit_message_text(f"Ошибка при запуске торрента: {e}") await query.edit_message_text(f"Ошибка при запуске торrenta: {e}")
except Exception as e: except Exception as e:
logger.error(f"An unexpected error occurred during torrent resuming: {e}") logger.error(f"An unexpected error occurred during torrent resuming: {e}")
await query.edit_message_text(f"Произошла непредвиденная ошибка: {e}") await query.edit_message_text(f"Произошла непредвиденная ошибка: {e}")
@ -318,12 +315,10 @@ async def send_directory_options(query, context):
"/share/Data/torrents", "/share/Data/torrents",
] ]
# Убедимся, что пути уникальны и отсортированы
available_paths = sorted(list(set([p.replace(os.sep, '/') for p in available_paths if p]))) available_paths = sorted(list(set([p.replace(os.sep, '/') for p in available_paths if p])))
directory_keyboard = [] directory_keyboard = []
for path in available_paths: for path in available_paths:
# Отображаем только имя папки, если путь слишком длинный
display_path = os.path.basename(path) if len(path) > 30 else path display_path = os.path.basename(path) if len(path) > 30 else path
directory_keyboard.append([InlineKeyboardButton(display_path, callback_data=f"select_dir_{path}")]) directory_keyboard.append([InlineKeyboardButton(display_path, callback_data=f"select_dir_{path}")])
@ -372,7 +367,6 @@ async def select_directory_callback(update: Update, context: ContextTypes.DEFAUL
f"Категория: {category or 'Без категории'}\n" f"Категория: {category or 'Без категории'}\n"
f"Директория: {selected_directory}" f"Директория: {selected_directory}"
) )
# Очищаем данные пользователя после успешного добавления
if 'current_torrent_url' in context.user_data: if 'current_torrent_url' in context.user_data:
del context.user_data['current_torrent_url'] del context.user_data['current_torrent_url']
if 'selected_category' in context.user_data: if 'selected_category' in context.user_data: