How to send a voicemail for outbound calls in case of no-answer using Twilio Voice?

267 Views Asked by At

I cannot find a way to send a no-answer outbound call to go straight to mailbox.

I tried to use AMD to handle the flow of call but it did not work for me. If a call is declined, I get a voicemail on an answering machine. If I let the phone ring and let the call go unanswered, I do not get a voicemail on my device.

Twilio.TwilioClient.Init(username, password);
CallResource call = CallResource.Create(+1xxxxxxxxx, +1xxxxxxxxx,
   twiml: <Response> <Say> Enjoy! </Say>  </Response>",  //detail of voice
   timeout: 60, 
   statusCallback: new Uri(https://test.com/api/Callback),
   statusCallbackMethod: Twilio.Http.HttpMethod.Post,
   statusCallbackEvent: ["initiated", "ringing", "answered", "completed"],
   machineDetection: "DetectMessageEnd"
);
1

There are 1 best solutions below

0
Swimburger On

When you specify the twiml parameter, the TwiML instructions will be executed immediately, while the AMD process is still trying to detect whether a human is answering or an answering machine. You should specify the url parameter pointing to a webhook handler that reads the AnsweredBy parameter and if it is machine_end_beep, respond with the TwiML you'd like.

Here's an example. The code below creates the call using the url parameter which Twilio will call once AMD determines who is answering the call.

using Microsoft.Extensions.Configuration;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

var config = new ConfigurationBuilder()
    .AddUserSecrets<Program>()
    .Build();

TwilioClient.Init(config["TwilioAccountSid"], config["TwilioAuthToken"]);

CallResource.Create(
    new PhoneNumber("+1xxxxxxxxxxx"),
    new PhoneNumber("+1xxxxxxxxxxx"),
    timeout: 60,
    url: new Uri("https://hostname/handler"),
    machineDetection: "DetectMessageEnd"
);

The webhook handler looks like this:

using Twilio.AspNet.Core;
using Twilio.TwiML;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapPost("/handler", async (HttpRequest request) =>
{
    var form = await request.ReadFormAsync();

    var response = new VoiceResponse();
    if (form["AnsweredBy"] == "machine_end_beep")
    {
        response.Say("Your order has been delivered to the store, please pick it up at your earliest convenience.");
    }
    if (form["AnsweredBy"] == "human")
    {
        response.Say("Hi human");
    }

    return Results.Extensions.TwiML(response);
});

app.Run();

AnsweredBy can also be other values than the two cases above, as shown in the AMD docs. The ASP.NET Core app is using the Twilio helper library for ASP.NET Core to handle the webhook.