Twilio AutopilotからAWS API Gatewayをコールしてみました。
やること
電話に話しかけるとTwilioがAPI Gateway経由でサーバの起動停止をするLambdaを呼び出す仕組みをつくってみます。
注)認証的なものは入れてません。
必要なもの
- twilioアカウント
- AWSアカウント
手順概要
- [AWS] lambdaを作成する
- [AWS] apiを作成する
- [Twilio] virtual assistantを作成する
- [Twilio] taskを作成する
- [Twilio] sampleを作成して、modelをビルドする
- [Twilio] 電話番号にvirtual assistantを紐づける
- [Twilio] テストする
1. [AWS] lambdaを作成する
import boto3
import json
INSTANCE_ID = 'I-*****************'
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
command = get_command(event)
reply = ''
if command == 'start':
res = ec2.start_instances(
InstanceIds=[INSTANCE_ID]
)
reply = 'The server is starting.'
elif command == 'stop':
res = ec2.stop_instances(
InstanceIds=[INSTANCE_ID]
)
reply = 'The server is stopping'
else:
reply = 'Please tell me start or stop.'
body = {
'actions': [
{
'say': reply
}
]
}
return({
'isBase64Encoded': False,
'statusCode': 200,
'headers': {},
'body': json.dumps(body)
})
def get_command(event):
try:
command = event['pathParameters']['command']
except KeyError as err:
command = 'other'
return command
2. [AWS] apiを作成する
API Gatewayでapiを作成してデプロイします。
項目 | 値 |
---|---|
メソッド | POST |
Lambdaプロキシ統合の使用 | ON |
ステージ名 | prod |

3. [Twilio] virtual assistantを作成する
twilioのコンソールから[Autopilot] - [Create a New Assistant]を選択して、virtual assistantを作成します。
4. [Twilio] taskを作成する
initial
{
"actions": [
{
"say": "Do you want to strat a hoge server or stop a hoge server?"
},
{
"listen": true
}
]
}
start
{
"actions": [
{
"redirect": "https://**********.execute-api.us-east-1.amazonaws.com/prod/start"
}
]
}
stop
{
"actions": [
{
"redirect": "https://**********.execute-api.us-east-1.amazonaws.com/prod/stop"
}
]
}
5. [Twilio] sampleを作成して、modelをビルドする



6. [Twilio] 電話番号にvirtual assistantを紐づける
[Channels] - [Programmable Voice]のVOICE URLをコピーします。

下図の赤枠にペーストして、電話番号と紐づけます。

7. [Twilio] テストする
Twilioで購入した電話番号に電話して、「start」か「stop」を指示します。
雑感
その1
発音が悪いのか、stopの方しか認識してくれませんでした。早く日本語に対応しないかな。。
その2
最近のtwilioはSendGridを買収したりと電話の枠を超えてコミュニケーション分野全体に手を広げているように見えます。そのうちSlackやFacebookを飲み込んだりして。。。