I have multiple twilio numbers, for e.g 2 active numbers. When anyone calls number A, forward it xyz number but when a user calls number B, I want it to be forwarded to a different number. I want it do it using python flask/django or even a simple python script. Is there any way to create complete call forwarding studio flow using python like this: https://www.twilio.com/docs/studio/tutorials/how-to-forward-calls. Right now, I have implemented https://www.twilio.com/blog/routing-incoming-phone-calls-twilio-programmable-voice-python-django but its no good. Because this only works for 1 number.
1 Answers
From the information provided in your question, this is what i understand:
You have 2 twilio numbers say 'A' and 'B'. You want to configure a call flow such that when A receives an incoming call from say 'caller1' you want to forward it to a number say 'X'
'caller1' ==> 'A' ==> 'X' (caller1 and X will be connected)
Similarly for 'B'
Let's say 'caller2' ==> 'B' ==> 'Y' (caller2 and Y will be connected)
You can achieve this using webhooks.
Login to your Twilio account on the Twilio console webpage and Go to your Twilio number 'A'. Under the section Voice & Fax, you will find a field with title "A call comes in" In the drop down, select Webhook. Now in the text field beside the dropdown, enter the URL which points to a server whose task will be to respond with a TwiML[containing the forward to number (X in our case)]. In case you are hosting the server locally, you can use ngrok and tunnel the request sent by Twilio to the local server.
For Twilio number A, you can setup a webhook as: http://ngrok_public_url.ngrok.io/forwardA
and for B, you can setup the webhook as: http://ngrok_public_url.ngrok.io/forwardB
Next you will have to create flask endpoints to handle the above routes
from flask import Flask
from twilio.twiml.voice_response import Dial, VoiceResponse, Say
app = Flask(__name__)
@app.route("/forwardA", methods=['GET', 'POST'])
def callForwardA():
resp = VoiceResponse()
resp.dial('X_phone_number')
resp.say('Goodbye')
return str(resp)
@app.route("/forwardB", methods=['GET', 'POST'])
def callForwardB():
resp = VoiceResponse()
resp.dial('Y_phone_number')
resp.say('Goodbye')
return str(resp)
if __name__ == "__main__":
app.run(debug=True, host = '127.0.0.1', port = 3000)