Я разделил весь бот на 4 файла:
main.py
import os, re, configparser, pafy
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher, FSMContext
from aiogram.utils import executor
from aiogram.utils.helper import Helper, HelperMode, ListItem
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
from keyboard import menu, back, make_keyboards
config = configparser.ConfigParser()
config.read("settings.ini")
TOKEN = '5770821791:AAEqNmQmuiBIaDfiCOEZB70mIKvmUNDgNi4'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot, storage=MemoryStorage())
def get_title(url):
yVideo = pafy.new(url)
title = yVideo.title
return title
def get_author(url):
yVideo = pafy.new(url)
author = yVideo.author
return author
def get_url(call):
url = call.split('|')
video_url = url[1]
return video_url
def get_download_url_with_audio(url_video):
yVideo = pafy.new(url_video)
video = yVideo.getbest()
return video.url_https
def get_download_url_best_video(url_video):
yVideo = pafy.new(url_video)
video = yVideo.getbestvideo()
return video.url_https
def get_download_url_best_audio(url_video):
yVideo = pafy.new(url_video)
video = yVideo.getbestaudio()
return video.url_https
class Info(StatesGroup):
video = State()
@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
await bot.send_message(chat_id=message.chat.id, text=' Привет, я помогу тебе скачать видео с YouTube.', reply_markup = menu())
@dp.message_handler(text="Скачать")
async def save_video(message: types.Message):
await bot.send_message(chat_id=message.chat.id, text=' Введи ссылку на видео: ', reply_markup=back())
await Info.video.set()
@dp.message_handler(state=Info.video, content_types=types.ContentTypes.TEXT)
async def edit_name(message: types.Message, state: FSMContext):
if message.text.lower() == 'отмена':
await bot.send_message(chat_id=message.chat.id, text='Ты вернулся в главное меню.', reply_markup=menu())
await state.finish()
else:
if message.text.startswith('https://www.youtube.com/watch?v=' or "https://youtu.be/"):
try:
video_url = message.text
await bot.send_message(chat_id=message.chat.id, text=f'Название видео: {get_title(video_url)}\nАвтор: {get_author(video_url)}\n\nВыберите качество загрузки:', reply_markup = make_keyboards(video_url))
await state.finish()
except OSError:
await bot.send_message(chat_id=message.chat.id, text=f'Ссылка неверная, либо видео не найдено. Введи ссылку в формате: ```https://www.youtube.com/watch?v=...```', reply_markup = back(), parse_mode="Markdown")
except ValueError:
await bot.send_message(chat_id=message.chat.id, text=f'Ссылка неверная, либо видео не найдено. Введи ссылку в формате: ```https://www.youtube.com/watch?v=...```', reply_markup = back(), parse_mode="Markdown")
else:
await bot.send_message(chat_id=message.chat.id, text=f'Введи ссылку в формате: ```https://www.youtube.com/watch?v=...```', reply_markup = back(), parse_mode="Markdown")
@dp.callback_query_handler()
async def handler_call(call: types.CallbackQuery, state: FSMContext):
chat_id = call.from_user.id
if call.data.startswith('best_with_audio'):
await bot.delete_message(call.message.chat.id, call.message.message_id)
video_url = get_url(call.data)
download_link = get_download_url_with_audio(video_url)
await bot.send_message(chat_id=chat_id, text=f' Вот ваша ссылка на скачивание видео: {download_link}', reply_markup = menu())
elif call.data.startswith('best_video'):
await bot.delete_message(call.message.chat.id, call.message.message_id)
video_url = get_url(call.data)
download_link = get_download_url_best_video(video_url)
await bot.send_message(chat_id=chat_id, text=f' Вот ваша ссылка на скачивание видео: {download_link}', reply_markup = menu())
elif call.data.startswith('best_audio'):
await bot.delete_message(call.message.chat.id, call.message.message_id)
video_url = get_url(call.data)
download_link = get_download_url_best_audio(video_url)
await bot.send_message(chat_id=chat_id, text=f' Вот ваша ссылка на скачивание аудио: {download_link}', reply_markup = menu())
elif call.data == 'cancel':
await bot.delete_message(call.message.chat.id, call.message.message_id)
await bot.send_message(chat_id=chat_id, text='Ты вернулся в главное меню.', reply_markup=menu())
if __name__ == "__main__":
executor.start_polling(dp, skip_updates=True)
keyboard.py
from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
def menu():
download_button = KeyboardButton('Скачать')
menu_kb = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
menu_kb.add(download_button)
return menu_kb
def back():
button_back = KeyboardButton('Отмена')
back_kb = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
back_kb.add(button_back)
return back_kb
def make_keyboards(url):
inline_kb1 = InlineKeyboardMarkup()
button = InlineKeyboardButton('Лучшее качество до 720p(с звуком).', callback_data=f'best_with_audio|{url}')
button2 = InlineKeyboardButton('Лучшее качество(без звука).', callback_data=f'best_video|{url}')
button3 = InlineKeyboardButton('Звук в лучшем качестве.', callback_data=f'best_audio|{url}')
button4 = InlineKeyboardButton('Отмена', callback_data=f'cancel')
inline_kb1.add(button)
inline_kb1.add(button2)
inline_kb1.add(button3)
inline_kb1.add(button4)
return inline_kb1
start.bat
py main.py
pause
Ошибка :
Task exception was never retrieved
future: <Task finished name='Task-22' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=ButtonDataInvalid('Button_data_invalid')>
Traceback (most recent call last):
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File "c:\Users\Intel\Desktop\Data\yt_download_bot\main.py", line 69, in edit_name
await bot.send_message(chat_id=message.chat.id, text=f'Название видео: {get_title(video_url)}\nАвтор: {get_author(video_url)}\n\nВыберите качество загрузки:', reply_markup = make_keyboards(video_url))
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\bot\bot.py", line 346, in send_message
result = await self.request(api.Methods.SEND_MESSAGE, payload)
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\bot\base.py", line 236, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\bot\api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\bot\api.py", line 115, in check_result
exceptions.BadRequest.detect(description)
File "C:\Users\Intel\AppData\Local\Programs\Python\Python310\lib\site-packages\aiogram\utils\exceptions.py", line 140, in detect
raise err(cls.text or description)
aiogram.utils.exceptions.ButtonDataInvalid: Button_data_invalid