Handle user input with DTMF

A building block 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

Replace the following variables in the example code:

Key Description
NEXMO_NUMBER Nexmo Number to call.

Prerequisites

Create an application

A Nexmo 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 Nexmo 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 Nexmo 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

Nexmo 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 dependencies

$ npm install express body-parser
Initialize your dependencies

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

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

app.use(bodyParser.json())

View full source

Write the code

Add the following to app.js:

Copy to Clipboard
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 app.js

Prerequisites

Create an application

A Nexmo 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 Nexmo 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 Nexmo 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

Nexmo 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 dependencies

Add the following to build.gradle:

compile 'com.nexmo:client:4.0.0'
compile 'com.sparkjava:spark-core:2.7.2'

Write the code

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

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

    InputAction input = new InputAction.Builder()
            .eventUrl(String.format("%s://%s/webhooks/dtmf", req.scheme(), req.host()))
            .maxDigits(1)
            .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 = new TalkAction.Builder(String.format("You pressed %s, Goodbye.",
            event.getDtmf()
    )).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.nexmo.quickstart.voice with the package containing DtmfInput:

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

Prerequisites

Create an application

A Nexmo 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 Nexmo 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 Nexmo 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

Nexmo 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 dependencies

$ composer require slim/slim:^3.8

Write the code

Add the following to index.php:

Copy to Clipboard
$app = new \Slim\App;

$app->get('/webhooks/answer', function (Request $request, Response $response) {
    $uri = $request->getUri();
    $ncco = [
        [
            'action' => 'talk',
            'text' => 'Please enter a digit'
        ],
        [
            'action' => 'input',
            'eventUrl' => [
                $uri->getScheme().'://'.$uri->getHost().':'.$uri->getPort().'/webhooks/dtmf'
            ]
        ]
    ];

    return $response->withJson($ncco);
});

$app->post('/webhooks/dtmf', function (Request $request, Response $response) {
    $params = $request->getParsedBody();

    $ncco = [
        [
            'action' => 'talk',
            'text' => 'You pressed '.$params['dtmf']
        ]
    ];

    return $response->withJson($ncco);
});

$app->run();

View full source

Run your code

Save this file to your machine and run it:

$ php -t . -S localhost:3000

Prerequisites

Create an application

A Nexmo 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 Nexmo 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 Nexmo 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

Nexmo 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 dependencies

$ pip install 'flask>=1.0'
Initialize your dependencies

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

Copy to Clipboard
from flask import Flask, request, jsonify
from pprint import pprint

app = Flask(__name__)

View full source

Write the code

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

Copy to Clipboard
@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)

View full source

Run your code

Save this file to your machine and run it:

$ python3 handle-user-input.py

Prerequisites

Create an application

A Nexmo 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 Nexmo 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 Nexmo 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

Nexmo 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 dependencies

$ gem install sinatra
Initialize your dependencies

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

Copy to Clipboard
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:

Copy to Clipboard
route :get, :post, '/webhooks/answer' do
  [
    {
      action: 'talk',
      text: 'Please enter a digit'
    },
    {
      action: 'input',
      eventUrl: ["#{request.base_url}/webhooks/dtmf"]
    }
  ].to_json
end

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

  [{
    action: 'talk',
    text: "You pressed #{dtmf}"
  }].to_json
end

set :port, 3000

View full source

Run your code

Save this file to your machine and run it:

$ ruby dtmf.rb

Try it out

Call your Nexmo 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.