videoDownloadTGbot/bot.py
vrubelroman 28ec2ff9b6
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 32s
fix(bot): убрать ник и текст автора из подписи к видео
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:56:39 +00:00

1174 lines
57 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import re
import json
import html
import logging
import asyncio
import time
import uuid
from pathlib import Path
from urllib.parse import urlparse, unquote
from dataclasses import dataclass
import httpx
from telegram import Update, Message, Bot
from telegram.error import BadRequest
from telegram.ext import Application, MessageHandler, filters, ContextTypes, CommandHandler, Defaults
from telegram.request import HTTPXRequest
import db
# Таймаут для HTTP-запросов к downloader-сервисам. read=330 с — больше, чем бюджет
# сервиса (yt-dlp ~150 с × 2 попытки); при таймауте бот НЕ ретраит.
HTTP_TIMEOUT = httpx.Timeout(connect=10, read=330, write=30, pool=30)
# Лёгкие запросы (/cookies/check)
CHECK_TIMEOUT = httpx.Timeout(connect=15, read=45, write=15, pool=15)
SERVICE_RETRIES = 2 # попытки при сетевой ошибке / 5xx
SERVICE_RETRY_PAUSE = 2 # секунд между попытками
STILL_WAITING_AFTER = 90 # через сколько секунд дописать «ещё жду»
QUEUE_LIMIT_PER_USER = 3 # активных элементов очереди на одного пользователя
GROUP_ERROR_TTL = 60 # секунд, через сколько удалять сообщение об ошибке в группе
FILE_MAX_AGE = 3600 # секунд; старше — удаляется из video/
CLEANUP_INTERVAL = 30 * 60
MAX_VIDEO_SIZE = 50 * 1024 * 1024 # лимит Telegram Bot API
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# httpx на INFO пишет URL getUpdates с токеном бота — глушим
logging.getLogger('httpx').setLevel(logging.WARNING)
logging.getLogger('httpcore').setLevel(logging.WARNING)
logging.getLogger('apscheduler').setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
TELEGRAM_BOT_USERNAME = os.getenv('TELEGRAM_BOT_USERNAME', 'vrubelVideoDownload_bot')
ADMIN_BOT_TOKEN = os.getenv('ADMIN_BOT_TOKEN')
SUPPORT_CONTACT = os.getenv('SUPPORT_CONTACT', '@rvrubel')
SERVICES = {
'youtube': {'url': os.getenv('YOUTUBE_DOWNLOADER_URL', 'http://localhost:5557'), 'name': 'YouTube'},
'instagram': {'url': os.getenv('INSTAGRAM_DOWNLOADER_URL', 'http://localhost:5556'), 'name': 'Instagram'},
'vk': {'url': os.getenv('VK_DOWNLOADER_URL', 'http://localhost:5555'), 'name': 'VK'},
'yapfiles': {'url': os.getenv('YAPFILES_DOWNLOADER_URL', 'http://localhost:5558'), 'name': 'Yapfiles'},
'tiktok': {'url': os.getenv('TIKTOK_DOWNLOADER_URL', 'http://localhost:5559'), 'name': 'TikTok'},
}
# Домены источников; проверка суффиксом (host == d или host.endswith('.' + d))
SOURCE_DOMAINS = {
'youtube': ['youtube.com', 'youtu.be', 'm.youtube.com', 'music.youtube.com', 'youtube-nocookie.com'],
'instagram': ['instagram.com'],
'vk': ['vk.com', 'm.vk.com', 'vk.ru', 'vkontakte.ru', 'vkvideo.ru'],
'yapfiles': ['yapfiles.ru'],
'tiktok': ['tiktok.com', 'vm.tiktok.com', 'vt.tiktok.com'],
}
# Instagram отказывает в показе такого контента анонимным/несовместимым аккаунтам
INSTAGRAM_SENSITIVE_CONTENT_MARKERS = ("can't be seen by certain audiences", "isn't available to everyone")
BASE_DIR = Path(__file__).resolve().parent
DOWNLOADS_DIR = BASE_DIR / 'video'
DOWNLOADS_DIR.mkdir(parents=True, exist_ok=True)
DATA_DIR = BASE_DIR / 'data'
DATA_DIR.mkdir(parents=True, exist_ok=True)
# ============================================================================
# ЛОКАЛИЗАЦИЯ (все тексты — HTML; подстановки экранируются вызывающим кодом)
# ============================================================================
TEXTS = {
'ru': {
'start': (
"👋 Привет! Пришлите ссылку на видео — верну его файлом прямо сюда.\n\n"
"<b>Поддерживаю:</b> YouTube (и Shorts), Instagram (Reels, посты), TikTok, VK Видео и Клипы, Yapfiles.\n\n"
"<b>Ограничения:</b> до 50 МБ (лимит Telegram), YouTube — до 720p "
"(длинные ролики — в качестве пониже, чтобы уложиться в 50 МБ).\n\n"
"<b>В группах:</b> добавьте меня администратором с правом удалять сообщения — "
"я буду заменять ссылки участников готовым видео."
),
'send_link': "Пришлите ссылку на видео с YouTube, Instagram, TikTok, VK или Yapfiles.",
'unsupported_source': "🤷 Эту ссылку я не умею скачивать.\nУмею: YouTube, Instagram, TikTok, VK, Yapfiles.",
'multiple_links': "🔗 В сообщении несколько ссылок — скачаю первую подходящую. Остальные пришлите отдельными сообщениями.",
'downloading': "⬇️ Скачиваю видео…\nОбычно это 10–60 секунд.",
'still_waiting': "⬇️ Скачиваю видео…\n⏳ Дольше обычного — видео большое или источник медленный. Жду до 5 минут.",
'sending': "📤 Отправляю в Telegram…",
'caption': "🎬 {title}\n🔗 {url}\n@{bot_username}",
'video_fallback': "Видео",
'queue_position': "⏳ Вы {position}-й в очереди, впереди {ahead} видео.\nНачну скачивать автоматически.",
'queue_limit': "⏸ У вас уже {limit} видео в очереди. Пришлите ссылку, когда они скачаются.",
'error': "❌ Не получилось скачать это видео. Попробуйте ещё раз через пару минут.",
'error_service_down': "😔 Сервис {source} сейчас не отвечает. Попробуйте через 5–10 минут.",
'error_private': "🔒 Видео приватное, удалено или недоступно в вашем регионе — скачать его не получится.",
'error_no_video': "🤷 По этой ссылке нет видео, которое я могу скачать. Пришлите ссылку на конкретный ролик.",
'error_login_required': "🛠 {source} временно требует входа в аккаунт. Мы уже в курсе и чиним — попробуйте через пару часов.",
'error_sensitive_content': "🔞 Instagram ограничил этот контент (возраст / чувствительная тема) — скачать его я не могу. Откройте ссылку в приложении Instagram.",
'error_file_too_large': "📦 Видео весит {size_mb:.1f} МБ, а Telegram позволяет боту отправлять только до 50 МБ. Попробуйте более короткий ролик.",
'error_file_too_large_unknown': "📦 Видео больше 50 МБ — это предел Telegram для ботов. Попробуйте более короткий ролик.",
'error_timeout': "⏱ Источник отвечал слишком долго, скачивание прервано. Попробуйте позже или другой ролик.",
'error_vk_not_video': "🔗 Это ссылка VK, но не на видео. Пришлите ссылку вида vk.com/video… или vk.com/clip…",
},
'en': {
'start': (
"👋 Hi! Send me a video link and I'll return the file right here.\n\n"
"<b>Supported:</b> YouTube (incl. Shorts), Instagram (Reels, posts), TikTok, VK Video &amp; Clips, Yapfiles.\n\n"
"<b>Limits:</b> up to 50 MB (Telegram limit), YouTube — up to 720p "
"(long videos come in lower quality to fit 50 MB).\n\n"
"<b>In groups:</b> add me as an admin with \"delete messages\" permission — "
"I'll replace members' links with the video."
),
'send_link': "Send me a video link from YouTube, Instagram, TikTok, VK or Yapfiles.",
'unsupported_source': "🤷 I can't download from this site.\nSupported: YouTube, Instagram, TikTok, VK, Yapfiles.",
'multiple_links': "🔗 Several links in one message — I'll download the first supported one. Send the others separately.",
'downloading': "⬇️ Downloading…\nUsually takes 10–60 seconds.",
'still_waiting': "⬇️ Downloading…\n⏳ Taking longer than usual — large video or slow source. I'll wait up to 5 minutes.",
'sending': "📤 Sending to Telegram…",
'caption': "🎬 {title}\n🔗 {url}\n@{bot_username}",
'video_fallback': "Video",
'queue_position': "⏳ You're #{position} in line, {ahead} video(s) ahead.\nI'll start automatically.",
'queue_limit': "⏸ You already have {limit} videos in the queue. Send the link again once they're done.",
'error': "❌ Couldn't download this video. Try again in a couple of minutes.",
'error_service_down': "😔 The {source} service isn't responding right now. Try again in 5–10 minutes.",
'error_private': "🔒 This video is private, removed or blocked in this region — it can't be downloaded.",
'error_no_video': "🤷 There's no video I can download at this link. Send a link to a specific video.",
'error_login_required': "🛠 {source} temporarily requires a login. We're on it — try again in a couple of hours.",
'error_sensitive_content': "🔞 This content is restricted by Instagram (age/sensitive content) and can't be downloaded by the bot. Try opening the link directly in the Instagram app.",
'error_file_too_large': "📦 This video is {size_mb:.1f} MB, but Telegram lets bots send up to 50 MB only. Try a shorter clip.",
'error_file_too_large_unknown': "📦 This video is over 50 MB — Telegram's limit for bots. Try a shorter clip.",
'error_timeout': "⏱ The source took too long to respond and the download was aborted. Try later or another clip.",
'error_vk_not_video': "🔗 This is a VK link, but not a video. Send a vk.com/video… or vk.com/clip… link.",
},
}
assert set(TEXTS['ru']) == set(TEXTS['en']), (
f"Наборы ключей TEXTS различаются: {set(TEXTS['ru']) ^ set(TEXTS['en'])}"
)
RU_LOCALES = {'ru', 'uk', 'be', 'kk'}
BOT_SHORT_DESCRIPTION = {
'ru': "Скачивает видео из YouTube, Instagram, TikTok, VK, Yapfiles",
'en': "Downloads videos from YouTube, Instagram, TikTok, VK, Yapfiles",
}
BOT_DESCRIPTION = {
'ru': "Пришлите ссылку — получите видео файлом. До 50 МБ. Работает и в группах.",
'en': "Send a link — get the video as a file. Up to 50 MB. Works in groups too.",
}
def get_locale_from_language_code(language_code: str | None) -> str:
"""ru/uk/be/kk → ru, остальное → en."""
if not language_code:
return 'en'
code = language_code.lower().replace('_', '-')
primary = code.split('-', 1)[0]
if primary in RU_LOCALES or primary.startswith('ru'):
return 'ru'
return 'en'
def get_text(locale: str, key: str, **kwargs) -> str:
"""Локализованный текст. Подстановки с пользовательскими данными экранировать до вызова."""
if locale not in TEXTS:
locale = 'en'
text = TEXTS[locale].get(key, TEXTS['en'].get(key, key))
if kwargs:
text = text.format(**kwargs)
return text
# ============================================================================
# УТИЛИТЫ
# ============================================================================
def _host_of(url: str) -> str:
if '://' not in url:
url = 'https://' + url
host = urlparse(url).hostname or ''
return host.lower().rstrip('.')
def _host_matches(host: str, domains: list[str]) -> bool:
return any(host == d or host.endswith('.' + d) for d in domains)
def detect_video_source(url: str) -> str:
"""Определяет источник по хосту URL (суффиксная проверка домена)."""
host = _host_of(url)
if not host:
return 'unknown'
for source, domains in SOURCE_DOMAINS.items():
if _host_matches(host, domains):
return source
return 'unknown'
_VK_VIDEO_PATH = re.compile(r'^(?:video|clip)-?\d+_\d+(?:/|$|\?)')
_VK_VIDEO_QUERY = re.compile(r'(?:^|&)z=(?:video|clip)-?\d+_\d+')
_VK_EMBED_OID = re.compile(r'(?:^|&)oid=-?\d+(?:&|$)')
_VK_EMBED_ID = re.compile(r'(?:^|&)id=\d+(?:&|$)')
def is_vk_video_url(url: str) -> bool:
"""VK-ссылка ведёт именно на видео/клип (а не на профиль, группу или альбом videos-123)."""
if not _host_matches(_host_of(url), SOURCE_DOMAINS['vk']):
return False
parsed = urlparse(url if '://' in url else 'https://' + url)
path = parsed.path.lower().strip('/')
query = unquote(parsed.query.lower())
if path == 'video_ext.php': # embed-плеер: vk.com/video_ext.php?oid=-1&id=2&hash=…
return bool(_VK_EMBED_OID.search(query) and _VK_EMBED_ID.search(query))
return bool(_VK_VIDEO_PATH.match(path) or _VK_VIDEO_QUERY.search(query))
_URL_PATTERN = re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+')
_TRAILING_PUNCT = '.,;:!?)]>»"\''
def extract_urls_from_text(text: str) -> list[str]:
"""Все http(s)-URL из текста без хвостовой пунктуации."""
urls = []
for raw in _URL_PATTERN.findall(text):
url = raw.rstrip(_TRAILING_PUNCT)
if url:
urls.append(url)
return urls
def strip_urls(text: str) -> str:
"""Текст сообщения без URL, схлопнутые пробелы."""
return re.sub(r'\s+', ' ', _URL_PATTERN.sub('', text)).strip()
def cleanup_old_files() -> None:
"""Удаляет из video/ все файлы старше часа (зависшие после сбоев)."""
try:
threshold = time.time() - FILE_MAX_AGE
for file_path in DOWNLOADS_DIR.iterdir():
try:
if file_path.is_file() and file_path.stat().st_mtime < threshold:
file_path.unlink()
logger.info("Удалён старый файл: %s", file_path.name)
except Exception as e:
logger.warning("Не удалось удалить %s: %s", file_path.name, e)
except Exception:
logger.error("Ошибка при очистке video/", exc_info=True)
def get_admin_chat_id() -> int | None:
try:
admin_chat_id_file = DATA_DIR / 'admin_chat_id.txt'
if admin_chat_id_file.exists():
value = admin_chat_id_file.read_text().strip()
if value:
return int(value)
except Exception as e:
logger.error("Ошибка при чтении chat_id админа: %s", e)
return None
def user_label(from_user) -> str:
"""'@user · id 123' / 'Имя · id 123', экранировано для HTML."""
if not from_user:
return 'неизвестно'
name = f"@{from_user.username}" if from_user.username else (from_user.first_name or 'без имени')
return f"{html.escape(name)} · id {from_user.id}"
# ============================================================================
# КЛАССИФИКАЦИЯ ОШИБОК
# ============================================================================
# Классы из контракта сервисов + внутренние (service_down — бот не достучался)
ERROR_CODES = {'bad_request', 'unsupported_url', 'private_or_removed', 'login_required',
'sensitive_content', 'too_large', 'timeout', 'download_failed', 'service_down'}
# Ретраим только недостижимость сервиса (сеть, 502/503 без кода). download_failed не ретраим:
# сервис уже сделал свои попытки в бюджете ~300 с, повтор удвоил бы время одного элемента очереди.
RETRYABLE_CODES = {'service_down'}
# Не поломка бота — админу не слать, только считать в events
SILENT_ADMIN_CODES = {'too_large', 'private_or_removed', 'sensitive_content', 'unsupported_url', 'bad_request'}
ERROR_TEXT_KEYS = {
'service_down': 'error_service_down',
'private_or_removed': 'error_private',
'login_required': 'error_login_required',
'sensitive_content': 'error_sensitive_content',
'too_large': 'error_file_too_large',
'timeout': 'error_timeout',
'unsupported_url': 'error_no_video',
'bad_request': 'error_no_video',
}
ERROR_HINTS = {
'login_required': 'протухшие cookies → cookies/README.md',
'service_down': 'сервис не отвечает — контейнер упал или перегружен',
'timeout': 'источник медленный или yt-dlp завис',
'download_failed': 'ошибка yt-dlp (версия экстрактора / блокировка IP / формат)',
}
class DownloadError(Exception):
def __init__(self, code: str, message: str, http_status: int | None = None, size_mb: float | None = None):
super().__init__(message)
self.code = code if code in ERROR_CODES else 'download_failed'
self.message = message
self.http_status = http_status
self.size_mb = size_mb
# Копия ERROR_CLASSES из downloader_common/app_factory.py (другой образ — импорт невозможен).
# Держать синхронно; сквозной тест tests/test_services.py::test_end_to_end_user_visible_code.
# Порядок важен: специфичные фразы раньше общих; голые 'unavailable' / 'not available' /
# 'cookies' не маркеры (есть в «503 Service Unavailable» и в подсказке yt-dlp «--cookies»).
ERROR_CLASSES = (
('unsupported_url', ('unsupported url', 'urls are supported')),
('too_large', ('larger than max-filesize', 'file is larger')),
('sensitive_content', INSTAGRAM_SENSITIVE_CONTENT_MARKERS),
('private_or_removed', ('private video', 'video unavailable', 'this video is unavailable',
'has been removed', 'has been deleted', 'no longer available',
'does not exist', 'author has been blocked',
'video not available', 'temporarily unavailable', # TikTok 10204, VK
'you do not have permission to view',
# тексты наших сервисов по-русски
'видео недоступно', 'видео удалено')),
('login_required', ('sign in to confirm', 'login required', 'redirected to the login page',
'rate-limit', 'not a bot', 'no longer valid',
'http error 401', 'unauthorized')),
('timeout', ('timed out', 'timeout')),
)
def _normalize_error_text(text: str | None) -> str:
"""Нижний регистр + типографские апострофы → прямой (Instagram/YouTube шлют ’)."""
return (text or '').lower().replace('\u2019', "'").replace('\u2018', "'").replace('\u02bc', "'")
def classify_error_text(text: str | None) -> str:
"""Классификация по тексту: старые сервисы без поля code и уточнение generic download_failed."""
lower = _normalize_error_text(text)
for code, markers in ERROR_CLASSES:
if any(m in lower for m in markers):
return code
return 'download_failed'
def _error_from_response(source: str, status: int, body: bytes) -> DownloadError:
text = body.decode('utf-8', 'replace')
code = None
try:
data = json.loads(text)
if isinstance(data, dict):
text = str(data.get('error') or text)
code = data.get('code')
except ValueError:
pass
# code сервиса первичен; generic download_failed уточняем по маркерам текста
if code not in ERROR_CODES or code == 'download_failed':
if status == 413:
code = 'too_large'
elif status == 504:
code = 'timeout'
elif status in (502, 503):
code = 'service_down'
else:
code = classify_error_text(text)
size_mb = None
if code == 'too_large':
m = re.search(r'(\d{6,})\s*bytes', text)
if m:
size_mb = int(m.group(1)) / (1024 * 1024)
else:
m = re.search(r'(\d+(?:\.\d+)?)\s*МБ больше', text)
if m:
size_mb = float(m.group(1))
name = SERVICES[source]['name']
return DownloadError(code, f"{name} сервис вернул {status}: {text[:1000]}", status, size_mb)
def user_error_text(locale: str, source: str, error: DownloadError) -> str:
key = ERROR_TEXT_KEYS.get(error.code, 'error')
source_name = SERVICES.get(source, {}).get('name', source)
if key == 'error_file_too_large' and error.size_mb is None:
key = 'error_file_too_large_unknown'
return get_text(locale, key, source=source_name, size_mb=error.size_mb or 0)
# ============================================================================
# АДМИН-УВЕДОМЛЕНИЯ (один общий Bot, создаётся в post_init)
# ============================================================================
ADMIN_BOT: Bot | None = None
ADMIN_ALERT_WINDOW = 10 * 60
_admin_alert_state: dict[tuple[str, str], dict] = {} # (service, code) -> {'ts', 'suppressed'}
async def _admin_send(text: str, **kwargs) -> None:
if not ADMIN_BOT:
return
admin_chat_id = get_admin_chat_id()
if not admin_chat_id:
logger.debug("Админ chat_id не найден, уведомление пропущено")
return
# Подстановки режутся до экранирования вызывающим кодом; готовый HTML не режем
# (срез посреди <pre> ломает разбор). Если всё же не принят — простым текстом.
try:
await ADMIN_BOT.send_message(chat_id=admin_chat_id, text=text, parse_mode='HTML',
disable_web_page_preview=True, **kwargs)
except BadRequest as e:
logger.warning("Админ-уведомление не принято (%s), шлю простым текстом", e)
try:
await ADMIN_BOT.send_message(chat_id=admin_chat_id, text=html_to_plain(text)[:4000],
parse_mode=None, disable_web_page_preview=True, **kwargs)
except Exception as e2:
logger.error("Ошибка при отправке уведомления админ боту: %s", e2)
except Exception as e:
logger.error("Ошибка при отправке уведомления админ боту: %s", e)
async def send_video_to_admin_bot(video_path: str, url: str, from_user=None) -> None:
"""Копия скачанного видео админу."""
if not ADMIN_BOT:
return
admin_chat_id = get_admin_chat_id()
if not admin_chat_id:
return
short_url = url[:300]
caption = (
f"📥 Видео скачано\n👤 {user_label(from_user)}\n"
f"🔗 <a href=\"{html.escape(url, quote=True)}\">{html.escape(short_url)}</a>"
)
try:
for attempt in range(3):
with open(video_path, 'rb') as video_file:
try:
await ADMIN_BOT.send_video(
chat_id=admin_chat_id, video=video_file, caption=caption,
parse_mode='HTML', supports_streaming=True,
read_timeout=600, write_timeout=600, connect_timeout=60, pool_timeout=60,
)
break
except Exception as send_error:
if attempt == 2:
raise
logger.warning("Отправка видео админу: попытка %s не удалась: %s", attempt + 1, send_error)
await asyncio.sleep((attempt + 1) * 2)
logger.info("Видео отправлено админ боту: %s", video_path)
except Exception as e:
logger.error("Ошибка при отправке видео админ боту: %s", e)
async def notify_admin_error(source: str, url: str, error: DownloadError, from_user=None, chat=None) -> None:
"""Алерт админу об ошибке; не-поломки не шлём, одинаковые (сервис, класс) агрегируем в окне 10 мин."""
if error.code in SILENT_ADMIN_CODES:
return
key = (source, error.code)
now = time.time()
state = _admin_alert_state.get(key)
if state and now - state['ts'] < ADMIN_ALERT_WINDOW:
state['suppressed'] += 1
logger.info("Алерт (%s, %s) подавлен, в окне уже %s", source, error.code, state['suppressed'])
return
suppressed = state['suppressed'] if state else 0
_admin_alert_state[key] = {'ts': now, 'suppressed': 0}
name = SERVICES.get(source, {}).get('name', source)
header = f"🟥 <b>{html.escape(name)} — ошибка скачивания</b>"
if suppressed:
header += f" (подавлено похожих: {suppressed})"
hint = ERROR_HINTS.get(error.code)
text = (
f"{header}\n"
f"👤 {user_label(from_user)}\n"
+ (f"👥 в группе «{html.escape((chat.title or str(chat.id))[:100])}»\n"
if chat is not None and is_group(chat.type) else "")
+ f"🔗 {html.escape(url[:300])}\n"
f"<pre>{html.escape(error.message[:600])}</pre>\n"
f"Класс: <code>{error.code}</code>"
)
if hint:
text += f"\nПохоже на: {html.escape(hint)}"
await _admin_send(text)
logger.info("Алерт об ошибке отправлен админу: %s %s", source, error.code)
# ============================================================================
# COOKIE HEALTH-CHECK
# ============================================================================
COOKIE_STATUS_FILE = DATA_DIR / 'cookie_health_state.json'
COOKIE_CHECK_INTERVAL = 30 * 60
COOKIE_REMINDER_INTERVAL = 24 * 3600
COOKIE_FAIL_STREAK = 2 # сломано только после N подряд неудачных проверок (гистерезис)
def _load_cookie_state() -> dict:
try:
return json.loads(COOKIE_STATUS_FILE.read_text())
except Exception:
return {}
def _save_cookie_state(state: dict) -> None:
try:
COOKIE_STATUS_FILE.write_text(json.dumps(state))
except Exception as e:
logger.error("Не удалось сохранить состояние cookie-health: %s", e)
def _format_duration(seconds: float) -> str:
total_hours = int(seconds // 3600)
days, hours = divmod(total_hours, 24)
if days:
return f"{days} дн. {hours} ч."
return f"{hours} ч." if hours else "меньше часа."
async def notify_admin_cookie_alert(service: str, status: str, detail: str, test_url: str = '',
broken_since: float | None = None) -> None:
"""status: 'ok' | 'cookies_invalid' | 'cookies_incomplete' | 'extraction_failed'."""
name = SERVICES.get(service, {}).get('name', service)
url_line = f"🔗 Проверялось на: {html.escape(test_url)}\n" if test_url else ""
detail_block = f"<pre>{html.escape(detail[:600])}</pre>\n" if detail else ""
duration_line = ""
if broken_since:
failed = await asyncio.to_thread(db.count_failed_downloads_since, service, broken_since)
duration_line = (
f"Сломано уже {_format_duration(time.time() - broken_since)} "
f"Неудачных скачиваний за это время: {failed}.\n"
)
if status == 'ok':
text = f"✅ <b>{name} снова работает</b>\n{url_line}Проверка проходит успешно."
elif status == 'cookies_invalid':
text = (
f"🍪 <b>{name}: cookies протухли</b>\n{url_line}{duration_line}{detail_block}"
"Обновить по инструкции в cookies/README.md (для YouTube — только через приватное окно)."
)
elif status == 'cookies_incomplete':
text = (
f"🍪 <b>{name}: cookies неполные</b>\n{url_line}{duration_line}{detail_block}"
"Файл cookies есть, но реальной сессии в нём нет (похоже на неправильный экспорт). "
"Переэкспортировать по инструкции в cookies/README.md."
)
else:
text = (
f"🛠 <b>{name}: сервис не может извлечь видео</b>\n{url_line}{duration_line}{detail_block}"
"Причина неясна — версия yt-dlp, JS-рантайм или cookies. Смотреть логи сервиса."
)
await _admin_send(text)
logger.info("Уведомление health-check (%s, %s) отправлено админу", service, status)
async def check_cookies_health() -> None:
"""Периодическая проверка cookies YouTube и Instagram с гистерезисом."""
state = _load_cookie_state()
streaks = state.setdefault('fail_streak', {})
reminders = state.setdefault('last_reminder_ts', {})
broken_since = state.setdefault('broken_since', {})
for service in ('youtube', 'instagram'):
endpoint = f"{SERVICES[service]['url']}/cookies/check"
try:
async with httpx.AsyncClient(timeout=CHECK_TIMEOUT) as client:
response = await client.post(endpoint)
data = response.json()
except Exception as e:
logger.warning("Проверка cookies %s не удалась (сервис недоступен?): %s", service, e)
continue # сетевая ошибка состояние не меняет
status = data.get('status')
if status is None: # старый формат ответа
valid = data.get('cookies_valid')
status = 'no_cookies' if valid is None else ('ok' if valid else 'cookies_invalid')
if status == 'no_cookies':
continue
detail = data.get('detail', '')
test_url = data.get('test_url', '')
was_healthy = state.get(service, 'healthy') == 'healthy'
now = time.time()
if status == 'ok':
streaks[service] = 0
if not was_healthy:
state[service] = 'healthy'
broken_since.pop(service, None)
await notify_admin_cookie_alert(service, 'ok', '', test_url)
continue
streaks[service] = streaks.get(service, 0) + 1
if was_healthy:
if streaks[service] >= COOKIE_FAIL_STREAK:
state[service] = 'broken'
broken_since[service] = now
reminders[service] = now
await notify_admin_cookie_alert(service, status, detail, test_url)
else:
logger.warning("Cookie-check %s: %s (%s/%s подряд, ждём подтверждения)",
service, status, streaks[service], COOKIE_FAIL_STREAK)
elif now - reminders.get(service, 0) >= COOKIE_REMINDER_INTERVAL:
reminders[service] = now
await notify_admin_cookie_alert(service, status, detail, test_url,
broken_since=broken_since.get(service))
_save_cookie_state(state)
# ============================================================================
# СКАЧИВАНИЕ ЧЕРЕЗ СЕРВИС
# ============================================================================
_EXT_BY_CONTENT_TYPE = {
'video/mp4': 'mp4', 'video/quicktime': 'mov', 'video/webm': 'webm',
'video/x-matroska': 'mkv', 'video/x-msvideo': 'avi', 'video/3gpp': '3gp',
}
def _decode_rfc5987(value: str) -> str:
value = value.strip().strip('"\'')
m = re.match(r"^(?:utf-8|iso-8859-1)'[^']*'(.*)$", value, re.IGNORECASE)
if m:
return unquote(m.group(1))
if '%' in value:
return unquote(value)
return value
def _parse_content_disposition(header: str) -> str | None:
"""Имя файла из Content-Disposition (filename*= приоритетнее filename=)."""
if not header:
return None
m = re.search(r"filename\*\s*=\s*([^;]+)", header, re.IGNORECASE)
if m:
return _decode_rfc5987(m.group(1))
m = re.search(r'filename\s*=\s*"((?:[^"\\]|\\.)*)"', header)
if m:
return m.group(1).replace('\\"', '"')
m = re.search(r"filename\s*=\s*([^;]+)", header, re.IGNORECASE)
if m:
return m.group(1).strip().strip('"\'')
return None
def _pick_extension(content_type: str, filename: str | None) -> str:
ct = (content_type or '').split(';')[0].strip().lower()
if ct in _EXT_BY_CONTENT_TYPE:
return _EXT_BY_CONTENT_TYPE[ct]
if filename:
suffix = Path(filename).suffix.lstrip('.').lower()
if re.fullmatch(r'[a-z0-9]{1,5}', suffix):
return suffix
if ct.startswith('video/'):
sub = re.sub(r'[^a-z0-9]', '', ct.split('/', 1)[1])
if 1 <= len(sub) <= 5:
return sub
return 'mp4'
def _title_from_headers(headers) -> str | None:
raw_title = headers.get('X-Video-Title')
if raw_title:
title = _decode_rfc5987(raw_title).strip()
if title:
return title
filename = _parse_content_disposition(headers.get('Content-Disposition', ''))
if filename:
stem = Path(filename).stem.strip()
if stem:
return stem
return None
async def fetch_from_service(source: str, url: str, chat_id: int) -> tuple[str, str | None]:
"""POST /download/stream к сервису-загрузчику; файл пишется чанками на диск.
Возвращает (путь, название). Ретрай (2 попытки, пауза 2 с) только когда сервис
недостижим (сеть, connect-таймаут, 502/503); ответы с кодом и read-таймауты не ретраятся.
"""
service = SERVICES[source]
endpoint = f"{service['url']}/download/stream"
last_error: DownloadError | None = None
for attempt in range(1, SERVICE_RETRIES + 1):
logger.info("%s: запрос к %s (попытка %s/%s)", service['name'], endpoint, attempt, SERVICE_RETRIES)
video_path: Path | None = None
done = False
try:
async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
async with client.stream('POST', endpoint, json={'url': url}) as response:
if response.status_code != 200:
body = await response.aread()
raise _error_from_response(source, response.status_code, body)
filename = _parse_content_disposition(response.headers.get('Content-Disposition', ''))
ext = _pick_extension(response.headers.get('Content-Type', ''), filename)
title = _title_from_headers(response.headers)
video_path = DOWNLOADS_DIR / f'{chat_id}_{uuid.uuid4().hex}.{ext}'
size = 0
with open(video_path, 'wb') as f:
async for chunk in response.aiter_bytes(256 * 1024):
f.write(chunk)
size += len(chunk)
logger.info("%s: файл получен %s (%.1f МБ)", service['name'], video_path.name, size / 1048576)
done = True
return str(video_path), title
except DownloadError as e:
last_error = e
if e.code not in RETRYABLE_CODES:
raise
logger.warning("%s: попытка %s: %s", service['name'], attempt, e.message[:300])
except (httpx.ConnectTimeout, httpx.PoolTimeout) as e:
last_error = DownloadError('service_down', f"{service['name']}: сервис не принимает соединение: {e.__class__.__name__}")
logger.warning("%s: попытка %s: %s", service['name'], attempt, e.__class__.__name__)
except httpx.TimeoutException as e:
raise DownloadError('timeout', f"{service['name']}: таймаут запроса к сервису ({e.__class__.__name__})") from e
except httpx.HTTPError as e:
last_error = DownloadError('service_down', f"{service['name']}: сервис недоступен: {e.__class__.__name__}: {e}")
logger.warning("%s: попытка %s: сетевая ошибка: %s", service['name'], attempt, e)
finally:
# недокачанный файл после исключения не оставляем
if video_path is not None and not done:
video_path.unlink(missing_ok=True)
if attempt < SERVICE_RETRIES:
await asyncio.sleep(SERVICE_RETRY_PAUSE)
raise last_error or DownloadError('download_failed', f"{service['name']}: неизвестная ошибка")
# ============================================================================
# ОЧЕРЕДЬ
# ============================================================================
@dataclass
class QueueItem:
original_message: Message
url: str
source: str
chat_id: int
chat_type: str
user_id: int
locale: str
status_message: Message | None = None
last_text: str | None = None
processing: bool = False
APP: Application | None = None
download_queue: asyncio.Queue | None = None
queue_items: list[QueueItem] = []
queue_lock = asyncio.Lock()
def is_group(chat_type: str) -> bool:
return chat_type in ('group', 'supergroup')
async def set_status(item: QueueItem, text: str) -> None:
"""Редактирует статус только если текст реально изменился."""
if item.status_message is None or text == item.last_text:
return
try:
await item.status_message.edit_text(text, disable_web_page_preview=True)
item.last_text = text
except BadRequest as e:
if 'not modified' in str(e).lower():
item.last_text = text
else:
logger.warning("Не удалось обновить статус: %s", e)
except Exception as e:
logger.warning("Не удалось обновить статус: %s", e)
def queue_status_text(locale: str, position: int) -> str:
if position <= 1:
return get_text(locale, 'downloading')
return get_text(locale, 'queue_position', position=position, ahead=position - 1)
async def update_queue_positions() -> None:
"""Обновляет позиции ожидающих; тот, что уже качается, не трогаем."""
async with queue_lock:
snapshot = list(queue_items)
for i, item in enumerate(snapshot):
if item.processing or item.status_message is None:
continue
await set_status(item, queue_status_text(item.locale, i + 1))
async def _still_waiting_watchdog(item: QueueItem) -> None:
await asyncio.sleep(STILL_WAITING_AFTER)
await set_status(item, get_text(item.locale, 'still_waiting'))
CAPTION_TITLE_MAX = 100
CAPTION_VISIBLE_MAX = 1000 # лимит Telegram 1024 по видимому тексту, с запасом
def _clip(text: str, limit: int) -> str:
text = text.strip()
return text if len(text) <= limit else text[:limit - 1].rstrip() + '…'
def html_to_plain(text: str) -> str:
"""Видимый текст HTML-сообщения (теги убраны, сущности раскрыты)."""
return html.unescape(re.sub(r'<[^>]+>', '', text))
def build_caption(item: QueueItem, title: str | None) -> str:
"""Подпись к видео: название, ссылка, бот. Без ника и текста автора.
Режем сырой текст ДО экранирования, готовый HTML не режем: срез разрубал
'&amp;' → «can't parse entities» → ложное «не получилось скачать»."""
locale = item.locale
raw_title = (title or '').strip() or get_text(locale, 'video_fallback')
def render(title_max: int) -> str:
return get_text(locale, 'caption', title=html.escape(_clip(raw_title, title_max)),
url=html.escape(item.url, quote=False), bot_username=TELEGRAM_BOT_USERNAME)
caption = render(CAPTION_TITLE_MAX)
if len(html_to_plain(caption)) > CAPTION_VISIBLE_MAX:
caption = render(40)
return caption
async def _delete_message_job(context: ContextTypes.DEFAULT_TYPE) -> None:
chat_id, message_id = context.job.data
try:
await context.bot.delete_message(chat_id=chat_id, message_id=message_id)
except Exception as e:
logger.debug("Не удалось удалить сообщение %s/%s: %s", chat_id, message_id, e)
async def handle_item_error(item: QueueItem, error: DownloadError) -> None:
from_user = item.original_message.from_user
await asyncio.to_thread(db.increment_error_count, item.source)
await asyncio.to_thread(db.record_event, 'download', item.source, item.user_id, item.chat_id, False, error.code)
await notify_admin_error(item.source, item.url, error, from_user, item.original_message.chat)
error_msg = user_error_text(item.locale, item.source, error)
message = None
try:
await set_status(item, error_msg)
message = item.status_message
except Exception:
pass
if message is None or item.last_text != error_msg:
try:
message = await item.original_message.reply_text(error_msg)
except Exception as e:
logger.warning("Не удалось отправить сообщение об ошибке: %s", e)
# В группе сообщение об ошибке не должно висеть вечно
if message is not None and is_group(item.chat_type) and APP and APP.job_queue:
APP.job_queue.run_once(_delete_message_job, GROUP_ERROR_TTL, data=(item.chat_id, message.message_id))
async def process_queue_item(item: QueueItem) -> None:
video_path: str | None = None
try:
await set_status(item, get_text(item.locale, 'downloading'))
watchdog = asyncio.create_task(_still_waiting_watchdog(item))
try:
video_path, title = await fetch_from_service(item.source, item.url, item.chat_id)
finally:
watchdog.cancel()
file_size = Path(video_path).stat().st_size
if file_size > MAX_VIDEO_SIZE:
size_mb = file_size / (1024 * 1024)
raise DownloadError('too_large', f"Файл слишком большой: {size_mb:.1f} MB", size_mb=size_mb)
await set_status(item, get_text(item.locale, 'sending'))
caption = build_caption(item, title)
filename = f"{(title or 'video').strip()[:80] or 'video'}{Path(video_path).suffix}"
filename = re.sub(r'[\\/:*?"<>|\r\n]+', '_', filename)
# Аплоад большого файла иногда обрывается транспортной ошибкой — ретраим, открывая файл заново
parse_mode = 'HTML'
for attempt in range(3):
with open(video_path, 'rb') as video_file:
try:
# Исходное сообщение со ссылкой удаляется после отправки — ответ на него
# превратился бы в цитату «Удалённое сообщение». Поэтому шлём не ответом,
# но в ту же тему форума; в группе автор и его текст есть в подписи.
original = item.original_message
await original.reply_video(
video=video_file, filename=filename, caption=caption, parse_mode=parse_mode,
supports_streaming=True,
quote=False,
message_thread_id=original.message_thread_id if original.is_topic_message else None,
read_timeout=600, write_timeout=600, connect_timeout=60, pool_timeout=60,
)
break
except BadRequest as send_error:
if 'parse entities' not in str(send_error).lower() or parse_mode is None:
raise
logger.warning("Подпись не распарсилась (%s), отправляю простым текстом", send_error)
caption, parse_mode = html_to_plain(caption)[:1024], None
except Exception as send_error:
if attempt == 2:
raise
logger.warning("Отправка видео: попытка %s не удалась: %s", attempt + 1, send_error)
await asyncio.sleep((attempt + 1) * 2)
await asyncio.to_thread(db.increment_downloads)
await asyncio.to_thread(db.record_event, 'download', item.source, item.user_id, item.chat_id, True, None)
logger.info("Видео отправлено: %s → chat %s", item.url, item.chat_id)
if item.status_message:
try:
await item.status_message.delete()
except Exception as e:
logger.warning("Не удалось удалить статусное сообщение: %s", e)
# Ссылка после успешной отправки не нужна ни в личке, ни в группе
try:
await item.original_message.delete()
except Exception as e:
logger.warning("Не удалось удалить исходное сообщение в чате %s: %s", item.chat_id, e)
# Копия админу — после уборки у пользователя: аплоад до 50 МБ не должен держать
# «Отправляю…» и исходное сообщение в группе
await send_video_to_admin_bot(video_path, item.url, item.original_message.from_user)
except DownloadError as e:
logger.error("Ошибка при обработке %s: [%s] %s", item.url, e.code, e.message[:500])
await handle_item_error(item, e)
except Exception as e:
logger.error("Неожиданная ошибка при обработке %s", item.url, exc_info=True)
await handle_item_error(item, DownloadError('download_failed', f"{e.__class__.__name__}: {e}"))
finally:
if video_path:
try:
Path(video_path).unlink(missing_ok=True)
except Exception as e:
logger.warning("Не удалось удалить файл %s: %s", video_path, e)
async def queue_worker() -> None:
logger.info("Воркер очереди запущен")
while True:
item = await download_queue.get()
try:
async with queue_lock:
item.processing = True
logger.info("Начинаю обработку: %s (в очереди: %s)", item.url, len(queue_items))
await process_queue_item(item)
except asyncio.CancelledError:
raise
except Exception:
logger.error("Ошибка обработки элемента очереди %s", item.url, exc_info=True)
finally:
async with queue_lock:
if item in queue_items:
queue_items.remove(item)
download_queue.task_done()
try:
await update_queue_positions()
except Exception:
logger.error("Ошибка обновления позиций очереди", exc_info=True)
logger.info("Обработка завершена. Осталось в очереди: %s", len(queue_items))
async def queue_worker_supervisor() -> None:
"""Перезапускает воркер, если он упал."""
while True:
try:
await queue_worker()
except asyncio.CancelledError:
raise
except Exception:
logger.error("Воркер очереди упал, перезапуск через 1 с", exc_info=True)
await asyncio.sleep(1)
# ============================================================================
# ОБРАБОТЧИКИ
# ============================================================================
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.message
if not message or not message.text:
return
text = message.text.strip()
chat_id = message.chat_id
chat_type = message.chat.type
from_user = message.from_user
username = from_user.username if from_user else None
first_name = from_user.first_name if from_user else None
locale = get_locale_from_language_code(from_user.language_code if from_user else None)
user_id = from_user.id if from_user else chat_id
private = chat_type == 'private'
await asyncio.to_thread(db.add_user, chat_id, username, first_name, locale)
urls = extract_urls_from_text(text)
if not urls:
if private:
await message.reply_text(get_text(locale, 'send_link'))
return
urls = list(dict.fromkeys(urls))
url = next((u for u in urls if detect_video_source(u) != 'unknown'), urls[0])
source = detect_video_source(url)
if source == 'unknown':
if private:
await message.reply_text(get_text(locale, 'unsupported_source'))
return
if source == 'vk' and not is_vk_video_url(url):
if private:
await message.reply_text(get_text(locale, 'error_vk_not_video'))
return
if len(urls) > 1 and private:
await message.reply_text(get_text(locale, 'multiple_links'))
await asyncio.to_thread(db.record_user_link, user_id, username, first_name)
item = QueueItem(original_message=message, url=url, source=source, chat_id=chat_id,
chat_type=chat_type, user_id=user_id, locale=locale)
async with queue_lock:
active = sum(1 for q in queue_items if q.user_id == user_id)
if active >= QUEUE_LIMIT_PER_USER:
position = None
else:
queue_items.append(item)
position = len(queue_items)
if position is None:
sent = await message.reply_text(get_text(locale, 'queue_limit', limit=QUEUE_LIMIT_PER_USER))
if not private and context.job_queue:
context.job_queue.run_once(_delete_message_job, GROUP_ERROR_TTL, data=(chat_id, sent.message_id))
return
status_text = queue_status_text(locale, position)
try:
item.status_message = await message.reply_text(status_text, disable_web_page_preview=True)
item.last_text = status_text
except Exception as e:
logger.warning("Не удалось отправить статус в чат %s: %s", chat_id, e)
async with queue_lock:
if item in queue_items:
queue_items.remove(item)
return
await download_queue.put(item)
logger.info("Добавлено в очередь: %s (%s), позиция %s", url, source, position)
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
message = update.message
from_user = message.from_user
locale = get_locale_from_language_code(from_user.language_code if from_user else None)
await asyncio.to_thread(db.add_user, message.chat_id,
from_user.username if from_user else None,
from_user.first_name if from_user else None, locale)
await message.reply_text(get_text(locale, 'start'), disable_web_page_preview=True)
async def on_error(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
logger.error("Необработанное исключение в хендлере (update=%s)", update, exc_info=context.error)
# ============================================================================
# ПЕРИОДИЧЕСКИЕ ЗАДАЧИ И ЗАПУСК
# ============================================================================
async def _cleanup_job(context: ContextTypes.DEFAULT_TYPE) -> None:
await asyncio.to_thread(cleanup_old_files)
async def _cookie_check_job(context: ContextTypes.DEFAULT_TYPE) -> None:
try:
await check_cookies_health()
except Exception:
logger.error("Ошибка при проверке здоровья cookies", exc_info=True)
async def register_bot_meta(bot: Bot) -> None:
"""Описания бота для ru и default (en); меню команд снимается."""
for locale, lang in (('en', None), ('ru', 'ru'), ('ru', 'uk'), ('ru', 'be'), ('ru', 'kk')):
try:
# меню команд не нужно: снимаем, если было зарегистрировано раньше
await bot.delete_my_commands(language_code=lang)
await bot.set_my_short_description(BOT_SHORT_DESCRIPTION[locale], language_code=lang)
await bot.set_my_description(BOT_DESCRIPTION[locale], language_code=lang)
logger.info("Описания зарегистрированы, меню команд снято (%s)", lang or 'default')
except Exception as e:
logger.warning("Не удалось зарегистрировать команды (%s): %s", lang or 'default', e)
async def post_init(application: Application) -> None:
global APP, download_queue, ADMIN_BOT, TELEGRAM_BOT_USERNAME
APP = application
if application.bot.username:
TELEGRAM_BOT_USERNAME = application.bot.username
download_queue = asyncio.Queue()
application.bot_data['queue_worker_task'] = asyncio.create_task(queue_worker_supervisor())
if ADMIN_BOT_TOKEN:
ADMIN_BOT = Bot(token=ADMIN_BOT_TOKEN, request=HTTPXRequest(
connection_pool_size=4, read_timeout=600, write_timeout=600, connect_timeout=60, pool_timeout=60,
))
await ADMIN_BOT.initialize()
logger.info("Админ-бот для уведомлений инициализирован")
if application.job_queue:
application.job_queue.run_repeating(_cleanup_job, interval=CLEANUP_INTERVAL, first=CLEANUP_INTERVAL,
name='cleanup')
application.job_queue.run_repeating(_cookie_check_job, interval=COOKIE_CHECK_INTERVAL,
first=COOKIE_CHECK_INTERVAL, name='cookie_check')
logger.info("Периодические задачи запущены (очистка каждые %s мин, cookies каждые %s мин)",
CLEANUP_INTERVAL // 60, COOKIE_CHECK_INTERVAL // 60)
else:
logger.error("job_queue недоступен (нет python-telegram-bot[job-queue]) — периодические задачи не запущены")
await register_bot_meta(application.bot)
async def post_shutdown(application: Application) -> None:
task = application.bot_data.get('queue_worker_task')
if task:
task.cancel()
if ADMIN_BOT:
try:
await ADMIN_BOT.shutdown()
except Exception as e:
logger.warning("Ошибка при остановке админ-бота: %s", e)
def main() -> None:
if not TELEGRAM_BOT_TOKEN:
logger.error("TELEGRAM_BOT_TOKEN не установлен!")
return
db.init_database()
cleanup_old_files()
request = HTTPXRequest(read_timeout=3600, write_timeout=3600, connect_timeout=300, pool_timeout=300)
application = (
Application.builder()
.token(TELEGRAM_BOT_TOKEN)
.request(request)
.get_updates_request(HTTPXRequest(read_timeout=120, connect_timeout=60))
.defaults(Defaults(parse_mode='HTML', allow_sending_without_reply=True))
.post_init(post_init)
.post_shutdown(post_shutdown)
.build()
)
application.add_handler(CommandHandler("start", start_command))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
application.add_error_handler(on_error)
logger.info("Бот запущен")
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == '__main__':
main()