Home > other >  How to fetch media url through api
How to fetch media url through api

Time:06-21

How do I get a media instance through the REST api? I'm looking to either download the file or fetch the url for that media. I'm using Ruby

CodePudding user response:

You can get the media SID from a message resource. For example:

account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

messages = @client.conversations
                  .conversations('CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                  .messages
                  .list(order: 'desc', limit: 20)

messages.each do |message|
  puts message.sid
  message.media.each do |media|
    puts "#{media.sid}: #{media.filename} #{media.content_type}"
  end
end

I've not actually tried the above, the media objects may just be plain hashes and you would access the sid with media['sid'] instead.

Once you have the SID, you can fetch the media by constructing the following URL using the Chat service SID and the Media SID:

https://mcs.us1.twilio.com/v1/Services/<chat_service_sid>/Media/<Media SID>

For downloading files in Ruby, I like to use the Down gem. You can read about how to use Down to download images here. Briefly, here's how you would use Down and the URL above to download the image:

conversation_sid = "CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
media_sid = "MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
account_sid = ENV["TWILIO_ACCOUNT_SID"]
auth_token = ENV["TWILIO_AUTH_TOKEN"]

url = "https://#{account_sid}:#{auth_token}@mcs.us1.twilio.com/v1/Services/#{conversation_sid}/Media/#{media_sid}"

tempfile = Down.download(url)
  • Related