Grabar un mensaje

Un fragmento de código que muestra cómo grabar una conversación. Responder a una llamada y devuelve una NCCO que incluye un record acción. Cuando la llamada haya finalizado, se envía un webhook al eventUrl que especifique. El webhook incluye la URL de la grabación.

Ejemplo

Requisitos previos

npm install express body-parser

Escriba el código

Añada lo siguiente a record-a-message.js:

const Express = require('express');
const bodyParser = require('body-parser');

const app = new Express();
app.use(bodyParser.json());

const onInboundCall = (request, response) => {
  const ncco = [
    {
      action: 'talk',
      text: 'Please leave a message after the tone, then press #. We will get back to you as soon as we can.',
    },
    {
      action: 'record',
      endOnKey: '#',
      beepStart: 'true',
      endOnSilence: '3',
      eventUrl: [`${request.protocol}://${request.get('host')}/webhooks/recordings`],
    },
    {
      action: 'talk',
      text: 'Thank you for your message. Goodbye.',
    },
  ];

  response.json(ncco);
};

const onRecording = (request, response) => {
  const recording_url = request.body.recording_url;
  console.log(`Recording URL = ${recording_url}`);

  response.status(204).send();
};

app
  .get('/webhooks/answer', onInboundCall)
  .post('/webhooks/recordings', onRecording);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

node record-a-message.js

Requisitos previos

Añada lo siguiente a build.gradle:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'
implementation 'io.ktor:ktor-server-netty'
implementation 'io.ktor:ktor-serialization-jackson'

Escriba el código

Añada lo siguiente al método main del archivo RecordMessage:

embeddedServer(Netty, port = 8000) {
    routing {
        get("/webhooks/answer") {
            call.response.header("Content-Type", "application/json")
            call.respond(
                Ncco(
                    talkAction("Please leave a message after the tone, then press #."),
                    recordAction {
                        eventUrl(call.request.path().replace("answer", "recordings"))
                        beepStart(true)
                        endOnSilence(3)
                        endOnKey('#')
                    },
                    talkAction("Thank you for your message. Goodbye!")
                ).toJson()
            )
        }
        post("/webhooks/recordings") {
            val event = EventWebhook.fromJson(call.receive())
            println("Recording URL: ${event.recordingUrl}")
            call.respond(204)
        }
    }
}.start(wait = true)

Ver fuente completa

Ejecute su código

Podemos utilizar el plugin aplicación para Gradle para simplificar la ejecución de nuestra aplicación. Actualiza tu build.gradle con lo siguiente:

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

Ejecute el siguiente comando gradle para ejecutar su aplicación, sustituyendo com.vonage.quickstart.kt.voice por el paquete que contiene RecordMessage:

gradle run -Pmain=com.vonage.quickstart.kt.voice.RecordMessage

Requisitos previos

Añada lo siguiente a build.gradle:

implementation 'com.vonage:server-sdk:9.3.1'
implementation 'com.sparkjava:spark-core:2.9.4'

Escriba el código

Añada lo siguiente al método main del archivo RecordMessage:

/*
 * Route to answer and connect incoming calls with recording.
 */
Route answerRoute = (req, res) -> {
    String recordingUrl = String.format("%s://%s/webhooks/recordings", req.scheme(), req.host());

    TalkAction intro = TalkAction.builder(
            "Please leave a message after the tone, then press #. We will get back to you as soon as we can.").build();

    RecordAction record = RecordAction.builder()
            .eventUrl(recordingUrl)
            .endOnSilence(3)
            .endOnKey('#')
            .beepStart(true)
            .build();

    TalkAction outro = TalkAction.builder("Thank you for your message. Goodbye").build();

    res.type("application/json");

    return new Ncco(intro, record, outro).toJson();
};

/*
 * Route which prints out the recording URL it is given to stdout.
 */
Route recordingRoute = (req, res) -> {
    EventWebhook recordEvent = EventWebhook.fromJson(req.body());
    System.out.println(recordEvent.getRecordingUrl());

    res.status(204);
    return "";
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingRoute);

Ver fuente completa

Ejecute su código

Podemos utilizar el plugin aplicación para Gradle para simplificar la ejecución de nuestra aplicación. Actualiza tu build.gradle con lo siguiente:

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

Ejecute el siguiente comando gradle para ejecutar su aplicación, sustituyendo com.vonage.quickstart.voice por el paquete que contiene RecordMessage:

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

Requisitos previos

Install-Package Vonage

Escriba el código

Añada lo siguiente a RecordMessageController.cs:

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 sitebase = $"{Request.Scheme}://{host}";
    var outGoingAction = new TalkAction()
    {
        Text = "Please leave a message after the tone, then press #. We will get back to you as soon as we can"
    };
    var recordAction = new RecordAction
    {
        EventUrl = new [] {$"{sitebase}/recordmessage/webhooks/recording"},
        EventMethod = "POST",
        EndOnSilence = "3",
        EndOnKey = "#",
        BeepStart = true
    };
    var thankYouAction = new TalkAction {Text = "Thank you for your message. Goodbye"};
    var ncco = new Ncco(outGoingAction, recordAction, thankYouAction);
    return Ok(ncco.ToString());
}

[HttpPost("webhooks/recording")]
public async Task<IActionResult> Recording()
{
    var record = await WebhookParser.ParseWebhookAsync<Record>(Request.Body, Request.ContentType);
    Console.WriteLine($"Record event received on webhook - URL: {record?.RecordingUrl}");
    return StatusCode(204);
}

Ver fuente completa

Requisitos previos

composer require slim/slim:^3.8 vonage/client

Escriba el código

Añada lo siguiente a index.php:

require 'vendor/autoload.php';

$app = new \Slim\App();

$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/recording';

    $record = new \Vonage\Voice\NCCO\Action\Record();
    $record
        ->setEndOnSilence(3)
        ->setEndOnKey('#')
        ->setBeepStart(true)
        ->setEventWebhook(new \Vonage\Voice\Webhook($url))
    ;

    $ncco = new \Vonage\Voice\NCCO\NCCO();
    $ncco
        ->addAction(
            new \Vonage\Voice\NCCO\Action\Talk('Please leave a message after the tone, then press #. We will get back to you as soon as we can')
        )
        ->addAction($record)
        ->addAction(
            new \Vonage\Voice\NCCO\Action\Talk('Thank you for your message. Goodbye')
        )
    ;

    return new JsonResponse($ncco);
});

$app->post('/webhooks/recording', function (Request $request, Response $response) {
    /** @var \Vonage\Voice\Webhook\Record */
    $recording = \Vonage\Voice\Webhook\Factory::createFromRequest($request);
    error_log($recording->getRecordingUrl());

    return $response->withStatus(204);
});

$app->run();

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

php -S localhost:3000 -t .

Requisitos previos

pip install vonage python-dotenv fastapi[standard]

Escriba el código

Añada lo siguiente a record-a-message.py:

from pprint import pprint

from fastapi import Body, FastAPI, Request
from vonage_voice import NccoAction, Record, Talk

app = FastAPI()


@app.get('/webhooks/answer')
async def answer_call(request: Request):
    print(request.base_url)
    ncco: list[NccoAction] = [
        Talk(
            text='Please leave a message after the tone, then press #. We will get back to you as soon as we can.'
        ),
        Record(
            endOnSilence=3,
            endOnKey='#',
            beepStart=True,
            eventUrl=[str(request.base_url) + 'webhooks/recordings'],
        ),
        Talk(text='Thank you for your message. Goodbye.'),
    ]

    return [action.model_dump(by_alias=True, exclude_none=True) for action in ncco]


@app.post('/webhooks/recordings')
async def recordings(data: dict = Body(...)):
    pprint(data)
    return {'message': 'webhook received'}

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

fastapi dev voice/record-a-message.py

Requisitos previos

gem install sinatra sinatra-contrib

Escriba el código

Añada lo siguiente a record-a-message.rb:

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

before do
  content_type :json
end

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

route :get, :post, '/webhooks/answer' do
  [
    {
      "action": "talk",
      "text": "Please leave a message after the tone, then press #. We will get back to you as soon as we can"
    },
    {
      "action": "record",
      "eventUrl": ["#{request.base_url}/webhooks/recordings"],
      "endOnSilence": "3",
      "endOnKey": "#",
      "beepStart": "true"
    },
    {
      "action": "talk",
      "text": "Thank you for your message. Goodbye"
    }
  ].to_json
end

route :get, :post, '/webhooks/recordings' do
  recording_url = params['recording_url'] || parsed_body['recording_url']
  puts "Recording URL = #{recording_url}"

  halt 204
end

set :port, 3000

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

ruby record-a-message.rb

Pruébalo

Necesitarás:

  1. Graba un mensaje marcando tu número de Vonage y dejando tu mensaje después del tono (este fragmento de código).
  2. Descarga la grabación. Consulta el Descargar una grabación para saber cómo hacerlo.

Lecturas complementarias

  • Buzón de voz - Aprende a grabar audio de llamadas entrantes usando .NET y Voice API de Vonage.