E
E
Eugene2019-03-20 19:08:20
Python
Eugene, 2019-03-20 19:08:20

How to get file_id of photos?

I will say right away - I am not connected with it, my education is not specialized, I am working on a small pet project after reading 1 book and watching several dozen videos + a couple of dozen tasks from chekio.org on Python. You can directly say where and what is wrong, I will only be glad!
The essence is a small telegram bot that takes orders and sends them to the operator. There are photos of dishes neatly folded into a folder in the project directory. There is a list of dishes with a description and a path to the file with the image of the dish. Designed as a dictionary (config.menu).
On command, we run the function, get the id and save it to a .txt file in the format Name of the dish \n ​​File ID of the photo.

def photo_id(message):
    result = str()
    for i in config.menu:
        file = config.menu[i][1]
        photo = open(file, 'rb')
        msg = bot.send_photo(message.chat.id, photo, None)
        temp_file_id = bot.send_message(message.chat.id, msg.photo[0].file_id, reply_to_message_id=msg.message_id)
        temp_file_id = f'{temp_file_id}'
        index = temp_file_id.rfind(':')
        start = index + 3
        stop = index + 59
        temp_file_id = temp_file_id[start:stop]
        result += f'{i}\n{temp_file_id}\n\n'
    with open("File_ID.txt", "w") as file:
        file.write(result)

It doesn't look very elegant in my opinion. Is there an option not to translate the received message into a string and not to search for the beginning of file_id with rfind?
An additional question - when assigning values ​​to the msg and temp_file_id variables, the bot sends both a message and a photo. Is there a way to keep the bot from making extra moves?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bbkmzzzz, 2019-03-21
@bbkmzzzz

Look towards the serialization libraries. For example pickle or json.
json example:

import json

    data = {
        'param1': 'val1',
        'param2': 10,
        'parm3': 11.54,
        'country': {
            'name': 'Russia',
            'cities': ['Moscow']
        }
    }
    print(data)
    serialized_to_string = json.dumps(data)  # сериализация с записью в строку
    print(serialized_to_string)
    with open('testfile.json', 'w') as fle:
        json.dump(data, fle) # сериализация с записью в файл
    #  ### читаем
    with open('testfile.json', 'r') as fle:
        loaded = json.load(fle)  #  чтение из файла
    print(loaded)
    loaded_from_string = json.loads(serialized_to_string) # из строки
    print(serialized_to_string)

Thus, the object is saved to a string or file, and then the object is also loaded.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question