Код:
import logging
import os
from aiogram import Bot, Dispatcher, types
from aiogram.types import ParseMode
from aiogram.utils import executor
from pytube import YouTube
from moviepy.editor import AudioFileClip
API_TOKEN = ''
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
await message.reply("Привет! Отправь мне ссылку на YouTube видео, и я скачаю его в mp3 для тебя.")
@dp.message_handler(regexp=r'^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$')
async def download_video(message: types.Message):
url = message.text
await message.reply("Скачиваю видео, подождите немного...")
try:
# Скачиваем видео с YouTube
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
output_file = video.download()
# Конвертируем видео в mp3
base, ext = os.path.splitext(output_file)
new_file = base + '.mp3'
audio_clip = AudioFileClip(output_file)
audio_clip.write_audiofile(new_file)
audio_clip.close()
# Отправляем mp3 файл пользователю
await bot.send_audio(message.chat.id, audio=open(new_file, 'rb'))
# Удаляем временные файлы
os.remove(output_file)
os.remove(new_file)
except Exception as e:
await message.reply(f"Произошла ошибка: {e}")
if __name__ == '__main__':
from aiogram import executor
executor.start_polling(dp, skip_updates=True)

