|
| 1 | +import os |
| 2 | +from flask import Flask, request |
| 3 | +from twilio.twiml.voice_response import VoiceResponse |
| 4 | +from twilio.rest import Client |
| 5 | + |
| 6 | + |
| 7 | +app = Flask(__name__) |
| 8 | + |
| 9 | +# pulls credentials from environment variables |
| 10 | +client = Client() |
| 11 | + |
| 12 | +BASE_URL = os.getenv("BASE_URL") |
| 13 | +twiml_instructions_url = "{}/record".format(BASE_URL) |
| 14 | +recording_callback_url = "{}/callback".format(BASE_URL) |
| 15 | + |
| 16 | +twilio_phone_number = os.getenv("TWILIO_PHONE_NUMBER") |
| 17 | + |
| 18 | + |
| 19 | +@app.route("/record", methods=["GET", "POST"]) |
| 20 | +def record(): |
| 21 | + """Returns TwiML which prompts the caller to record a message""" |
| 22 | + # Start our TwiML response |
| 23 | + response = VoiceResponse() |
| 24 | + |
| 25 | + # Use <Say> to give the caller some instructions |
| 26 | + response.say('Ahoy! Call recording starts now.') |
| 27 | + |
| 28 | + # Use <Record> to record the caller's message |
| 29 | + response.record() |
| 30 | + |
| 31 | + # End the call with <Hangup> |
| 32 | + response.hangup() |
| 33 | + |
| 34 | + return str(response) |
| 35 | + |
| 36 | + |
| 37 | +@app.route("/dial/<int:phone_number>") |
| 38 | +def dial(phone_number): |
| 39 | + """Dials an outbound phone call to the number in the URL. Just |
| 40 | + as a heads up you will never want to leave a URL like this exposed |
| 41 | + without authentication and further phone number format verification. |
| 42 | + phone_number should be just the digits with the country code first, |
| 43 | + for example 14155559812.""" |
| 44 | + call = client.calls.create( |
| 45 | + to='+{}'.format(phone_number), |
| 46 | + from_=twilio_phone_number, |
| 47 | + url=twiml_instructions_url, |
| 48 | + ) |
| 49 | + print(call.sid) |
| 50 | + return "dialing +{}".format(phone_number) |
| 51 | + |
| 52 | + |
| 53 | +@app.route("/get-recording-url/<call_sid>") |
| 54 | +def get_recording_url(call_sid): |
| 55 | + recording_urls = "" |
| 56 | + call = client.calls.get(call_sid) |
| 57 | + for r in call.recordings.list(): |
| 58 | + recording_urls="\n".join([recording_urls, r.uri]) |
| 59 | + return str(recording_urls) |
0 commit comments