Twilio developer evangelist here.
When you use <Record>
to record a user, you can provide a URL as the recordingStatusCallback
attribute. Then, when the recording is ready, Twilio will make a request to that URL with the details about the recording.
So, you can update your record
TwiML to something like this:
# Use <Record> to record the caller's message
response.record(
recording_status_callback="/recording-complete",
recording_status_callback_event="completed"
)
Then you will need a new route for /recording-complete
in which you receive the callback and download the file. There is a good post on how to download files in response to a webhook but it covers MMS messages. However, we can take what we learn from there to download the recording.
First, install and import the requests
library. Also import request
from Flask
import requests
from flask import Flask, request
Then, create the /recording-complete
endpoint. We'll read the recording URL from the request. You can see all the request parameters in the documentation. Then we'll open a file using the recording SID as the file name, download the recording using requests and write the contents of the recording to the file. We can then respond with an empty <Response/>
.
@app.route("/recording-complete", methods=['GET', 'POST'])
def recording_complete():
response = VoiceResponse()
# The recording url will return a wav file by default, or an mp3 if you add .mp3
recording_url = request.values['RecordingUrl'] + '.mp3'
filename = request.values['RecordingSid'] + '.mp3'
with open('{}/{}'.format("directory/to/download/to", filename), 'wb') as f:
f.write(requests.get(recording_url).content)
return str(resp)
Let me know how you get on with that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…