Handle user input with DTMF

A code snippet that shows how to handle a user input with DTMF. The user enters an option on the keypad and the selected option is acknowledged via a text-to-speech message.

Example

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "User Input DTMF Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

npm install express body-parser

Create a file named dtmf.js and add the following code:

const app = require('express')()
const bodyParser = require('body-parser')

app.use(bodyParser.json())

View full source

Write the code

Add the following to dtmf.js:

const onInboundCall = (request, response) => {
  const ncco = [
    {
      action: 'talk',
      text: 'Please enter a digit'
    },
    {
      action: 'input',
      eventUrl: [`${request.protocol}://${request.get('host')}/webhooks/dtmf`]
    }
  ]

  response.json(ncco)
}

const onInput = (request, response) => {
  const dtmf = request.body.dtmf

  const ncco = [{
    action: 'talk',
    text: `You pressed ${dtmf}`
  }]

  response.json(ncco)
}

app
  .get('/webhooks/answer', onInboundCall)
  .post('/webhooks/dtmf', onInput)

app.listen(3000)

View full source

Run your code

Save this file to your machine and run it:

node dtmf.js

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "User Input DTMF Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

Add the following to `build.gradle`:

compile 'com.vonage:client:6.2.0'
compile 'com.sparkjava:spark-core:2.7.2'

Write the code

Add the following to the main method of the DtmfInput class:

/*
 * Route to answer incoming calls.
 */
Route answerRoute = (req, res) -> {
    TalkAction intro = TalkAction
            .builder("Hello. Please press any key to continue.")
            .build();

    DtmfSettings dtmfSettings = new DtmfSettings();
    dtmfSettings.setMaxDigits(1);

    InputAction input = InputAction.builder()
            .type(Collections.singletonList("dtmf"))
            .eventUrl(String.format("%s://%s/webhooks/dtmf", req.scheme(), req.host()))
            .dtmf(dtmfSettings)
            .build();


    res.type("application/json");

    return new Ncco(intro, input).toJson();
};

/*
 * Route which returns NCCO saying which DTMF code was received.
 */
Route inputRoute = (req, res) -> {
    InputEvent event = InputEvent.fromJson(req.body());

    TalkAction response = TalkAction.builder(String.format("You pressed %s, Goodbye.",
            event.getDtmf().getDigits()
    )).build();

    res.type("application/json");

    return new Ncco(response).toJson();
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/dtmf", inputRoute);

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

  apply plugin: 'application'
  mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.voice with the package containing DtmfInput:

gradle run -Pmain=com.vonage.quickstart.voice.DtmfInput

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "User Input DTMF Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

Install-Package Vonage

Create a file named HandleDtmfInputController.cs and add the following code:

using Vonage.Utility;
using Vonage.Voice.EventWebhooks;
using Vonage.Voice.Nccos;

View full source

Write the code

Add the following to HandleDtmfInputController.cs:

[HttpGet("[controller]/webhooks/answer")]
public IActionResult Answer()
{
    var host = Request.Host.ToString();
    //Uncomment the next line if using ngrok with --host-header option
    //host = Request.Headers["X-Original-Host"];

    var eventUrl = $"{Request.Scheme}://{host}/webhooks/dtmf";

    var talkAction = new TalkAction() { Text = "Hello please press any key to continue" };
    var inputAction = new MultiInputAction()
    {
        EventUrl = new[] { eventUrl },
        Dtmf = new DtmfSettings { MaxDigits = 1}
    };
    var ncco = new Ncco(talkAction, inputAction);
    return Ok(ncco.ToString());
}

[HttpPost("webhooks/dtmf")]
public async Task<IActionResult> Dtmf()
{            
    var input = WebhookParser.ParseWebhook<MultiInput>(Request.Body, Request.ContentType);
    var talkAction = new TalkAction() { Text = $"You Pressed {input?.Dtmf.Digits}, goodbye" };
    var ncco = new Ncco(talkAction);
    return Ok(ncco.ToString());
}

View full source

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "User Input DTMF Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

composer require slim/slim:^3.8 vonage/client

Create a file named index.php and add the following code:

use Laminas\Diactoros\Response\JsonResponse;
use \Psr\Http\Message\ResponseInterface as Response;
use \Psr\Http\Message\ServerRequestInterface as Request;

View full source

Add the following to index.php:

require 'vendor/autoload.php';

$app = new \Slim\App();

View full source

Write the code

Add the following to index.php:

$app->get('/webhooks/answer', function (Request $request, Response $response) {
    //Get our public URL for this route
    $uri = $request->getUri();
    $url = $uri->getScheme() . '://'.$uri->getHost() . ($uri->getPort() ? ':'.$uri->getPort() : '') . '/webhooks/dtmf';

    $input = new \Vonage\Voice\NCCO\Action\Input();
    $input
        ->setEnableDtmf(true)
        ->setEventWebhook(new \Vonage\Voice\Webhook($url, 'GET'))
    ;

    $ncco = new \Vonage\Voice\NCCO\NCCO();
    $ncco
        ->addAction(
            new \Vonage\Voice\NCCO\Action\Talk('Please enter a digit')
        )
        ->addAction($input)
    ;

    return new JsonResponse($ncco);
});

$app->map(['GET', 'POST'], '/webhooks/dtmf', function (Request $request, Response $response) {
    /** @var \Vonage\Voice\Webhook\Input $input */
    $input = \Vonage\Voice\Webhook\Factory::createFromRequest($request);
    $ncco = new \Vonage\Voice\NCCO\NCCO();
    $ncco->addAction(
        new \Vonage\Voice\NCCO\Action\Talk('You pressed '. $input->getDtmf()['digits'])
    );

    return new JsonResponse($ncco);
});

$app->run();

View full source

Run your code

Save this file to your machine and run it:

php -t . -S localhost:3000

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "User Input DTMF Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

pip install 'flask>=1.0'

Create a file named handle-user-input.py and add the following code:

from pprint import pprint
from flask import Flask, request, jsonify

app = Flask(__name__)

View full source

Write the code

Add the following to handle-user-input.py:

@app.route("/webhooks/answer")
def answer_call():
    for param_key, param_value in request.args.items():
        print("{}: {}".format(param_key, param_value))
    input_webhook_url = request.url_root + "webhooks/dtmf"
    ncco = [
        {
            "action": "talk",
            "text": "Hello, please press any key to continue."
        },
        {
            "action": "input",
            "maxDigits": 1,
            "eventUrl": [input_webhook_url]
        }
    ]
    return jsonify(ncco)



@app.route("/webhooks/dtmf", methods=['POST'])
def dtmf():
    data = request.get_json()
    pprint(data)
    ncco = [
        {
            "action": "talk",
            "text": "You pressed {}, goodbye".format(data['dtmf'])
        }
    ]
    return jsonify(ncco)


if __name__ == '__main__':
    app.run(port=3000)

View full source

Run your code

Save this file to your machine and run it:

python3 handle-user-input.py

Prerequisites

A Vonage application contains the required configuration for your project. You can create an application using the Nexmo CLI (see below) or via the dashboard. To learn more about applications see our Vonage concepts guide.

Install the CLI

npm install -g nexmo-cli

Create an application

Once you have the CLI installed you can use it to create a Vonage application. Run the following command and make a note of the application ID that it returns. This is the value to use in NEXMO_APPLICATION_ID in the example below. It will also create private.key in the current directory which you will need in the Initialize your dependencies step

Vonage needs to connect to your local machine to access your answer_url. We recommend using ngrok to do this. Make sure to change demo.ngrok.io in the examples below to your own ngrok URL.

nexmo app:create "User Input DTMF Example" http://demo.ngrok.io/webhooks/answer http://demo.ngrok.io/webhooks/events --keyfile private.key

gem install sinatra sinatra-contrib

Create a file named dtmf.rb and add the following code:

require 'sinatra'
require 'sinatra/multi_route'
require 'json'

helpers do
  def parsed_body
    JSON.parse(request.body.read)
  end
end

before do
  content_type :json
end

View full source

Write the code

Add the following to dtmf.rb:

route :get, :post, '/webhooks/answer' do
  [
    {
      action: 'talk',
      text: 'Please enter a digit'
    },
    {
      action: 'input',
      type: [ 'dtmf' ],
      dtmf: {
        'maxDigits': 1,
        'timeOut': 5
      },
      eventUrl: ["#{request.base_url}/webhooks/dtmf"]
    }
  ].to_json
end

route :get, :post, '/webhooks/dtmf' do
  dtmf = params['dtmf'] || parsed_body['dtmf']

  [{
    action: 'talk',

View full source

Run your code

Save this file to your machine and run it:

ruby dtmf.rb

Try it out

Call your Vonage Number. When the call is answered you will hear a menu. Press 1 on the keypad followed by the # key. You will then hear a text-to-speech message acknowledging your selected option.