Install Twilio's Python Library
- Ensure you have Python and pip (Python package manager) installed on your system.
- Install the Twilio Python library using pip:
pip install twilio
Set Up Your Environment
- Create a new Python file in your project directory.
- Import the necessary modules from the Twilio library:
from twilio.rest import Client
Authenticate Your Twilio Client
- Copy your Twilio Account SID and Auth Token from your Twilio Console.
- Initialize the Twilio client with these credentials:
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
Make a Call
- Define the numbers for the call; the 'from\_' number must be your Twilio number:
- Use the `client.calls.create` method to initiate a call and pass a URL providing TwiML instructions:
call = client.calls.create(
to='+1234567890',
from_='+0987654321',
url='http://demo.twilio.com/docs/voice.xml'
)
Handle Incoming Calls
- Set up a web server using Flask to respond to incoming calls with TwiML (Twilio Markup Language).
- Create a simple Flask application:
from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse
app = Flask(__name__)
@app.route("/voice", methods=['GET', 'POST'])
def voice():
response = VoiceResponse()
response.say("Hello, this is a call from Twilio!")
return str(response)
if __name__ == "__main__":
app.run(debug=True)
Configure Twilio to Use Your Webhook
- In your Twilio Console, configure the phone number settings to point to your Flask server URL for voice calls.
- For development purposes, use `ngrok` to expose your local server to the Internet:
ngrok http 5000
Test Your Implementation
- Use a phone to call your Twilio number and verify the TwiML response is correctly processed by listening to the spoken message.
- Check Twilio's logs in your console to debug any issues that might arise.
flask run