forked from gtrnocswift/mobile-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
72 lines (60 loc) · 2.31 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
from flask import Flask, request
from twilio.util import TwilioCapability
import twilio.twiml
# Account Sid and Auth Token can be found in your account dashboard
ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
# TwiML app outgoing connections will use
APP_SID = 'APZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'
CALLER_ID = '+12345678901'
CLIENT = 'jenny'
app = Flask(__name__)
@app.route('/token')
def token():
account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
auth_token = os.environ.get("AUTH_TOKEN", AUTH_TOKEN)
app_sid = os.environ.get("APP_SID", APP_SID)
capability = TwilioCapability(account_sid, auth_token)
# This allows outgoing connections to TwiML application
if request.values.get('allowOutgoing') != 'false':
capability.allow_client_outgoing(app_sid)
# This allows incoming connections to client (if specified)
client = request.values.get('client')
if client != None:
capability.allow_client_incoming(client)
# This returns a token to use with Twilio based on the account and capabilities defined above
return capability.generate()
@app.route('/call', methods=['GET', 'POST'])
def call():
""" This method routes calls from/to client """
""" Rules: 1. From can be either client:name or PSTN number """
""" 2. To value specifies target. When call is coming """
""" from PSTN, To value is ignored and call is """
""" routed to client named CLIENT """
resp = twilio.twiml.Response()
from_value = request.values.get('From')
to = request.values.get('To')
if not (from_value and to):
resp.say("Invalid request")
return str(resp)
from_client = from_value.startswith('client')
caller_id = os.environ.get("CALLER_ID", CALLER_ID)
if not from_client:
# PSTN -> client
resp.dial(callerId=from_value).client(CLIENT)
elif to.startswith("client:"):
# client -> client
resp.dial(callerId=from_value).client(to[7:])
else:
# client -> PSTN
resp.dial(to, callerId=caller_id)
return str(resp)
@app.route('/', methods=['GET', 'POST'])
def welcome():
resp = twilio.twiml.Response()
resp.say("Welcome to Twilio")
return str(resp)
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)