skip to Main Content

I’m coding a telegram bot with python and Aiogram.
I can’t send local photos on the chat but if I link one that’s from google it’s OK. Why is that?

    script_directory = os.path.dirname(os.path.abspath(__file__))

    percorso_img = script_directory + '\images\volume1.jpg'
    print(percorso_img)

    await message.answer_photo('https://m.media-amazon.com/images/I/71Rpwr00gpS._AC_UF1000,1000_QL80_.jpg')
    await message.answer_photo(percorso_img)

This is my code, the first photo is sent on the bot as it is a link from the internet.
The second which is a path to a local photo is not. The path is correct as printed on the terminal and by clicking it to open the photo.

This is the error that I get
TelegramBadRequest: Telegram server says - Bad Request: invalid file HTTP URL specified: Wrong port number specified in the URL

I’ve tried other methods like

script_directory = os.path.dirname(os.path.abspath(__file__))
percorso_immagine = os.path.join(script_directory, 'images', 'volume1.jpg')

with open(percorso_immagine, 'rb') as immagine_file:
    input_file = types.InputFile(immagine_file)

await message.answer_photo(input_file)

and i get other errors

Errore nell'invio dell'immagine: Can't instantiate abstract class InputFile with abstract method read

also tried

   photo=open(percorso_img, "rb")
   await bot.send_photo(message.from_user.id, photo)

but

ValidationError: 2 validation errors for SendPhoto
photo.is-instance[InputFile]
  Input should be an instance of InputFile [type=is_instance_of, input_value=<_io.BufferedReader name=...m\images\volume1.jpg'>, input_type=BufferedReader]
    For further information visit https://errors.pydantic.dev/2.3/v/is_instance_of
photo.str
  Input should be a valid string [type=string_type, input_value=<_io.BufferedReader name=...m\images\volume1.jpg'>, input_type=BufferedReader]
    For further information visit https://errors.pydantic.dev/2.3/v/string_type`

2

Answers


  1. Try to use this way for local photo:

    await message.answer_photo(
            types.FSInputFile(path=path_to_photo), caption="Some kind of caption"
        )
    

    And this for photo from the internet:

    await call.message.answer_photo(
            photo=URLInputFile(
                url=photo_url,
                filename=f"picture.png"
            ), caption="Some kind of caption"
        )
    

    I tested the performance of these methods on aiogram version 3 and Python 3.11 works

    Login or Signup to reply.
  2. Thanks a lot! It was so helpful!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search