TwiML™ for Programmable Voice
TwiMLとは何か
TwiML (the Twilio Markup Language) is a set of instructions you can use to tell Twilio what to do when you receive an incoming call, SMS, or fax.
How TwiML works
When someone makes a call to one of your Twilio numbers, Twilio looks up the URL associated with that phone number and sends it a request. Twilio then reads the TwiML instructions hosted at that URL to determine what to do, whether it's recording the call, playing a message for the caller, or prompting the caller to press digits on their keypad.
At its core, TwiML is an XML document with special tags defined by Twilio to help you build your Programmable Voice application.
Not making phone calls? TwiML powers more than just Twilio Programmable Voice – check out the documentation on how to use TwiML with Programmable SMS and Programmable Fax.
The following will say "Hello, world!" when someone dials a Twilio number configured with this TwiML:
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Hello, world!</Say> </Response>
You can always return raw TwiML from your language of choice, or leverage the Twilio helper libraries to automatically create valid TwiML for you. In the code sample below, toggle to your preferred web programming language to see how the above TwiML looks using the helper library.
Check out our short tutorial on responding to incoming phone calls, available in our six supported helper library languages. You can also leverage Twilio's TwiML bins, our serverless solution that lets you write TwiML that Twilio will host for you so you can quickly prototype a solution without spinning up a web server.
Outbound calls (calls from a Twilio number to an outside number) are controlled using TwiML in the same manner. When you initiate an outbound call with the Twilio API, Twilio then requests your TwiML to learn how to handle the call.
Twilio executes just one TwiML document to the caller at a time, but many TwiML documents can be linked together to build complex interactive voice applications.
TwiML elements
In TwiML parlance, XML elements are divided into three groups: the root <Response>
element, verbs, and nouns.
TwiML elements (verbs and nouns) have case-sensitive names. For example, using <say>
instead of <Say>
will result in an error. Attribute names are also case sensitive and camelCased.
You can use XML comments freely in your TwiML; the interpreter ignores them.
<Response>
要素
In any TwiML response to a Twilio request, you must nest all verb elements within <Response>
, the root element of Twilio's XML markup:
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say> This message must be nested in a Response element in order for Twilio to say it to your caller. </Say> </Response>
他のいかなる構造も無効とみなされます。
TwiML verbs for Programmable Voice
TwiML verbs tell Twilio what actions to take on a given call. Because of this, most elements in a TwiML document are TwiML verbs. Verb names are case sensitive, as are their attribute names.
You can use different combinations of TwiML verbs to create all kinds of interactive voice applications. The core TwiML verbs for Programmable Voice are:
- <Say> - Read text to the caller
- <Play> - Play an audio file for the caller
- <Dial> - Add another party to the call
- <Record> - Record the caller's voice
- <Gather> - Collect digits the caller types on their keypad
The following verbs may be used to control the flow of your call:
- <Hangup> - Hang up the call
- <Enqueue> - Add the caller to a queue of callers
- <Leave> - Remove a caller from a queue of callers
- <Pause> - Wait before executing more instructions
- <Redirect> - Redirect call flow to a different TwiML document
- <Refer> - Twilio initiates SIP REFER towards IP communication infrastructure
- <Reject> - Decline an incoming call without being billed
The following nouns provide advanced capabilities:
- <Autopilot> - Build AI-powered Conversational IVR
There are certain situations when the TwiML interpreter may not reach verbs in a TwiML document because control flow has passed to a different document. This usually happens when a verb's action attribute is set.
For example, if a <Say>
verb is followed by a <Redirect>
and then another <Say>
, the 2nd <Say>
is unreachable because <Redirect>
transfers full control of a call to the TwiML at a different URL.
TwiML名詞
A TwiML noun describes the phone numbers and API resources you want to take action on. Effectively, a TwiML noun is anything nested inside a verb that is not itself a verb: it's whatever the verb is acting on.
TwiML nouns are usually just text. However, as in the case of <Dial>
with its <Number>
and <Conference>
nouns, at times there are nested XML elements that are nouns.
開発者のアプリケーションへのTwilioからのリクエスト
When someone makes an inbound call to one of your Twilio phone numbers, Twilio needs to request TwiML from your application to get instructions for handling the call.
You can configure your Twilio phone number to point to your application's URL by visiting the phone numbers section of the console. Select your phone number, then scroll to the 'Voice & Fax' section to set a webhook, TwiML bin, or Twilio Function for Twilio to send that HTTP request when a call comes in:
Twilio makes its request over HTTP, either as a GET
or POST
, just like requesting a web page in your browser or submitting a form.
TwilioはPOSTリクエストをキャッシュできません。 Twilioに静的なTwiMLページをキャッシュさせたい場合は、GETを使用してTwilioからリクエストを送信させるようにしてください。
By including parameters and values in its request, Twilio sends data to your application that you can act upon before responding.
リクエストパラメーター
Twilio always sends the following parameters with its request.
These will send as either POST
parameters or URL query parameters, depending on which HTTP method you've configured.
パラメーター | 概要 |
---|---|
CallSid | Twilio が生成したこの通話のユニークな識別子です。 |
AccountSid | あなたの Twilio アカウント ID。AC から始まる 34 文字の文字列です。 |
From |
通話を開始する側、つまり発信者の電話番号またはクライアント識別子です。 Phone numbers are formatted with a '+' and country code, e.g. |
To |
発信先の電話番号またはクライアント識別子です。 電話番号は「+」記号に続き国コードが続く形式で指定します。 Phone numbers are formatted with a '+' and country code, e.g. |
CallStatus |
通話に対する記述ステータスです。 The value is one of the following: |
ApiVersion |
この通話の際使用されたTwilioのAPIバージョン For incoming calls, this is determined by the API version set on the called number. For outgoing calls, this is the version used by the REST API request from the outgoing call. |
Direction |
A string describing the direction of the call:
|
ForwardedFrom |
This parameter is set only when Twilio receives a forwarded call, but its value depends on the caller's carrier including information when forwarding. Not all carriers support passing this information. |
CallerName | This parameter is set when the IncomingPhoneNumber that received the call has had its VoiceCallerIdLookup value set to true ($0.01 per lookup). |
ParentCallSid |
このレグを生成した通話の一意な識別子です。 通話の最初のレグにはこのパラメーターは渡されません。 |
Twilio also attempts to look up geographic data based on the To and From phone numbers. If available, Twilio will send the following parameters with its request:
パラメーター | 概要 |
---|---|
FromCity | The city of the caller |
FromState | The state or province of the caller |
FromZip | The postal code of the caller |
FromCountry | The country of the caller |
ToCity | The city of the called party |
ToState | The state or province of the called party |
ToZip | The postal code of the called party |
ToCountry | The country of the called party |
通話中に起こったことに応じて、他の変数も送信されることがあります。
For example, when Twilio receives SIP, it will send additional parameters to your web application: you'll find the list of parameters sent with SIP in "SIP and TwiML interaction".
CallStatus 値
The following are the possible values for the CallStatus parameter. These values also apply to the DialCallStatus parameter, which is sent with HTTP requests to a <Dial>
action URL.
Status | 概要 |
---|---|
queued | 通話は発信待ち状態です。 |
ringing | 呼び出し中です。 |
in-progress | The call was answered and is actively in progress. |
completed | 相手が応答し、通話が正常に終了しました。 |
busy | 相手からビジー信号を受信しました。 |
failed | 通話を接続できませんでした。通常は、ダイヤルした電話番号が存在しません。 |
no-answer | 相手が応答せず、通話が終了しました。 |
canceled | 通話がqueued(発信待機中)またはringing(呼び出し中)の間に、REST APIによってキャンセルされました。 |
Ending the call: callback requests
After receiving a call, requesting TwiML from your app, processing it, and finally ending the call, Twilio will make an asynchronous HTTP request to the StatusCallback URL configured for the Twilio number that was called.
You need to explicitly provide this URL to your application in the StatusCallback parameter of each message for which you want the status callbacks. The raw TwiML for this looks like:
<?xml version="1.0" encoding="UTF-8"?> <Response> <Dial> <Number statusCallbackEvent="initiated ringing answered completed" statusCallback="https://myapp.com/calls/events" statusCallbackMethod="POST"> +12316851234 </Number> </Dial> </Response>
The code sample below shows how to set your StatusCallback URL with plain TwiML or using the helper library of your choice:
By providing a StatusCallback URL for your Twilio number and capturing this request, you can determine when a call ends and receive information about the call. Please note that non-relative URLs must contain a valid hostname, and underscores are not permitted.
StatusCallback request parameters
When Twilio sends parameters to your application in an asynchronous request to the StatusCallback URL, they include the same parameters passed in a synchronous TwiML request.
この他にも、StatusCallback リクエストは次のパラメーターを渡します。
パラメーター | 概要 |
---|---|
CallDuration | 通話の秒数 |
RecordingUrl | 通話中に録音された音声ファイルの URL です。 このパラメーターは、REST API リクエストで Record=true を設定した場合のみ使用され、<Dial> または <Record> で録音した場合には使用されません。 |
RecordingSid | この通話の Recording のユニーク ID です。 |
RecordingDuration | 録音された音声ファイルの長さ (秒) です。 |
データフォーマット
電話番号
All phone numbers in requests from Twilio are in E.164 format if possible. For example, (231) 685-1234 would come through as '+12316851234'. However, there are occasionally cases where Twilio cannot normalize an incoming caller ID to E.164. In these situations, Twilio will report the raw caller ID string.
日付と時間
Twilio からのリクエストに含まれるすべての日付と時刻には、 RFC 2822 フォーマットの GMT 時間が使用されます。 たとえば、2010 年 8 月 19 日午後 6 時 13 分 (太平洋夏時間) は、「Fri, 20 Aug 2010 01:13:42 +0000」となります。
Twilioはお行儀のよいHTTPクライアントです
URL へ HTTP リクエストを送信する際、Twilio は通常のウェブ ブラウザと同じように振る舞います。
- Cookie: 通常のWebブラウザーと同様、TwilioはHTTP Cookieを受け入れ、これらを (Twilioからの) 各リクエストに追加します。
- Redirects: Twilio follows HTTP Redirects (HTTP status codes 301, 307, etc.), just like a normal web browser. Twilio supports a maximum of 10 redirects before failing the request with error code 11215.
- キャッシュ: こちらも通常のWebブラウザーと同様、HTTPヘッダーで許可されており (ETagおよびLast-Modifiedヘッダー) 、かつHTTPメソッドがGETである場合、Twilioはファイルのキャッシュを行います。
MIME Type に対応
Twilio はユーザー アプリケーションのレスポンスの MIME Type に応じて異なる動作をします。
MIME Type | 動作 |
---|---|
text/xml, application/xml, text/html | Twilioは返されたドキュメントをXMLの命令セットとして解釈します (これをTwiMLと呼んでいます) 。これは最もよく使われるレスポンスです。 |
various audio types | Twilio plays the audio file to the caller, and then hangs up. See the <Play> documentation for supported MIME types. |
text/plain | Twilio は発信者に向けてテキストの内容を読み上げ、通話を終了します。 |
Twilioにレスポンスを返す
In your response to Twilio's request to your configured URL, you can tell Twilio what to do on a call.
How the TwiML interpreter works
When your application responds to a Twilio request with XML, Twilio runs your document through the TwiML interpreter. To keep things simple, the TwiML interpreter only understands the few specially-named XML elements that make up TwiML: <Response>
, verbs, and nouns.
The interpreter starts at the top of your TwiML document and executes instructions (verbs) in order from top to bottom.
The following code snippet reads "Hello World" to the caller before playing Cowbell.mp3 for the caller and then hanging up.
<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Hello, World!</Say> <Play>https://api.twilio.com/Cowbell.mp3</Play> </Response>
Just as with all TwiML, you can use the helper libraries to help you play some music to a caller. Include the loop
attribute to tell Twilio to loop this recording 10 times (or until the caller hangs up):
Status callbacks in your response
ステータス・コールバックは通話フローを制御しないため、TwiMLを返す必要はありません。 レスポンスを返す際は、ステータスコード 204 No Content または、Content-Type: text/xmlおよび空の <Response/>
のBodyをともなった 200 OK を使用してください。 正しくレスポンスを返さないと、デバッガーで警告が発生します。
関連トピック
Go in-depth to learn more about the various TwiML verbs you'll use with Twilio's Programmable Voice, such as <Dial> to connect a call or <Gather> for speech recognition and collecting user key presses. You'll find all in-depth reference documents linked above.
You may also wish to explore how to generate TwiML with Twilio's helper libraries, provided to let you generate TwiML in your favorite language.
For a guided walkthrough, check out our quickstarts that will show you how to make and receive phone calls with Twilio in C#/.NET, Java, Node.js, PHP, Python, or Ruby.
ヘルプが必要ですか?
誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。