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

Install dependencies

Initialize your dependencies

Write the code

Add the following to app.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 app.js

Prerequisites

Create an application

Install dependencies

Write the code

Add the following to DtmfInput.java:

/*
 * Route to answer incoming calls with an NCCO response.
 */
Route incomingCall = (req, res) -> {
    TalkNcco intro = new TalkNcco("Hello please press any key to continue");

    String eventUrl = String.format("%s://%s/webhooks/dtmf", req.scheme(), req.host());
    InputNcco input = new InputNcco();
    input.setEventUrl(eventUrl);

    Ncco[] nccos = new Ncco[]{intro, input,};

    res.type("application/json");
    return new ObjectMapper().writer().writeValueAsString(nccos);
};

/*
 * Webhook Route which returns NCCO saying which DTMF code was received.
 */
Route answerRoute = (req, res) -> {
    String dtmf = req.queryParams("dtmf");
    TalkNcco intro = new TalkNcco(String.format("You pressed %s, Goodbye.", dtmf));

    Ncco[] nccos = new Ncco[]{intro};

    res.type("application/json");
    return new ObjectMapper().writer().writeValueAsString(nccos);
};

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

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

Install dependencies

Write the code

Add the following to index.php:

$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

Install dependencies

Initialize your dependencies

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 inout_webhook():
    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

Write the code

Add the following to dtmf.rb:

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

before do
  content_type :json
end

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

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.