0

I am using Ruby for my telegram bot. People send some information to bot, and some times it is photo. I Need to save this photo to my computer in directory with Ruby file and then send this photo another people if he or she is needed of it.

So, How do I download a photo that was sent to my Telegram bot? I know about getFile from official site of Telegram and about this question How do I download a file or photo that was sent to my Telegram bot? but i don't understand how to use it with Ruby, because i'm start ruby only 5 months ago. I try to wrote different code, but all doesn't work...

bot.messages_handler(content_types=['photo'])
bot.send_message(message.chat_id,bot.get_file_url(message.photo[0].file_id))

I'm hope for your help.

UPDATE! So, now after codding and analisis all information and answer I have code which can find 'file_id' of photo from message of user and use this 'file_id' for sending this photo to another users.

if message.photo
  info_about_phot = message.photo.to_s #Hash all info about photo to string
  for i in ((info_about_phot.index('@file_id="')+10).. 
      (info_about_phot.index('", @file_unique_id=')-1)) #find all simbols of 'file_id' inside info about photo
      info_about_phot = info_about_phot + message.photo.to_s[i] #mabe 'file_id from all simbols'
   end
end
bot.api.send_photo(chat_id: message.from.id, photo: info_about_phot) #send message with only photo

may be it is not so clear as variant of @mechnicov but it works perfect and help me with my problem. But if some body can write better code - i will say "Thanks!!!".

Max
  • 1
  • 1

1 Answers1

0

You didn't specify used gem

Just as example using telegram-bot-ruby

You can pass photo file_id from message to getFile method and get file information, that has file_path attribute

photo_url = bot.api.get_file(message.photo.last.file_id).file_path

It is photo URL. After that you can download file different ways with Ruby, for example

require "open-uri"

io = URI.open(photo_url)
File.open(path_to_save, 'w') { |f| f.write(io.read) }
mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • Thanks for wanting to help I use ruby-2.7.2 after you answer i try to use your code and now have this eror undefined method `file_id' for nil:NilClass (NoMethodError) – Max Sep 02 '22 at 09:04
  • @Max it means there is no photo in that message – mechnicov Sep 02 '22 at 10:45
  • thanks you for help, after you answer i analised it and wrote code which helped me. I wrote it also in the top question. – Max Sep 02 '22 at 14:55