Помогите составить парсер бота на Aiogram; PDF в PNG

Суть того что бот должен качать файл с сайта колледжа(pdf) конвертировать его в png и отправлять в чат. Вызов команды с помошью /get. введите сюда описание изображения Тут расположен файл пдф который нужно будет скачать в корень программы и конвертировать в пнг или любой другой файл изображения. Я пытался сконертировать в пнг и отправить фотографии массивом, т.е. файлы который он конвертирует добовлять в массив. НО, если смотреть что происходит то он не качает пдф файл во время работы и не конвертирует, но как я только останавливаю бота, он сразу конвертирует и скачивает файл, я склонен к тому что это кривое отображение пайчарма. И при попытки отправить фотографии он не отправляет их. В интерненте решение на aiogram 2 с использованием executor. А я программирую на 3.3.0, прошу вас помочь с этим.

import asyncio
import logging
import fitz
import requests
import keyboards
from datetime import datetime
from aiogram import Bot, Dispatcher, html, F, types
from aiogram.filters import Command
from aiogram.types import Message
from aiogram.types import (
    ReplyKeyboardMarkup,
    KeyboardButton
)
from aiogram.utils.formatting import (Bold, as_list, as_marked_section, HashTag)
from bs4 import BeautifulSoup
from config_reader import config
logging.basicConfig(level=logging.INFO)
bot = Bot(token=config.bot_token.get_secret_value(), parse_mode="HTML")
dp = Dispatcher()
dp["started_at"] = datetime.now().strftime("%Y-%m-%d %H:%M")


@dp.message(Command("start"))
async def command_start_handler(message: Message) -> None:
    await message.answer(f"Hello, {html.bold(html.quote(message.from_user.full_name))}!", reply_markup=keyboards.main_kb)



@dp.message(Command("get"))
async def get_sait(message: types.Message):
    url = "https://lmk-lipetsk.ru/main_razdel/shedule/index.php"
    response = requests.get(url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')

        # Find all links on the page
        links = soup.find_all('a', href=True)

        # Assume that the link to the PDF contains the keyword "pdf"
        pdf_links = [link['href'] for link in links if 'pdf' in link['href'].lower()]

        if pdf_links:
            pdf_url = pdf_links[0]
            pdf_response = requests.get('https://lmk-lipetsk.ru' + pdf_url)

            if pdf_response.status_code == 200:
                with open("file.pdf", "wb") as pdf_file:
                    pdf_file.write(pdf_response.content)
                print("File successfully downloaded.")

                # Convert PDF to images
                pdf_document = fitz.open("file.pdf")
                image_list = []

                for page_number in range(pdf_document.page_count):
                    page = pdf_document[page_number]
                    image = page.get_pixmap()
                    image_path = f"page_{page_number + 1}.png"
                    image.save(image_path)

                    # Append the image to the list
                    image_list.append(bot.types.InputMediaPhoto(open(image_path, 'rb')))

                # Close the PDF document
                pdf_document.close()

                # Send all images in a single message
                await bot.send_media_group(message.chat.id, media=image_list)

                await message.answer("PDF successfully converted to images.")
            else:
                await message.answer(f"Error downloading PDF: {pdf_response.status_code}")
        else:
            await message.answer("PDF links not found.")
    else:
        await message.answer(f"Error getting the page: {response.status_code}")


async def main():
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot)


if __name__ == "__main__":
    asyncio.run(main())


Ответы (0 шт):