telegramtelegram-bot

Telegram bot upload file API response is not consistent


When I upload a txt file I get the file name in event. For e.g. 'basane.txt' in this case.

{'update_id': 154781156, 'message': {'message_id': 40, 'from': {'id': 6718326872, 'is_bot': False, 'first_name': 'Shantanu', 'last_name': 'Oak', 'username': 'soak', 'language_code': 'en'}, 'chat': {'id': 6718326872, 'first_name': 'Shantanu', 'last_name': 'Oak', 'username': 'soak', 'type': 'private'}, 'date': 1727147855, 'document': {'file_name': 'basane.txt', 'mime_type': 'text/plain', 'file_id': 'BQACAgUAAxkBAAMoZvIvTyoUOQUwqs8JkQlUWyADDCMAArsQAAJklpFX9DE7pYrYYYk2BA', 'file_unique_id': 'AgADuxAAAmSWkVc', 'file_size': 325405}}}

But if I upload an image file, I do not get the filename. For e.g. in this response I do not see the name of the jpg file that I sent.

{'update_id': 154781157, 'message': {'message_id': 41, 'from': {'id': 6718326872, 'is_bot': False, 'first_name': 'Shantanu', 'last_name': 'Oak', 'username': 'soak', 'language_code': 'en'}, 'chat': {'id': 6718326872, 'first_name': 'Shantanu', 'last_name': 'Oak', 'username': 'soak', 'type': 'private'}, 'date': 1727150140, 'photo': [{'file_id': 'AgACAgUAAxkBAAMpZvI4PMcy02obaSa47F9dsjKuleIAAmvBMRtklpFX7-sCRfMcqD8BAAMCAANzAAM2BA', 'file_unique_id': 'AQADa8ExG2SWkVd4', 'file_size': 829, 'width': 90, 'height': 50}, {'file_id': 'AgACAgUAAxkBAAMpZvI4PMcy02obaSa47F9dsjKuleIAAmvBMRtklpFX7-sCRfMcqD8BAAMCAANtAAM2BA', 'file_unique_id': 'AQADa8ExG2SWkVdy', 'file_size': 10699, 'width': 320, 'height': 179}, {'file_id': 'AgACAgUAAxkBAAMpZvI4PMcy02obaSa47F9dsjKuleIAAmvBMRtklpFX7-sCRfMcqD8BAAMCAAN4AAM2BA', 'file_unique_id': 'AQADa8ExG2SWkVd9', 'file_size': 42287, 'width': 800, 'height': 447}, {'file_id': 'AgACAgUAAxkBAAMpZvI4PMcy02obaSa47F9dsjKuleIAAmvBMRtklpFX7-sCRfMcqD8BAAMCAAN5AAM2BA', 'file_unique_id': 'AQADa8ExG2SWkVd-', 'file_size': 81771, 'width': 1280, 'height': 716}]}}

I need the name of the image file to process it correctly. (like the .txt file)


Solution

  • This is expected behaviour.

    Both sendDocument and sendPhoto return a Message object`.

    The Message here has a photo index that holds an array of photoSize, which does not contain any filename. Telegram strips all meta data from photo's, so there is not way or retrieving that.

    On the other hand, the Document object does has an (optional) file_name, as defined by the sender.

    You could upload the image as a document as well, so not using sendPhoto, but rather sendDocument, this way it will not be shown in chat, but as a file with an actual name.