Telegram bot fails to send PDF document with HTTP URL error

I’m having trouble with my Telegram bot when trying to send a PDF file. Every time I attempt to send the document, I get this error message: aiogram.exceptions.TelegramBadRequest: Telegram server says - Bad Request: failed to get HTTP URL content

Here’s my code that handles photo processing and PDF generation:

import os
import uuid
import asyncio
from aiogram import Router, F, Bot
from aiogram.filters import CommandStart
from aiogram.types import Message
from gradio_client import Client, handle_file

msg_router = Router()

def process_math_question(file_path):
    ai_client = Client("Qwen/Qwen2-Math-Demo")
    response = ai_client.predict(
        image=handle_file(file_path),
        sketchpad={
            "background": handle_file(
                'https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png'),
            "layers": [],
            "composite": None
        },
        question="solve this, answer in LaTex format",
        api_name="/math_chat_bot"
    )
    return response

@msg_router.message(CommandStart())
async def start_command(msg: Message):
    await msg.answer("Hello there!")

@msg_router.message(F.photo)
async def handle_photo(msg: Message, telegram_bot: Bot):
    temp_image = f"{uuid.uuid4()}.png"
    
    file_data = await telegram_bot.get_file(msg.photo[-1].file_id)
    await telegram_bot.download_file(file_data.file_path, destination=temp_image)
    
    await msg.answer("Processing your request...")
    
    math_result = await asyncio.to_thread(process_math_question, temp_image)
    output_file = f"{uuid.uuid4()}.tex"
    
    with open(output_file, "w") as tex_file:
        tex_file.write(f"{math_result}")
    
    os.system('bash convert_script.sh')
    await msg.answer_document("output.pdf")
    
    os.remove(temp_image)
    os.remove(output_file)
    os.remove("output.tex")

I tried using msg.answer_document("filename") but it doesn’t work. The PDF file gets created successfully by the bash script, but sending it through the bot fails. What could be causing this issue?

try using FSInputFile instead of just passing the string path. something like await msg.answer_document(FSInputFile('output.pdf')) - worked for me when i had same issue with pdf sending. also double check your bash script isnt changing working directory

Had this exact problem last month and it drove me crazy for hours. The issue is probably timing related - your bash script might still be running when you try to send the PDF. I noticed you’re not waiting for the bash script to complete before calling answer_document. Try replacing os.system('bash convert_script.sh') with subprocess.run(['bash', 'convert_script.sh'], check=True) to ensure it finishes properly. Also worth adding a small delay with await asyncio.sleep(1) after the script runs, just to be safe. Another thing that caught me out was file permissions - make sure your bot process has read access to the generated PDF. You can verify this by adding a print statement to check the file size before sending it.

This error typically occurs when the bot tries to access a file that doesn’t exist at the specified path or lacks proper permissions. Looking at your code, I suspect the issue is with file path handling. You’re creating files with UUID names but then referencing ‘output.pdf’ directly in the answer_document call. I had a similar problem with my bot where the bash script was creating files in a different directory than expected. Try using absolute file paths and verify the PDF actually exists before sending it. Add a quick check like ‘if os.path.exists(“output.pdf”):’ before the answer_document line. Also consider using InputFile from aiogram.types for better file handling - it gives you more control over the file object being sent. Make sure your convert_script.sh is actually producing the output.pdf file in the correct location where your Python script expects it.