Реструкт, [22.08.2024 15:49] import telebot from telebot import types import ytdlp…
- User
Реструкт, [22.08.2024 15:49] import telebot from telebot import types import yt_dlp import os import threading
Ваш токен бота
TOKEN = '6782933152:AAGjeStV1QXEDwUzDRg1HmUxCpIwy-_vt7w' bot = telebot.TeleBot(TOKEN)
Настройки yt-dlp
ydl_opts = { 'format': 'best', 'outtmpl': '%(title)s.%(ext)s', }
Глобальная переменная для отслеживания загрузок
is_downloading = False
def get_video_info(url): with yt_dlp.YoutubeDL() as ydl: info_dict = ydl.extract_info(url, download=False) return info_dict
def get_available_formats(url): info_dict = get_video_info(url) formats = info_dict.get('formats', []) return [(fmt['format_id'], fmt.get('format_note', 'No description available')) for fmt in formats]
def download_video(url, quality, chat_id): global is_downloading is_downloading = True ydl_opts['format'] = quality with yt_dlp.YoutubeDL(ydl_opts) as ydl: try: ydl.download([url]) info_dict = ydl.extract_info(url, download=False) video_title = info_dict['title'] send_video(chat_id, video_title) except Exception as e: bot.send_message(chat_id, "Ошибка при загрузке видео.") print(e) finally: is_downloading = False
def send_video(chat_id, video_title): video_file = f"{video_title}.mp4" audio_file = f"{video_title}.mp3"
if os.path.exists(video_file): with open(video_file, 'rb') as video: bot.send_video(chat_id, video) os.remove(video_file) if os.path.exists(audio_file): with open(audio_file, 'rb') as audio: bot.send_audio(chat_id, audio) os.remove(audio_file)@bot.message_handler(commands=['start']) def send_welcome(message): bot.reply_to(message, "Привет! Отправь мне ссылку на YouTube видео, чтобы скачать его.")
@bot.message_handler(commands=['cancel']) def cancel_download(message): global is_downloading if is_downloading: is_downloading = False bot.send_message(message.chat.id, "Загрузка отменена.") else: bot.send_message(message.chat.id, "Нет активной загрузки.")
@bot.message_handler(func=lambda message: True) def handle_message(message): url = message.text available_formats = get_available_formats(url)
if not available_formats: bot.send_message(message.chat.id, "Не удалось получить доступные форматы для этого видео.") return # Получаем информацию о видео video_info = get_video_info(url) video_title = video_info.get('title', 'Видео') video_thumbnail = video_info.get('thumbnail', None) # Отправляем превью видео if video_thumbnail: bot.send_photo(message.chat.id, video_thumbnail, caption=f"Название: {video_title}\nВыберите качество для загрузки:") markup = types.InlineKeyboardMarkup() for format_id, format_note in available_formats: markup.add(types.InlineKeyboardButton(format_note, callback_data=f"{url}::{format_id}")) bot.send_message(message.chat.id, "Выберите качество:", reply_markup=markup)@bot.callback_query_handler(func=lambda call: True) def handle_query(call): url, quality = call.data.split("::") if is_downloading: bot.answer_callback_query(call.id, "Загрузка уже в процессе. Пожалуйста, отмените загрузку перед началом новой.") return
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.