Downloading media files from Twilio in Python

醉酒当歌 提交于 2020-02-05 08:34:19

问题


I'm trying to download all the media that is sent to my Twilio account and cannot for the life of me figure out how to access the actual images.

from twilio.rest import Client
import requests
from operator import itemgetter
import json

ACCOUNT_SID = "xxxxxxx"
AUTH_TOKEN = "xxxxxxxx"

client = Client(ACCOUNT_SID, AUTH_TOKEN)


# builds a list of messages and media uris
messages = client.messages.list(from_="+19999999999")
msgs = []
for m in messages:
    line = [m.from_, m.to, m.body, m.sid, m.subresource_uris['media']]
    line = [str(x) for x in line]
    msgs.append(line)

# with list of all messages:
msgs = sorted(msgs, key=itemgetter(0))
for m in msgs:
    # get media list for each message that has one, else catch exception
    try:
        medias = client.messages(m[3]).media.list()
        # returns Twilio.Api.V2010.MediaInstance and i'm stuck
        for med in medias:
            print client.messages(m[3]).media(med.sid).fetch()
    except Exception as e:
        pass

I am just lost and can't find any concrete examples in the documentation. I really can't even tell if I'm close, or waaaaaaaaaaay off. Thanks in advance!

SOLUTION Thanks to philnash from twilio.rest import Client import requests import json

# Find these values at https://twilio.com/user/account
ACCOUNT_SID = "xxxxx"
AUTH_TOKEN = "xxxxxx"
BASE_URL = "https://%s:%s@api.twilio.com" % (ACCOUNT_SID, AUTH_TOKEN)

client = Client(ACCOUNT_SID, AUTH_TOKEN)


# with list of all messages:
messages = client.messages.list(from_="+1999999999")
for m in messages:
    sid = m.sid
    # get media list for each message that has one, else catch exception
    try:
        message = client.messages(sid).fetch()
        print message.body
        medias = message.media.list()
        # returns Twilio.Api.V2010.MediaInstance and i'm stuck
        for media in medias:
            media_instance = client.messages(sid).media(media.sid).fetch()
            uri = requests.get(BASE_URL + media_instance.uri).json()
            uri2 = requests.get(BASE_URL + uri['uri'].replace('.json', ''))
            with open(media_instance.uri.split("/")[-1].replace(".json", ".png"), "wb") as f:
                f.write(uri2.content)
                f.close()
    except Exception as e:
        print e

回答1:


Twilio developer evangelist here.

When you get the Media URI from the helper library, it is the json representation of the resource and ends in .json. To get the raw resource you need only to strip the .json extension. You can use that URL to download the image.



来源:https://stackoverflow.com/questions/43645723/downloading-media-files-from-twilio-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!