S
S
Semyon2021-12-12 00:14:12
Python
Semyon, 2021-12-12 00:14:12

How to get file_id without sending message to user?

I need immediately after starting the bot (written on pyTelegramBotAPI) to get all the file_id of the photos that I plan to send to the user in the future. Therefore, the option of sending all those photos to someone and getting the file_id that way is not an option. Maybe there is some other way to pre-save the photo data to the Telegram server?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2021-12-12
@GSimonX37

I solved this problem like this: the first time I sent the file, I sent it as a file, remembering the file_id in the dictionary and in the table in the database, and the next time I already had the file_id ready. At the same time, I can add files at any time without thinking about whether I have already uploaded them to Telegram or not.

files = {}
def load_files():
  global files
  res = db.execute("SELECT file_name,file_id FROM files")
  files = {}
  for row in res:
    file_name, file_id = row
    files[file_name] = file_id

def save_file(file_name, file_id):
  global files
  db.execute("INSERT INTO files (file_name,file_id) VALUES (?,?) ON CONFLICT(file_name) DO UPDATE SET file_id=excluded.file_id", (file_name, file_id))
  files[file_name] = file_id

load_files()

...
        if item["photo"] in files:
          file_id = files[item["photo"]]
          print (f" send photo file_name={item['photo']} file_id={file_id}")
          bot.send_photo(call.message.chat.id, file_id)
        else:
          with open(os.path.join("menu", item["photo"]), "rb") as f:
            bot.send_chat_action(call.message.chat.id, "upload_photo")
            r = bot.send_photo(call.message.chat.id, f)
            file_id = r.photo[0].file_id
            save_file(item["photo"], file_id)
            print (f" uploaded photo file_name={item['photo']} file_id={file_id}")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question