This document is a content to learn Twilio, which is a communication API, using Python.
The content consists of the following five.
--Lesson 1. Try to make a call using RestAPI --Lesson 2 Play the original message --Lesson 3. Try using your browser as a phone --Lesson 4. Send voice-recognized content by SMS --Lesson 5. Sending and receiving faxes
For an overview of Twilio, please visit: https://twilio.kddi-web.com
Python
Since Python 3.x will be used this time, please prepare the execution environment (working folder) of Python 3. To find out the Python version, use the following command.
$ python --version
Python 3.7.2
Since pip is used to install the library, please make sure that pip can be used together with Python. https://pip.pypa.io/en/stable/installing/
ngrok
To use Twilio, you need a public server that you can access from Twilio. This time, we will not build a server, but use ngrok to make the local environment accessible from the outside. Download ngrok from the following site and extract it. https://ngrok.com/
Twilio
If you don't have a Twilio account, get a trial account first. Please refer to this article for how to sign up for free. [Latest version] Twilio sign-up
You can only purchase one phone number with your trial account. In addition, only the authenticated phone number used when signing up can be used as the destination. If you want to call any phone number or purchase multiple phone numbers, please register your payment information (card information) and purchase points.
In this lesson, you'll first purchase one phone number using Twilio's admin console. Then install the Python helper library and write the code to make the call. Currently, in order to purchase a Japanese phone number, you need to register your address information in advance. Please refer to the following article for how to register your address information. How to register your address on your phone number on Twilio
Log in to Twilio's admin console. https://jp.twilio.com/login/kddi-web
Click the button icon to open the slide menu and select Phone Number.
Select Buy a Number to open the screen for purchasing a phone number.
Make sure that "Japan (+81)" is selected for the country, check "Voice call" and "Fax", and press the search button.
Select one from the displayed list and press the "Purchase" button.
When the Buy This Number dialog appears, press the Buy This Number button.
When the Congratulations dialog appears, the number purchase is complete. Click the "Close" button to close the dialog.
Twilio has a helper library for Python, so install it first.
$ pip install twilio
The latest version as of 9/24/2019 is 6.31.0. If a lower version is installed, install it with the -U option. The latest version can be found at the following site. https://github.com/twilio/twilio-python/
Log in to Twilio's admin console. https://jp.twilio.com/login/kddi-web
Copy the ACCOUNT SID and AUTH TOKEN values displayed in the Account Summary of the Console Dashboard to Notepad.
from twilio.rest import Client
account_sid = "ACxxxxxxxxx" # Your Account SID from www.twilio.com/console
auth_token = "xxxxxxxx" # Your Auth Token from www.twilio.com/console
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+81xxxxxxx",
from_="+81xxxxxxx",
url="http://demo.twilio.com/docs/voice.xml"
)
print(call.sid)
$ python call.py
Let's check the code above. To make a call, call calls.create. In this, the source (from_) [* from cannot be used as a reserved word, so it becomes from_ *] and the destination (to) are specified. The point is the part specified by url. Here you specify the XML (called TwiML) that tells you what to do when the other person responds. The TwiML specified this time is an XML file as shown below.
<Response>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>
<Play>http://demo.twilio.com/docs/classic.mp3</Play>
</Response>
The
In this lesson, you will try to send your own original message. To do this, you'll need to create a TwiML with the message you want to stream and place it in a location that Twilio can access via http or https. There is a document at the following URL about what kind of TwiML is available. https://jp.twilio.com/docs/api/twiml
In order to make it accessible from Twilio, we will use Flask as a web framework this time. You can install Flask by following the steps below.
$ pip install Flask
# say.py
from flask import Flask
from twilio.twiml.voice_response import VoiceResponse
app = Flask(__name__)
@app.route('/say', methods=['GET', 'POST'])
def say():
#Create TwiML
resp = VoiceResponse()
resp.say("Hello. Twirio is a lot of fun.", language="ja-JP", voice="alice")
return str(resp)
if __name__ == "__main__":
app.run(port=5000, debug=True)
$ python say.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 219-682-997
Use ngrok to publish the created Python program to the outside.
$ ngrok http 5000
from twilio.rest import Client
account_sid = "ACxxxxxxxxxxx" # Your Account SID from www.twilio.com/console
auth_token = "xxxxxxxxxxxx" # Your Auth Token from www.twilio.com/console
client = Client(account_sid, auth_token)
call = client.calls.create(
to="+81xxxxxxxxxx",
from_="+8150xxxxxxxx",
url="https://xxxxxxx.ngrok.io/say"
)
print(call.sid)
$ python call.py
Say.py is creating the original TwiML. Twilio's Python helper library makes it easy to create TwiML as well. To create a Voice-based TwiML, import twilio.twiml.voice_response in advance. To speak Japanese, specify language ='ja-JP' and voice ='alice'. If you write a sentence that is too long, it may not be uttered correctly. In such a case, divide the Say verb into multiple parts. Also, with this sample, I feel that Japanese is terrifying. If you want to speak fluent Japanese, use "Polly.Mizuki" or "Polly.Takumi" for the voice parameter in the part that generates TwiML (see the code below) and speak in relatively clean Japanese. Will do it. It costs a little money, but if you want to use beautiful Japanese, please try it.
~ Abbreviation ~
def say():
#Create TwiML
resp = VoiceResponse()
resp.say("Hello. Twirio is a lot of fun.", language="ja-JP", voice="Polly.Mizuki")
return str(resp)
~ Abbreviation ~
In addition to this, for example, AI's voice synthesis technology can be combined.
--AI Co., Ltd. "AITalk"
You may not know what you're talking about, but Twilio allows you to use your usual browser as your phone. Yes, you can call with your browser. In this lesson, you will use your browser as a phone and try to make a call through your browser. Sending and receiving via a browser uses a function called Twilio Client, but a mechanism called an access token is required for sending and receiving. An access token is an authentication key that allows you to use Twilio to use phone functions, and can be obtained by requesting Twilio to issue an access token from the user side. It takes time to create these mechanisms from scratch, so this time we will use the quick start prepared in advance. This lesson will use ngrok as before.
If you can use Git, use the following command to clone the source file to your working directory.
$ git clone https://github.com/TwilioDevEd/client-quickstart-python.git
If you can't use Git, download the Zip file from the URL below and extract it to your working directory. https://github.com/TwilioDevEd/client-quickstart-python/archive/master.zip
Change to the cloned (extracted) directory.
$ cd client-quickstart-python
Create an .env file by copying the sample .env file.
$ cp .env.example .env
For Windows users
$ cp .env.example.ps1 .env.ps1
Open .env or .env.ps1 with an editor and set environment variables.
.env
export TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
export TWILIO_AUTH_TOKEN=your_auth_token
export TWILIO_TWIML_APP_SID=APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
export TWILIO_CALLER_ID=+1XXXYYYZZZZ
For TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN, enter the AccountSit and AuthToken used in the previous lesson. I don't know TWILIO_TWIML_APP_SID yet at this point, so leave it alone. In TWILIO_CALLER_ID, write the purchased 050 number in E.164 format. After completing the settings, save it by overwriting.
Set the environment variables with the following command.
$ source .env
For Windows users, use the following command to set.
. .\.env.ps1
Use the following command to load the required library.
$ pip install -r requirements.txt
The libraries used this time are Flask, twilio, and fake-factory.
$ ngrok http 5000
When ngrok starts, record the displayed URL (https) in Notepad.
Select the TwiML Apps you created again and make a note of the Application SID.
Post the written Application SID to TWILIO_TWIML_APP_SID in the .env you just edited.
Close the running application (app.py) once (Ctrl-C).
Reload the environment variables.
$ source .env
$ python app.py
If you see Twilio Device Ready! As shown on the screen, you can make a call. When making a call, specify the phone number in E.164 format.
Open app.py in an editor and check it. There are two large codes in it, one to get an access token called / token and the other to make a call called / voice. In / token, ClientCapbilityToken object is created and allow_client_outgoing (application_sid) and allow_client_incoming (identity) are set. The former is the setting for outgoing tokens, and the latter is the setting for incoming calls. The outgoing token specifies the TwiML Apps SID, which allows Twilio to call / voice when the browser gives you an instruction to make a call. In addition, the token for incoming calls sets its own identity, which enables other clients to specify the identity as the destination to receive a call. / voice is the URL that Twilio calls when you make a call, and the destination number is passed as a To parameter. By returning this as a Dial verb, Twilio will call you. This time, the incoming call with 050 number is not implemented, but if you want to implement it, use Twilio's management console to specify the incoming call processing of 050 number, and use TwiML for the Dial verb destined for identity. It's OK if you return it. The code on the front end side can be found in quickstart.js in the static folder. When the page loads, you'll see that you're using ajax to get an access token. If the token acquisition is successful, the Device will be initialized using the acquired token. When the initialization is complete, the Device.ready event is fired. In addition to ready, Device has some important events. These events are described in the following documents: https://jp.twilio.com/docs/api/client/device
In this lesson, you'll combine Twilio's voice recognition and SMS sending technologies to create a program that, when you receive an incoming call to your 050 number, records your voice and converts it into text and returns it to the caller via SMS. You cannot use the 050 number to send SMS, so purchase a new US number. ** You'll need to upgrade your Twilio trial account. ** **
# app.py
from flask import Flask, request, Response
from twilio.rest import Client
from twilio.twiml.voice_response import Gather, VoiceResponse, Say
app = Flask(__name__)
account_sid = "ACxxxxxxxxxxxxxxxxxxxxxx"
auth_token = "xxxxxxxxxxxxxxxxxxxxxxx"
client = Client(account_sid, auth_token)
@app.route('/calling', methods=['GET', 'POST'])
def calling():
#WebHook called when a call arrives
response = VoiceResponse()
gather = Gather(input='speech', language='ja-JP', action='/sendsms', method='POST')
gather.say('Thank you for calling. Please give me a message.', language='ja-JP', voice='alice')
response.append(gather)
return str(response)
@app.route('/sendsms', methods=['POST'])
def sendsms():
#Get voice recognition results
result = request.form["SpeechResult"] or ''
to = request.form["From"] or ''
if (result != '' and to != ''):
#Send SMS
message = client.messages.create(to=to,
from_="+1XXXXXXXXXXXX",
body=result)
print(message.sid)
resp = VoiceResponse()
resp.say("I have sent you a message. Thank you very much.", language="ja-JP", voice="alice")
return str(resp)
else:
resp = VoiceResponse()
resp.say("I'm sorry. Voice recognition was not possible.", language="ja-JP", voice="alice")
return str(resp)
if __name__ == "__main__":
app.run(port=5000, debug=True)
$ python app.py
$ ngrok http 5000
When ngrok starts, record the URL starting with https.
The Gather verb generated by calling is originally a verb for processing DTMF signals (push tone signals), but it is also possible to acquire voice data in addition to DTMF. The voice data is internally passed to the voice recognition engine, and the result is sent to the webhook specified by the action parameter. Voice can be recorded for up to 60 seconds, and an additional charge of 3 yen will be incurred for each conversion (15 seconds unit) in addition to the call charge. This time, we sent the SMS as it was after voice recognition, but it is also possible to create a BOT using voice by using, for example, IBM Watson's conversation API.
In this lesson, you will use the Programmable Fax feature to send and receive faxes. From a global perspective, Japan is still a country where faxes are still heavily used, and there are many possible ways to use them, such as sending faxes from programs and automatically processing received faxes. You can use the 050 number to send and receive faxes, but you cannot receive voice calls or faxes with the same 050 number. This time, I will switch the already purchased 050 number for fax and use it.
$ git clone https://github.com/twilioforkwc/simpleFAX.git
$ cd simpleFAX
$ mv example.env .env
$ source .env
$ python app.py
$ ngrok http 3000
Make a note of the URL of the started https.
Example: https://xxxxxx.ngrok.io/sendfax?to=03XXXXXXXX&pdf=xxxxxx.pdf
The app.py is large and contains two codes, one for sending (sendfax) and one for receiving (receive, actionReceiver).
The sendfax for sending contains the code to send a fax using the Rest API. At the moment, the helper library for Python does not support fax, so it is realized by using the requests library.
To determine whether the transmission was successful, it is necessary to specify statusCallback in the RestAPI at the time of transmission, or to call the RestAPI using the FAX SID included in the return value of the RestAPI at the time of transmission, but this process is omitted in this program. doing.
Receive for receive is the first webhook to be called when a fax arrives at your Twilio number. Here you need to return either the
More documentation on Programmable Fax can be found below. https://jp.twilio.com/docs/api/fax
This time we introduced the case of using Python, but in addition to Python, we also have SDKs for languages such as Node.js, C #, Java, Ruby, PHP, Salesforce. For more information, please see here.
https://twilio.kddi-web.com Twilio is a cloud API service that allows you to easily incorporate various communication methods such as voice calls, messaging (SMS / chat), and video into your applications and businesses. It is a pay-as-you-go system that does not require an initial cost and is compatible with various development languages, so it is also used for many hackathon events and startups.
Recommended Posts