How do I get twilio 5 digit error code for a failed voice call? - twilio

We have a callback url in place that is correctly capturing the failed status of a call.
Our code then fetches from twilio the details of the call by doing the following:
$call = $twilio_client->calls($sid)->fetch();
Within the call details returned there is no 5 digit error code listed, even though the failed status is present.
How do we get the 5 digit error code that caused the failure?

Twilio developer evangelist here.
Thanks to #miknik for the answer, however that is actually a deprecated resource (which is why you can't currently find any documentation on the matter). It's taken me a while to find the answer as I've been chasing down where the notifications have gone.
The Notifications API was deprecated in favour of the Monitor Alerts API. This API can give you all the details about an alert, including the 5 digit code.
The best way to receive these alerts for your application is to set up a webhook in your account console which will send all the parameters about the alert as part of the request.
You can also list your alerts which will allow you to find alerts from a specific resource SID (in your case, a call SID).
Let me know if this helps at all.

Make an authenticated GET request to
/2010-04-01/Accounts/{AccountNumber}/Calls/{CallSid}/Notifications
So in PHP the following will retrieve the notification info for your call
$json = file_get_contents('https://{AccountNumber}:{AuthToken}#api.twilio.com/2010-04-01/Accounts/{AccountNumber}/Calls/{CallSid}/Notifications.json');
Then use this line to get the returned JSON into an associative array
$obj = json_decode($json, true);
Now if all you want is the error code its stored as the following variable
echo $obj[notifications][0][error_code];
However, the full error info is also returned as a URL encoded string. You can access this by first urldecoding it, and then parsing the query string into an array with the following line
parse_str(urldecode($obj[notifications][0][message_text]), $output);
And you can now access the variables within like this
echo $output[Msg]; // Error text for failure eg invalid phone number
echo $output[phonenumber]; // Phone number for failed call
echo $output[ErrorCode]; // 5 digit error code
echo $output[LogLevel];` // Log level of error eg WARN
As far as I know this is not implemented in the PHP helper library, so you have to code for it manually

Related

How to collect the user input when make a call using Twilio API?

I am developing a simple application in C# which
Trigger a call using Twilio
receiver to press * after receiving the call and finish the call after pressing *
Provide the status completed if user pressed * otherwise provide different status.
I was able to make a call but not able to receive the user input Or status, I tried finishOnKey() but that didn't work, and it always provides status as completed. I didn't get much help from Twilio code sample, can someone redirect to correct article or provide the code to accomplish above.
Twilio developer evangelist here.
Once a call is answered successfully, it doesn't matter how the call is finished, the final status it reaches will be "completed". You can see more about Twilio call statuses in this documentation. You can see that the final call statuses could be:
completed: call was answered successfully and then finished
no-answer: Twilio dialled the number but there was no answer before the timeout
busy: Twilio dialled the number but received a busy signal
cancelled: The number was dialled, but the call was then cancelled using the API before answering
failed: the carrier couldn't connect the call
If you are using <Gather> to take the user input, you should ensure you have set the action attribute to a URL in your application. That URL will receive a new webhook request when the user presses a digit. For example:
<Response>
<Gather action="/gather_results" digits="1">
<Say>... your content goes here ...</Say>
</Gather>
</Response>
With the above TwiML a user would only have to press 1 key before the call is moved to the next stage and the webhook '/gather_results'.
The request to the /gather_results endpoint would include a body with a Digits parameter. If the user pressed "*" then the body of the request would include Digits=*, if the user pressed "1" then it would include Digits=1. You could then choose to do whatever you like with those results, including hanging up the call or recording the submitted digits.
Let me know if this helps at all.

Twilio whatsapp message fails even when matches the approved template

I am trying to send a whatsapp message via Twilio Business Account, from a number my company has registered via twilio and configured to be a sender.
In the Twilio logs, I see error 63016 message not in template, even though I double-checked every word and spacing to see that my message matches the approved template
some code to help:
def send_message(phone, template_message):
try:
message = twilio_client.messages.create(
body=template_message,
from_=f'whatsapp:{MY_SENDER_NUMBER}',
to=f'whatsapp:{phone}'
)
except TwilioRestException as e:
return False, e.msg
return True, ''
this completes with no error and results in this log line in twilio
From,To,Body,Status,SentDate,ApiVersion,NumSegments,ErrorCode,AccountSid,Sid,Direction,Price,PriceUnit
"whatsapp:+XXXXXXXXXXXX","whatsapp:+XXXXXXXXXXXX","MY MESSAGE THAT MATCHES THE TEMPLATE,
WITH SOME NEWLINES!
AND some characters like '' and ,
",UNDELIVERED,2021-04-11T07:58:32Z,"2010-04-01",1,63016,XXXXXXXXXXXXXXXXXXXXXXXXXXXXx,XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx,"
outbound-api",0.0,USD
note: if I open my whatsapp and sends the sender a message, then if I run this code again it will work and I will see that message (as that message does not have to match a template for a 24-hr window).
After help from Twilio support, it was a missing '\n' in the message that I was trying to send, that caused the message not to match the template.
I had the same problem, but was due to just a simple whitespace.

Taskrouter problem using Laravel. Task not getting created?

I've followed every single step in the Twilio's documentation called Dynamic Call Center with Laravel.
My problem is that a call gets through the IVR, then after choosing a digit, nothing happens.
My guess is that its not creating a task. the code provided in the documentation just generate a task with json but thats it. I check my tasks in Twilio taskrouter console and nothing shows up.
I've provided all credentials, used ngrok, filled in all url callbacks.
public function enqueueCall(Request $request)
{
define('workflowSid', env('TWILIO_WORKFLOW_SID'));
$selectedSkillInstruction = new \StdClass();
$selectedSkillInstruction->selected_skill = $this->_getSelectedSkill($request);
$response = new Twiml();
$enqueue = $response->enqueue(['workflowSid' => workflowSid]);
$enqueue->task(json_encode($selectedSkillInstruction));
return response($response)->header('Content-Type', 'text/xml');
}
I expect a code that actually creates a task, but when I call this api via postman, a task is not created
The above code returns Twilio Markup Language (TwiML) which uses the enqueue verb and a workflowSid attribute. The enqueue verb is used with Programmable Voice. Have you tried associating your application with a Twilio phone number and then calling the Twilio number which should enqueue the call into a task router workflow?
TwiML Voice: Enqueue
https://www.twilio.com/docs/voice/twiml/enqueue#attributes-workflowSid
I have solved my problem. It turned out that everything was in order, the only problem is that I didn't know I need to press # after choosing from the IVR because all the demo I saw from Twilio only press a number and it gets routed.

StatusCallback does not work as expected

Overview:
I am working on a VB.NET application that places a call into Twilio, the number is not a test number. I am using the C# library with the code written in VB.Net.
When I use this line of code:
Console.WriteLine(account.SendSmsMessage(Caller, to1, strBody))
I receive a text message on my phone however the post back is never posted to my website. I have included the URL of the site on the account under Messaging > Request URL.
When I reply to the message, Twilio does make a post to my site. From what I understand, a POST should have been made when Twilio was first sent a message from my application, however this is not the case.
When using this code, I do not get any text message and no POST is made.
Console.WriteLine(account.SendMessage(Caller, to1, strBody, PostBackURL))
I have tried SendSMSMessage, I have tried it with the URL on my account and without it,
nothing seems to effect the behavior.
I need the SmsMessageSid at the time the message is sent. From everything I have seen, Twilio does not provide a response other then what is sent to the PostBackURL, I could parse a response for the
SmsMessageSid however since there is no response that is not an option. If I am mistaken on that point that would be great, however it looks like the only way to get a reply is with the post back URL. Thanks for your help with this! Below you will find an excerpt of the code I am working with:
PostBackURL = "http%3A%2F%2F173.111.111.110%3A8001/XMLResponse.aspx"
' Create Twilio REST account object using Twilio account ID and token
account = New Twilio.TwilioRestClient(SID, Token)
message = New Twilio.Message
Try
'WORKS
'Console.WriteLine(account.SendSmsMessage(Caller, to1, strBody))
'DOES NOT WORK
Console.WriteLine(account.SendMessage(Caller, to1, strBody, PostBackURL))
Catch e As Exception
Console.WriteLine("An error occurred: {0}", e.Message)
End Try
Console.WriteLine("Press any key to continue")
Console.ReadKey()
I'm doing something similar with C# and like you, I'm not getting the POST to the callback URL. I don't know why that's not working, but if all you need is the sid when you send the message, you should be able to do this:
message = SendSmsMessage(Caller, to1, strBody))
and message.Sid will give you what you need, assuming no exceptions.

Twilio sms not coming in mobile

I have implemented test twilio sms application. I have downloaded three files from https://github.com/benedmunds/CodeIgniter-Twilio
I have used my account_sid, auth_token in twilio.php file which is in config folder. I have also used 'from' number as +15005550006 in that file.
I have used following codes in my controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Twiliosms extends TL_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->library('twilio');
$from = '+15005550006';
$to = '+91xxxxxxxxxx';
$message = 'This is a test...';
$response = $this->twilio->sms($from, $to, $message);
//echo "<pre>";print_r($response);echo "</pre>";
if($response->IsError)
echo 'Error: ' . $response->ErrorMessage;
else
//echo 'Sent message to ' . $to;
echo 'Sent message';
}
}
Now when I run the controller file in the browser(not in my machine but in server), it runs successfully and it shows "Sent message".
But no sms is received. Please help.
My name is Jarod and I work at Twilio. There are multiple reasons this could be failing so lets walk through them one at a time.
1. Sending an sms using Twilio test credentials will not result in an sms being sent.
Test credentials are used for testing and debugging your application. They are "fake" numbers, that do not send any data via carrier, but instead return preset error codes and responses in order to test response-handling in your application. As you experienced this specific test credential +15005550006 will always return NO ERROR, whereas +15005550001 will always respond with "This phone number is invalid".
2. You can only send SMS from a Twilio number or a verified phone number.
You can always send an SMS from a number you bought on Twilio.com, but in order to send an SMS from any other number you must first verify that phone number with Twilio. Read more about the difference here.
These are the most common reasons for not receiving and actual SMS but in the case of the Indian phone numbers it could very well be one of these rare limitations.
If none of these work we probably need to look into your specific account to find out what's happening, in which case you should reach out to support#twilio.com.
Hope this helps.
I banged my head against the walls for three hours and tried to work out with the number Twilio gave me at the time of sign up . But It always gave me the following error
{ "code": 21212, "message": "The 'From' number +234234234 is not a
valid phone number or shortcode.", "more_info":
"https://www.twilio.com/docs/errors/21212", "status": 400 }
At the end i got the exact point from where I got my test phone number for sms / call
Get your test phone number from Here .
You will have to make the from number a number you have verified with Twilio that you own: you can't just pick any number and use it. Do you own +15005550006, and have you verified that number in the Twilio admin console?

Resources