Faça uma chamada de saída com um NCCO

Este trecho de código faz uma chamada e reproduz uma mensagem de conversão de texto em fala quando a chamada é atendida. Você não precisa executar um servidor que hospede um answer_url para executar este trecho de código, à medida que você fornece seu NCCO como parte da solicitação

Exemplo

Substitua as seguintes variáveis no código de exemplo:

ChaveDescrição
VONAGE_VIRTUAL_NUMBER

Your Vonage Number. E.g. 447700900000

VOICE_TO_NUMBER

The recipient number to call, e.g. 447700900002.

Pré-requisitos

Execute o seguinte comando no prompt do terminal para criar o arquivo ` JWT ` para autenticação:

export JWT=$(nexmo jwt:generate $PATH_TO_PRIVATE_KEY application_id=$NEXMO_APPLICATION_ID)

Escreva o código

Adicione o seguinte ao arquivo ` make-an-outbound-call-with-ncco.sh`:

curl -X POST https://api.nexmo.com/v1/calls\
  -H "Authorization: Bearer $JWT"\
  -H "Content-Type: application/json"\
  -d '{"to":[{"type": "phone","number": "'$VOICE_TO_NUMBER'"}],
      "from": {"type": "phone","number": "'$VONAGE_VIRTUAL_NUMBER'"},
      "ncco": [
        {
          "action": "talk",
          "text": "This is a text to speech call from Vonage"
        }
      ]}'

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

sh make-an-outbound-call-with-ncco.sh

Pré-requisitos

npm install @vonage/server-sdk @vonage/voice

Crie um arquivo chamado ` make-an-outbound-call-with-ncco.js ` e insira o seguinte código:

const { Vonage } = require('@vonage/server-sdk');
const { NCCOBuilder, Talk } = require('@vonage/voice');

const vonage = new Vonage({
  applicationId: VONAGE_APPLICATION_ID,
  privateKey: VONAGE_PRIVATE_KEY,
});

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao arquivo ` make-an-outbound-call-with-ncco.js`:

const builder = new NCCOBuilder();
builder.addAction(new Talk('This is a text to speech call from Vonage'));

vonage.voice.createOutboundCall({
  to: [
    {
      type: 'phone',
      number: VOICE_TO_NUMBER,
    },
  ],
  from: {
    type: 'phone',
    number: VONAGE_VIRTUAL_NUMBER,
  },
  ncco: builder.build(),
})
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

node make-an-outbound-call-with-ncco.js

Pré-requisitos

Adicione o seguinte ao arquivo ` build.gradle`:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'

Crie um arquivo chamado ` OutboundTextToSpeechCallWithNcco ` e adicione o código a seguir ao método ` main `:

val client = Vonage {
    applicationId(VONAGE_APPLICATION_ID)
    privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
}

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao método ` main ` do arquivo ` OutboundTextToSpeechCallWithNcco `:

val callEvent = client.voice.createCall {
    toPstn(VOICE_TO_NUMBER)
    from(VONAGE_VIRTUAL_NUMBER)
    ncco(
        talkAction("This is a text to speech call from Vonage")
    )
}

Ver código-fonte completo

Execute seu código

Podemos usar o plugin “ aplicativo ” para o Gradle a fim de simplificar a execução do nosso aplicativo. Atualize seu arquivo ` build.gradle ` com o seguinte:

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

Execute o seguinte comando ` gradle ` para rodar seu aplicativo, substituindo ` com.vonage.quickstart.kt.voice ` pelo pacote que contém ` OutboundTextToSpeechCallWithNcco`:

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

Pré-requisitos

Adicione o seguinte ao arquivo ` build.gradle`:

implementation 'com.vonage:server-sdk:9.3.1'

Crie um arquivo chamado ` OutboundTextToSpeechWithNcco ` e adicione o código a seguir ao método ` main `:

VonageClient client = VonageClient.builder()
        .applicationId(VONAGE_APPLICATION_ID)
        .privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
        .build();

Ver código-fonte completo

Escreva o código

Adicione o seguinte ao método ` main ` do arquivo ` OutboundTextToSpeechWithNcco `:

Ncco ncco = new Ncco(TalkAction.builder("This is a text to speech call from Vonage").build());

client.getVoiceClient().createCall(new Call(VOICE_TO_NUMBER, VONAGE_VIRTUAL_NUMBER, ncco.getActions()));

Ver código-fonte completo

Execute seu código

Podemos usar o plugin “ aplicativo ” para o Gradle a fim de simplificar a execução do nosso aplicativo. Atualize seu arquivo ` build.gradle ` com o seguinte:

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

Execute o seguinte comando ` gradle ` para rodar seu aplicativo, substituindo ` com.vonage.quickstart.voice ` pelo pacote que contém ` OutboundTextToSpeechWithNcco`:

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

Pré-requisitos

Install-Package Vonage

Escreva o código

Adicione o seguinte ao arquivo ` MakeCallWithNcco.cs`:

var client = new VonageClient(creds);

var toEndpoint = new PhoneEndpoint() { Number = VOICE_TO_NUMBER };
var fromEndpoint = new PhoneEndpoint() { Number = VONAGE_VIRTUAL_NUMBER };
var extraText = "";
for (var i = 0; i < 50; i++)
    extraText += $"{i} ";
var talkAction = new TalkAction() { Text = "This is a text to speech call from Vonage " + extraText };
var ncco = new Ncco(talkAction);

var command = new CallCommand() { To = new Endpoint[] { toEndpoint }, From = fromEndpoint, Ncco = ncco };
var response = await client.VoiceClient.CreateCallAsync(command);

Ver código-fonte completo

Pré-requisitos

composer require vonage/client

Escreva o código

Adicione o seguinte ao arquivo ` index.php`:

$keypair = new \Vonage\Client\Credentials\Keypair(
    file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
    VONAGE_APPLICATION_ID
);
$client = new \Vonage\Client($keypair);

$outboundCall = new \Vonage\Voice\OutboundCall(
    new \Vonage\Voice\Endpoint\Phone(TO_NUMBER),
    new \Vonage\Voice\Endpoint\Phone(VONAGE_NUMBER)
);
$ncco = new NCCO();
$ncco->addAction(new \Vonage\Voice\NCCO\Action\Talk('This is a text to speech call from Nexmo'));
$outboundCall->setNCCO($ncco);

$response = $client->voice()->createOutboundCall($outboundCall);

var_dump($response);

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

php index.php

Pré-requisitos

pip install vonage python-dotenv

Escreva o código

Adicione o seguinte ao arquivo ` make-outbound-call-ncco.py`:

from vonage import Auth, Vonage
from vonage_voice import CreateCallRequest, Phone, Talk, ToPhone

client = Vonage(
    Auth(
        application_id=VONAGE_APPLICATION_ID,
        private_key=VONAGE_PRIVATE_KEY,
    )
)

response = client.voice.create_call(
    CreateCallRequest(
        ncco=[Talk(text='This is a text to speech call from Vonage.')],
        to=[ToPhone(number=VOICE_TO_NUMBER)],
        from_=Phone(number=VONAGE_VIRTUAL_NUMBER),
    )
)

pprint(response)

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

python voice/make-outbound-call-ncco.py

Pré-requisitos

gem install vonage

Escreva o código

Adicione o seguinte ao arquivo ` make-outbound-call-with-ncco.rb`:

client = Vonage::Client.new(
  application_id: VONAGE_APPLICATION_ID,
  private_key: VONAGE_PRIVATE_KEY
)

client.voice.create(
  to: [{
    type: 'phone',
    number: VOICE_TO_NUMBER
  }],
  from: {
    type: 'phone',
    number: VONAGE_VIRTUAL_NUMBER
  },
  ncco: [
    {
      'action' => 'talk',
      'text' => 'This is a text to speech call from Vonage'
    }
  ]
)

Ver código-fonte completo

Execute seu código

Salve este arquivo no seu computador e execute-o:

ruby make-outbound-call-with-ncco.rb

Experimente

Quando você executar o código, o VOICE_TO_NUMBER será feita uma ligação e uma mensagem de conversão de texto em fala será reproduzida caso a ligação seja atendida.

Leitura complementar

  • Notificações de voz - Neste guia, você aprenderá como entrar em contato com uma lista de pessoas por telefone, transmitir uma mensagem e verificar quem confirmou o recebimento da mensagem. Esses alertas críticos por voz são mais persistentes do que uma mensagem de texto, aumentando as chances de sua mensagem ser notada. Além disso, com a confirmação do destinatário, você pode ter certeza de que sua mensagem foi entregue.
  • Teleconferência - Este guia explica os dois Concepts que a Vonage associa a uma chamada: “leg” e “conversação”.
  • Bot de voz com o Google Dialogflow - Este guia vai ajudá-lo a dar os primeiros passos com um bot do Dialogflow de exemplo e a interagir com ele por meio de chamadas telefônicas, utilizando os códigos de referência de exemplo fornecidos e a Voice API da Vonage.