FredS
FredS

Reputation: 25

How to get a media messages URL using the twilio rest api?

I am trying to gather the URL of a media message sent in by a user in a python function. In theory (and according to this https://www.twilio.com/blog/retrieving-twilio-mms-image-urls-in-python tutorial) my python code below should work for this:

last_message = client.messages.list(limit = 1)
last_message_instance = last_message[0]
media = last_message_instance
media_url = 'https://api.twilio.com' + media.uri[:-5]

However, for some reason the media.uri parameter does not return all three sid (AccountSid, MessageSid, Sid) strings needed for the url. The url should be composed of:

https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages/{MessageSid}/Media/{Sid}.json

The .uri returns only my AccountSid and the sent message's MessageSid (interestingly, labelled as Sid in the json message as shown below)

"sid": "MMbde22b567bf7e3c77fcd4fe01d286446",

Does anyone have any tips on how to find the Media/{Sid} term I need (this typically begins with MEXxXxXxX) Thanks!

Upvotes: 1

Views: 1963

Answers (1)

philnash
philnash

Reputation: 73075

I think the issue here is that you are only making the request to the API to get a message, which is why you do not have the detail about the media.

You can request the media for the message by calling last_message_instance.media.list(). The result of that will be a list of media objects from which you can get the media URL.

last_message = client.messages.list(limit = 1)
last_message_instance = last_message[0]
    for media in last_message_instance.media.list():
        media_url = 'https://api.twilio.com' + media.uri[:-5]
        print(media_url)

Upvotes: 2

Related Questions