Skip to content

Simple Run Speech Menu

Note

 This sample is no longer supported in Version 1 REST API. A new implementation of this sample is supported in Version 2 of the REST API.

A simple application that presents an audio menu to an answered inbound or outbound call.

Options 1 and 2 direct to a page that reads out a weather report for the selected country (Belgium or Venezuala). Option 3 directs to a page that read out a weather report for Outer Mongolia. Each page then returns to the menu page.

If no selection or an invalid selection is made the caller is prompted to re-select. After several attempts the caller will be played an audio file (oneMoreTime.wav) prompting for a final go.

This application requires the wav file oneMoreTime.wav to be available in the cloud media store.

Uses actions:

Run Speech Menu, Play, Redirect

{
    "actions" :
    [
        {
            "run_speech_menu":
            {
                "prompt" :
                {
                    "play" :
                    {
                        "play_list" :
                        [
                            {
                                "text_to_say" : "Say the country for which you want a weather report,
                                                      Belgium, Venezuela or Outer Mongolia.
                                                      Or press 1 for Belgium,
                                                      2 for Venezuela,
                                                      3 for Outer Mongolia.
                                                      Or press 5 to listen to the options again."
                            }
                        ]
                    }
                },
                "menu_options" :
                [
                    {
                        "speech" : "belgium",
                        "digit" : "1",
                        "next_page" :
                        {
                            "url" : "WeatherReport"
                        }
                    },
                    {
                        "speech" : "venezuela",
                        "digit" : "2",
                        "next_page" :
                        {
                            "url" : "WeatherReport"
                        }
                    },
                    {
                        "speech" : "outer mongolia",
                        "digit" : "3",
                        "next_page" :
                        {
                            "url" : "WeatherInOuterMongolia"
                        }
                    }
                ],
                "help_digit" : "5",
                "help_word" : "help",
                "on_digit_timeout_messages":
                [
                    {
                        "play" :
                        {
                            "play_list" :
                            [
                                {
                                    "text_to_say" : "I didn't catch your entry."
                                }
                            ]
                        }
                    },
                    {
                        "play" :
                        {
                            "play_list" :
                            [
                                {
                                    "text_to_say" : "Please select a country."
                                }
                            ]
                        }
                    },
                    {
                        "play" :
                        {
                            "play_list" :
                            [
                                {
                                    "file_to_play" : "oneMoreTime.wav"
                                }
                            ]
                        }
                    }
                ],
                "on_invalid_digit_messages" :
                [
                    {
                        "play" :
                        {
                            "play_list" :
                            [
                                {
                                    "text_to_say" : "That wasn't one of the options. Please try again."
                                }
                            ]
                        }
                    },
                    {
                        "play" :
                        {
                            "play_list" :
                            [
                                {
                                    "file_to_play" : "oneMoreTime.wav"
                                }
                            ]
                        }
                    }
                ]
            }
        }
    ],
    "token" : "my run speech menu instance id"
}
{
    "actions" :
    [
        {
            "play" :
            {
                "play_list" :
                [
                    {
                        "text_to_say" : "The weather for Belgium is quite often good but sometimes is appalling."
                    }
                ]
            }
        },
        {
            "redirect" :
            {
                "next_page" :
                {
                    "url" : "SimpleRunSpeechMenu"
                }
            }
        }
    ]
}
{
    "actions" :
    [
        {
            "play" :
            {
                "play_list" :
                [
                    {
                        "text_to_say" : "The weather for Venezuela is dry from about November to May
                                         and considerably wetter for the rest of the year. It is close
                                         to the equator, so average temperatures below 1000 metres are
                                         between 70 and 85 degrees fahrenheit in most places."
                    }
                ]
            }
        },
        {
            "redirect" :
            {
                "next_page" :
                {
                    "url" : "SimpleRunSpeechMenu"
                }
            }
        }
    ]
}
{
    "actions" :
    [
        {
            "play" :
            {
                "play_list" :
                [
                    {
                        "text_to_say" : "The weather in Outer Mongolia is just right for outer mongolians."
                    }
                ]
            }
        },
        {
            "redirect" :
            {
                "next_page" :
                {
                    "url" : "SimpleRunSpeechMenu"
                }
            }
        }
    ]
}
{
    [
    ],
    "token" : "Error for Action: xxxx  ActionIndex: xxxx  Result: xxxx"
}
{
}

Implemented as ASP.Net Web Forms:

using System;
using System.Collections.Generic;
using RestAPIWrapper;

public partial class SimpleRunSpeechMenu : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(Request);
        if (!ourRequest.IsValid)
        {
            return;
        }

        // Setup the actions
        List<TelephonyAction> actions = new List<TelephonyAction>();

        // Create the menu action
        Play menuPrompt = Play.SayText("Say the country for which you want a weather report, " +
                                       "Belgium, Venezuela or Outer Mongolia. " +
                                       "Or press 1 for Belgium, " +
                                       "2 for Venezuela, " +
                                       "3 for Outer Mongolia. " +
                                       "Or press 5 to listen to the options again.");
        List<SpeechMenuOption> menuOptions = new List<SpeechMenuOption>();
        menuOptions.Add(new SpeechMenuOption("belgium", '1', new WebPageRequest("WeatherReport.aspx")));
        menuOptions.Add(new SpeechMenuOption("venezuela", '2', new WebPageRequest("WeatherReport.aspx")));
        menuOptions.Add(new SpeechMenuOption("outer mongolia", '3', new WebPageRequest("WeatherInOuterMongolia.aspx")));
        RunSpeechMenu runSpeechMenuAction = new RunSpeechMenu(menuPrompt, menuOptions);
        runSpeechMenuAction.HelpDigit = '5';
        runSpeechMenuAction.HelpWord = "help";

        // Set up some new info messages for no entry and invalid entry
        runSpeechMenuAction.OnInputTimeoutMessages = new List<Play>();
        runSpeechMenuAction.OnInputTimeoutMessages.Add(Play.SayText("I didn't catch your entry."));
        runSpeechMenuAction.OnInputTimeoutMessages.Add(Play.SayText("Please select a country."));
        runSpeechMenuAction.OnInputTimeoutMessages.Add(Play.PlayFile("oneMoreTime.wav"));
        runSpeechMenuAction.OnInvalidInputMessages = new List<Play>();
        runSpeechMenuAction.OnInvalidInputMessages.Add(Play.SayText("That wasn't one of the options. Please try again."));
        runSpeechMenuAction.OnInvalidInputMessages.Add(Play.PlayFile("oneMoreTime.wav"));

        actions.Add(runSpeechMenuAction);

        // Respond
        String token = "my run speech menu instance id";
        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
        ourResponse.ToHttpResponse(Response);
    }
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;

public partial class WeatherReport : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(Request);
        if (!ourRequest.IsValid)
        {
            return;
        }
        String token = ourRequest.InstanceInfo.Token;

        // Get the result of the run_menu or run_speech_menu action
        char selectedDigit;
        String nextPage;
        ActionResult actionResult = ourRequest.InstanceInfo.ActionResult;
        if (actionResult.Action.Equals("run_menu"))
        {
            selectedDigit = ((RunMenuResult)actionResult).SelectedDigit;
            nextPage = "SimpleRunMenu.aspx";
        }
        else
        {
            selectedDigit = ((RunSpeechMenuResult)actionResult).SelectedDigit;
            nextPage = "SimpleRunSpeechMenu.aspx";
        }

        // Setup the actions
        List<TelephonyAction> actions = new List<TelephonyAction>();
        Play playAction = new Play();
        switch (selectedDigit)
        {
            case '1':
                playAction.AddText("The weather for Belgium is quite often good but sometimes is appalling.");
                break;
            case '2':
                playAction.AddText("The weather for Venezuela is dry from about November to May " +
                                   "and considerably wetter for the rest of the year. " +
                                   "It is close to the equator, so average temperatures below 1000 metres " +
                                   "are between 70 and 85 degrees fahrenheit in most places.");
                break;
        }
        actions.Add(playAction);
        actions.Add(new Redirect(new WebPageRequest(nextPage)));

        // Respond
        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
        ourResponse.ToHttpResponse(Response);
    }
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;

public partial class WeatherInOuterMongolia : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(Request);
        if (!ourRequest.IsValid)
        {
            return;
        }
        String token = ourRequest.InstanceInfo.Token;

        // Did we get here as the result of the run_menu or run_speech_menu action?
        String nextPage;
        ActionResult actionResult = ourRequest.InstanceInfo.ActionResult;
        if (actionResult.Action.Equals("run_menu"))
        {
            nextPage = "SimpleRunMenu.aspx";
        }
        else
        {
            nextPage = "SimpleRunSpeechMenu.aspx";
        }

        // Setup the actions
        List<TelephonyAction> actions = new List<TelephonyAction>();
        actions.Add(Play.SayText("The weather in Outer Mongolia is just right for outer mongolians."));
        actions.Add(new Redirect(new WebPageRequest(nextPage)));

        // Respond
        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
        ourResponse.ToHttpResponse(Response);
    }
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;

public partial class ErrorPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(Request);
        if (!ourRequest.IsValid)
        {
            return;
        }
        ErrorResult result = ourRequest.InstanceInfo.ErrorResult;

        String token = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}",
            result.Action, result.ActionIndex, result.Result);

        // Respond
        TelephonyResponse ourResponse = new TelephonyResponse(null, token);
        ourResponse.ToHttpResponse(Response);
    }
}
using System;
using System.Collections.Generic;
using RestAPIWrapper;

public partial class FinalPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(Request);
        if (!ourRequest.IsValid)
        {
            return;
        }
    }
}

Implemented as ASP.Net Web Forms:

Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper

Partial Class SimpleRunSpeechMenu
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Unpack the request
        Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
        If Not ourRequest.IsValid Then
            Return
        End If

        ' Setup the actions
        Dim actions As List(Of TelephonyAction) = New List(Of TelephonyAction)

        ' Create the menu action
        Dim menuPrompt As Play = Play.SayText("Say the country for which you want a weather report, " +
                                       "Belgium, Venezuela or Outer Mongolia. " +
                                       "Or press 1 for Belgium, " +
                                       "2 for Venezuela, " +
                                       "3 for Outer Mongolia. " +
                                       "Or press 5 to listen to the options again.");
        Dim menuOptions As List(Of SpeechMenuOption) = New List(Of SpeechMenuOption)
        menuOptions.Add(New SpeechMenuOption("belgium", "1", New WebPageRequest("WeatherReport.aspx")))
        menuOptions.Add(New SpeechMenuOption("venezuela", "2", New WebPageRequest("WeatherReport.aspx")))
        menuOptions.Add(New SpeechMenuOption("outer mongolia", "3", New WebPageRequest("WeatherInOuterMongolia.aspx")))
        Dim runSpeechMenuAction As RunSpeechMenu = New RunSpeechMenu(menuPrompt, menuOptions)
        runSpeechMenuAction.HelpDigit = "5"
        runSpeechMenuAction.HelpWord = "Help"

        ' Set up some new info messages for no entry and invalid entry
        runSpeechMenuAction.OnInputTimeoutMessages = New List(Of Play)
        runSpeechMenuAction.OnInputTimeoutMessages.Add(Play.SayText("I didn't catch your entry."))
        runSpeechMenuAction.OnInputTimeoutMessages.Add(Play.SayText("Please select a country."))
        runSpeechMenuAction.OnInputTimeoutMessages.Add(Play.PlayFile("oneMoreTime.wav"))
        runSpeechMenuAction.OnInvalidInputMessages = New List(Of Play)
        runSpeechMenuAction.OnInvalidInputMessages.Add(Play.SayText("That wasn't one of the options. Please try again."))
        runSpeechMenuAction.OnInvalidInputMessages.Add(Play.PlayFile("oneMoreTime.wav"))

        actions.Add(runSpeechMenuAction)

        ' Respond
        Dim ourResponse As TelephonyResponse = New TelephonyResponse(actions, "my run speech menu instance id")
        ourResponse.ToHttpResponse(Response)
    End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper

Partial Class WeatherReport
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Unpack the request
        Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
        If Not ourRequest.IsValid Then
            Return
        End If
        Dim token As String = ourRequest.InstanceInfo.Token

        ' Get the result of the run_menu or run_speech_menu action
        Dim selectedDigit As Char
        Dim nextPage As String
        Dim actionResult As ActionResult = ourRequest.InstanceInfo.ActionResult
        If actionResult.Action.Equals("run_menu") then
            selectedDigit = ((RunMenuResult)actionResult).SelectedDigit
            nextPage = "SimpleRunMenu.aspx"
        Else
            selectedDigit = ((RunSpeechMenuResult)actionResult).SelectedDigit
            nextPage = "SimpleRunSpeechMenu.aspx"
        End If

        ' Setup the actions
        Dim actions As List(Of TelephonyAction) = New List(Of TelephonyAction)
        Dim playAction As Play = New Play()
        Select (selection)
            Case "1"
                playAction.AddText("The weather for Belgium is quite often good but sometimes is appalling.")
            Case "2"
                playAction.AddText("The weather for Venezuela is dry from about November to May " + _
                                   "and considerably wetter for the rest of the year. " + _
                                   "It is close to the equator, so average temperatures below 1000 metres " + _
                                   "are between 70 and 85 degrees Fahrenheit in most places.")
        End Select

        actions.Add(playAction)
        actions.Add(New Redirect(New WebPageRequest(nextPage)))

        ' Respond
        Dim ourResponse As TelephonyResponse = New TelephonyResponse(actions, token)
        ourResponse.ToHttpResponse(Response)
    End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper

Partial Class WeatherInOuterMongolia
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Unpack the request
        Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
        If Not ourRequest.IsValid Then
            Return
        End If
        Dim token As String = ourRequest.InstanceInfo.Token

        ' Setup the actions
        Dim actions As List(Of TelephonyAction) = New List(Of TelephonyAction)
        actions.Add(Play.SayText("The weather in Outer Mongolia is just right for Outer Mongolians."))
        actions.Add(New Redirect(New WebPageRequest("SimpleRunMenu.aspx")))

        ' Respond
        Dim ourResponse As TelephonyResponse = New TelephonyResponse(actions, token)
        ourResponse.ToHttpResponse(Response)
    End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper

Partial Class ErrorPage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Unpack the request
        Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
        If Not ourRequest.IsValid Then
            Return
        End If
        Dim result As ErrorResult = ourRequest.InstanceInfo.ErrorResult

        Dim token As String = String.Format("Action: {0}\nActionIndex: {1}\nResult: {2}", _
            result.Action, result.ActionIndex, result.Result)

        ' Respond
        Dim ourResponse As TelephonyResponse = New TelephonyResponse(token)
        ourResponse.ToHttpResponse(Response)
    End Sub
End Class
Imports System
Imports System.Collections.Generic
Imports RestAPIWrapper

Partial Class FinalPage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        ' Unpack the request
        Dim ourRequest As TelephonyRequest = New TelephonyRequest(Request)
        If Not ourRequest.IsValid Then
            Return
        End If
    End Sub
End Class

Implemented as Java Servlets:

package com.aculab.telephonyrestapi.samples;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;

public class SimpleRunSpeechMenu extends HttpServlet
{
    @Override
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    private void handleRequest(HttpServletRequest request,
                               HttpServletResponse response) throws IOException
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(request);
        if (!ourRequest.isValid())
        {
            return;
        }

        // Set up the actions
        List<TelephonyAction> actions = new ArrayList<TelephonyAction>();

        // Create the menu action
        Play menuPrompt = Play.sayText("Say the country for which you want a weather report, " +
                                       "Belgium, Venezuela or Outer Mongolia. " +
                                       "Or press 1 for Belgium, " +
                                       "2 for Venezuela, " +
                                       "3 for Outer Mongolia. " +
                                       "Or press 5 to listen to the options again.");
        List<SpeechMenuOption> options = new ArrayList<SpeechMenuOption>();
        menuOptions.add("belgium", '1', new WebPageRequest("WeatherReport"));
        menuOptions.add("venezuela", '2', new WebPageRequest("WeatherReport"));
        menuOptions.add("outer mongolia", '3', new WebPageRequest("WeatherInOuterMongolia"));
        RunSpeechMenu runSpeechMenuAction = new RunSpeechMenu(menuPrompt, menuOptions);
        runSpeechMenuAction.setHelpDigit('5');
        runSpeechMenuAction.setHelpWord("Help");

        // Set up some new info messages for no entry and invalid entry
        List<Play> onInputTimeoutMessages = new ArrayList<Play>();
        onInputTimeoutMessages.add(Play.sayText("I didn't catch your entry."));
        onInputTimeoutMessages.add(Play.sayText("Please select a country."));
        onInputTimeoutMessages.add(Play.playFile("oneMoreTime.wav"));
        runSpeechMenuAction.setOnInputTimeoutMessages(onInputTimeoutMessages);

        List<Play> onInvalidInputMessages = new ArrayList<Play>();
        onInvalidInputMessages.add(Play.sayText("That wasn't one of the options. Please try again."));
        onInvalidInputMessages.add(Play.playFile("oneMoreTime.wav"));
        runSpeechMenuAction.setOnInvalidInputMessages(onInvalidInputMessages);

        actions.add(runSpeechMenuAction);

        // Respond
        TelephonyResponse ourResponse = new TelephonyResponse(actions, "my run speech menu instance id");
        ourResponse.setHttpServletResponse(response);
    }
}
package com.aculab.telephonyrestapi.samples;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;

public class WeatherReport extends HttpServlet
{
    @Override
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    private void handleRequest(HttpServletRequest request,
                               HttpServletResponse response) throws IOException
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(request);
        if (!ourRequest.isValid())
        {
            return;
        }
        String token = ourRequest.getInstanceInfo().getToken();

        // Get the result of the run_menu or run_speech_menu action
        char selectedDigit;
        String nextPage;
        ActionResult actionResult = ourRequest.getInstanceInfo().getActionResult();
        if (actionResult.getAction().equals("run_menu"))
        {
            selectedDigit = ((RunMenuResult)actionResult).getSelectedDigit();
            nextPage = "SimpleRunMenu";
        }
        else
        {
            selectedDigit = ((RunSpeechMenuResult)actionResult).getSelectedDigit();
            nextPage = "SimpleRunSpeechMenu";
        }

        // Set up the actions
        List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
        Play playAction = new Play();
        switch (selectedDigit)
        {
            case '1':
                playAction.addText("The weather for Belgium is quite often good but sometimes is appalling.");
                break;
            case '2':
                playAction.addText("The weather for Venezuela is dry from about November to May " +
                                   "and considerably wetter for the rest of the year. " +
                                   "It is close to the equator, so average temperatures below 1000 metres " +
                                   "are between 70 and 85 degrees fahrenheit in most places.");
                break;
        }
        actions.add(playAction);
        actions.add(new Redirect(new WebPageRequest(nextPage)));

        // Respond
        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
        ourResponse.setHttpServletResponse(response);
    }
}
package com.aculab.telephonyrestapi.samples;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;

public class WeatherInOuterMongolia extends HttpServlet
{
    @Override
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    private void handleRequest(HttpServletRequest request,
                               HttpServletResponse response) throws IOException
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(request);
        if (!ourRequest.isValid())
        {
            return;
        }
        String token = ourRequest.getInstanceInfo().getToken();

        // Get the result of the run_menu or run_speech_menu action
        String nextPage;
        ActionResult actionResult = ourRequest.getInstanceInfo().getActionResult();
        if (actionResult.getAction().equals("run_menu"))
        {
            nextPage = "SimpleRunMenu";
        }
        else
        {
            nextPage = "SimpleRunSpeechMenu";
        }

        // Set up the actions
        List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
        actions.add(Play.sayText("The weather in Outer Mongolia is just right for outer mongolians."));
        actions.add(new Redirect(new WebPageRequest(nextPage)));

        // Respond
        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
        ourResponse.setHttpServletResponse(response);
    }
}
package com.aculab.telephonyrestapi.samples;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.aculab.telephonyrestapi.*;

public class ErrorPage extends HttpServlet
{
    private static final long serialVersionUID = -4842873371047361437L;

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
                    throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    private void handleRequest(HttpServletRequest request,
                               HttpServletResponse response) throws IOException
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(request);
        if (!ourRequest.isValid())
        {
            return;
        }
        ErrorResult result = ourRequest.getInstanceInfo().getErrorResult();

        String token = String.format("Action: %s\nActionIndex: %d\nResult: %s", result.getAction(), result.getActionIndex(), result.getResult());

        // Respond
        List<TelephonyAction> actions = new ArrayList<TelephonyAction>();
        TelephonyResponse ourResponse = new TelephonyResponse(actions, token);
        ourResponse.setHttpServletResponse(response);
    }
}
package com.aculab.telephonyrestapi.samples;

import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;
import com.aculab.telephonyrestapi.*;

public class FinalPage extends HttpServlet
{
    private static final long serialVersionUID = 5940620014313056844L;

    @Override
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
                    throws IOException, ServletException
    {
        handleRequest(request, response);
    }

    private void handleRequest(HttpServletRequest request,
                               HttpServletResponse response) throws IOException
    {
        // Unpack the request
        TelephonyRequest ourRequest = new TelephonyRequest(request);
        if (!ourRequest.isValid())
        {
            return;
        }
    }
}

Implemented using a wrapper for Python's wsgiref.simple_server.

For the purposes of this sample, the first page is first_page, the final page is final_page and the error page is error_page.

The application base class.

from aculab.telephony_rest_api import Play

class ApplicationBase:

    def __init__(self, exit=None):
        self.exit = exit or [self.exit]


    def exit(self):
        pass


    def error_page(self, my_actions, query_info):
        try:
            error_result = query_info.ErrorResult
            action = error_result.get('action', 'none')
            print("\nError {0} : {1}\n".format(action, error_result['result']))
            my_actions.add(Play(text_to_say='I encountered an error.'))

        except Exception as exc:
            print("Error page exception: {0}".format(exc))
        return True


    def final_page(self, my_actions, query_info):
        try:
            tcall = query_info.ThisCall
            if tcall:
                print("This call ID         : {0}".format(tcall.get('call_id')))
                print("This call duration   : {0}".format(tcall.get('seconds_call_duration')))
            self.exit[0]()
        except Exception as exc:
            print("Final page exception: {0}".format(exc))
        return True


    def unknown_page(self, my_actions, query_info):
        try:
            my_actions.add(Play(text_to_say='I find myself on an unknown page.'))
        except Exception as exc:
            print("Unknown page exception: {0}".format(exc))
        return True

The application code.

import sys, os
sys.path.append(os.path.abspath('../..'))

# import the wrappers for the REST API, these are used to create and send tasks
from aculab.telephony_rest_api import *
from aculab.simple_server import *
from aculab.base_application import ApplicationBase

class Weather:

    BELGIUM   = "The weather for Belgium is quite often good but sometimes is appalling."
    MONGOLIA  = "The weather in Outer Mongolia is just right for outer mongolians."
    VENEZUELA = ("The weather for Venezuela is dry from about November to May "
                 "and considerably wetter for the rest of the year. "
                 "It is close to the equator, so average temperatures below 1000 metres "
                 "are between 70 and 85 degrees fahrenheit in most places.")


class Application(ApplicationBase):

    def __init__(self):
        ApplicationBase.__init__(self)


    def responder(self, query, start_response):

        query_info = RESTQuery(query)
        page = query_info.Page

        my_actions = Actions(token='weather sample')

        # on your inbound service, set the first page entry to point to this page
        # e.g., http://<ip address>:<port>/first_page
        if 'first_page' == page:

            my_menu = RunSpeechMenu()
            # set up the menu
            play_action = Play(text_to_say = ('Say the country for which you want a weather report,'
                                              ' belgium, venezuela or outer mongolia.'
                                              ' Or press 1 for Belgium,'
                                              ' 2 for Venezuela,'
                                              ' 3 for Outer Mongolia.'
                                              ' Or press 5 to listen to the options again.'
                                             ),
                               tts_voice='English US Male Polly Joey'
                              )
            my_menu.on_prompt_play(play_action)
            # set up the dtmf responses
            my_menu.append_menu_option(1, 'beligium', WebPage('choice/belgium'))
            my_menu.append_menu_option(2, 'venezuela', WebPage('choice/venezuela'))
            my_menu.append_menu_option(3, 'outer mongolia', WebPage('choice/mongolia'))
            my_menu.set_help_digit(5)
            # on silence timeout
            my_menu.append_on_digit_timeout_message(Play(text_to_say="Sorry, I didn't catch your entry."))
            my_menu.append_on_digit_timeout_message(Play(text_to_say="Please select a country."))
            my_menu.append_on_digit_timeout_message(Play(file_to_play="oneMoreTime.wav"))
            # on invalid digit
            my_menu.append_on_invalid_digit_message(Play(text_to_say="That wasn't one of the options. Please try again."))
            my_menu.append_on_invalid_digit_message(Play(file_to_play="oneMoreTime.wav"))
            my_actions.add(my_menu)

        elif 'choice/belgium' == page:
            my_actions.add(Play(text_to_say = (Weather.BELGIUM)))
            my_actions.add(Redirect(next_page=WebPage(url='/first_page')))

        elif 'choice/mongolia' == page:
            my_actions.add(Play(text_to_say = (Weather.MONGOLIA)))
            my_actions.add(Redirect(next_page=WebPage(url='/first_page')))

        elif 'choice/venezuela' == page:
            my_actions.add(Play(text_to_say = (Weather.VENEZUELA)))
            my_actions.add(Redirect(next_page=WebPage(url='/first_page')))

        elif 'final_page' == page:
            if self.final_page(my_actions, query_info) is False:
                return None

        elif 'error_page' == page:
            if self.error_page(my_actions, query_info) is False:
                return None

        else:
            if self.unknown_page(my_actions, query_info) is False:
                return None

        response_body = my_actions.get_json()
        response_headers = [('Content-Type', 'application/json; charset=utf-8'), ('Content-Length', str(len(response_body)))]
        start_response('200 OK', response_headers)
        return [response_body]


if __name__ == "__main__":
    application = Application()
    # Set the host and port you want to use in the rest_simple_server.py file.
    # To use SSL also set the key and certificate file.
    ss = SimpleServer(application, simple_server_host, simple_server_port, simple_server_keyfile, simple_server_certfile)
    ss.start()
    print("Hit ctl-break to quit.")
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");

use \Aculab\TelephonyRestAPI\Actions;
use \Aculab\TelephonyRestAPI\Play;
use \Aculab\TelephonyRestAPI\RunSpeechMenu;
use \Aculab\TelephonyRestAPI\MessageList;

$response = new Actions();
$response->setToken('my run speech menu instance id');

// Create the menu action
$menuPrompt = Play::sayText(
    "Say the country for which you want a weather report, " .
    "Belgium, Venezuela or Outer Mongolia. " .
    "Or press 1 for Belgium, " .
    "2 for Venezuela, " .
    "3 for Outer Mongolia. " .
    "Or press 5 to listen to the options again."
);
$menu = new RunSpeechMenu($menuPrompt);
$menu->addSpeechMenuOption('belgium', '1', 'WeatherReport.php');
$menu->addSpeechMenuOption('venezuela', '2', 'WeatherReport.php');
$menu->addSpeechMenuOption('outer mongolia', '3', 'WeatherInOuterMongolia.php');
$menu->setHelpDigit('5');
$menu->setHelpWord('help');

// Set up some new info messages for input timeout and invalid input
$onInputTimeoutMessages = new MessageList();
$onInputTimeoutMessages->addMessage(Play::sayText("I didn't catch your entry."));
$onInputTimeoutMessages->addMessage(Play::sayText("Please select a country."));
$onInputTimeoutMessages->addMessage(Play::playFile("oneMoreTime.wav"));
$menu->setOnInputTimeoutMessages($onInputTimeoutMessages);

$onInvalidInputMessages = new MessageList();
$onInvalidInputMessages->addMessage(Play::sayText("That wasn't one of the options. Please try again."));
$onInvalidInputMessages->addMessage(Play::playFile("oneMoreTime.wav"));
$menu->setOnInvalidInputMessages($onInvalidInputMessages);

$response->add($menu);

print $response;
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");

use \Aculab\TelephonyRestAPI\InstanceInfo;
use \Aculab\TelephonyRestAPI\Actions;
use \Aculab\TelephonyRestAPI\Play;
use \Aculab\TelephonyRestAPI\Redirect;

$info = InstanceInfo::getInstanceInfo();

$response = new Actions();
$response->setToken($info->getToken());
// Get the result of the run_speech_menu action
$result = $info->getActionResult();
$selection = $result->getSelectedDigit();

// Set up the actions
$actions = new Actions();
$playAction = new Play();
if ($selection === '1') {
    $playAction->addText("The weather for Belgium is quite often good but sometimes is appalling.");
} else {
    $playAction->addText("The weather for Venezuela is dry from about November to May " .
        "and considerably wetter for the rest of the year. " .
        "It is close to the equator, so average temperatures below 1000 metres " .
        "are between 70 and 85 degrees fahrenheit in most places."
    );
}
$response->add($playAction);
$response->add(new Redirect("First.php"));

print $response;
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");

use \Aculab\TelephonyRestAPI\InstanceInfo;
use \Aculab\TelephonyRestAPI\Actions;
use \Aculab\TelephonyRestAPI\Play;
use \Aculab\TelephonyRestAPI\Redirect;

$info = InstanceInfo::getInstanceInfo();

$response = new Actions();
$response->setToken($info->getToken());

// Set up the actions
$actions = new Actions();
$playAction = new Play();
$playAction->addText("The weather in Outer Mongolia is just right for outer mongolians.");
$response->add($playAction);
$response->add(new Redirect("First.php"));

print $response;
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");

$info = \Aculab\TelephonyRestAPI\InstanceInfo::getInstanceInfo();

$error = $info->getErrorResult();
$action = $error->getAction();
$desc = $error->getResult();
if (!is_null($action)) {
    error_log("Error from action \"$action\" with result:\n$desc\n");
} else {
    error_log("Error result:\n$desc\n");
}

$response = new \Aculab\TelephonyRestAPI\Actions();
$response->setToken('Error');

$play = new \Aculab\TelephonyRestAPI\Play();
$play->addText('An error has occurred.');
$response->add($play);

print $response;
declare(encoding='UTF-8');
spl_autoload_register();
header("Content-Type: application/json; charset=UTF-8");

$info = \Aculab\TelephonyRestAPI\InstanceInfo::getInstanceInfo();
$call = $info->getThisCallInfo();
$callid = $call->getCallId();
$duration = $call->getSecondsCallDuration();
error_log("This all id: $callid\nThis call duration: $duration\n");

print '';