7

I am using twilio to send bulk sms messages. Let's say some customer decided that they don't want to receive messages anymore so they reply with "stop" and that will add them to the black list. I am hard coding the phone numbers because I am still testing on my own cell phones. I noticed that when I do not remove the numbers on the black list from my code, I am getting an error message and my script stops at that point.

In the future, I will probably be using numbers stored in a database or a file. In that case, how do I overcome this problem if it happened. Basically what I want to do is: If a number is in the black list, move on to the next number and avoid that error using an exception or something. The error message and code is below.

Thanks,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Send SMS</title>
<?php
    /* Send an SMS using Twilio. You can run this file 3 different ways:
     *
     * 1. Save it as sendnotifications.php and at the command line, run 
     *         php sendnotifications.php
     *
     * 2. Upload it to a web host and load mywebhost.com/sendnotifications.php 
     *    in a web browser.
     *
     * 3. Download a local server like WAMP, MAMP or XAMPP. Point the web root 
     *    directory to the folder containing this file, and load 
     *    localhost:8888/sendnotifications.php in a web browser.
     */

    // Step 1: Get the Twilio-PHP library from twilio.com/docs/libraries/php, 
    // following the instructions to install it with Composer.
    //require_once "vendor/autoload.php";
    require __DIR__ . '/twilio-php-master/Twilio/autoload.php';
    use Twilio\Rest\Client;

    // Step 2: set our AccountSid and AuthToken from https://twilio.com/console
    $AccountSid = "something";
    $AuthToken = "something";

    // Step 3: instantiate a new Twilio Rest Client
    $client = new Client($AccountSid, $AuthToken);

    // Step 4: make an array of people we know, to send them a message. 
    // Feel free to change/add your own phone number and name here.
    $people = array(
        "+17570123456" => "Chris",
        "+17571234568" => "Hussam"
    );

    // Step 5: Loop over all our friends. $number is a phone number above, and 
    // $name is the name next to it
    foreach ($people as $number => $name) {

        $sms = $client->account->messages->create(

            // the number we are sending to - Any phone number
            $number,

            array(
                // Step 6: Change the 'From' number below to be a valid Twilio number 
                // that you've purchased
                'from' => "+184444444444", 

                // the sms body
                'body' => "Hey $name, this is Hussam. Testing Twilio SMS API!"
            )
        );

        // Display a confirmation message on the screen
        echo "Sent message to $name.\n";
    }
?>

( ! ) Fatal error: Uncaught exception 'Twilio\Exceptions\RestException' with message '[HTTP 400] Unable to create record: The message From/To pair violates a blacklist rule.' in C:\wamp64\www\Twilio\twilio-php-master\Twilio\Version.php on line 86 ( ! ) Twilio\Exceptions\RestException: [HTTP 400] Unable to create record: The message From/To pair violates a blacklist rule. in C:\wamp64\www\Twilio\twilio-php-master\Twilio\Version.php on line 86 Call Stack

Time Memory Function Location 1 0.0000 239280 {main}( ) ...\send.php:0 2 0.0156 799016 Twilio\Rest\Api\V2010\Account\MessageList->create( ) ...\send.php:56 3 0.0156 814688 Twilio\Version->create( ) ...\MessageList.php:63

Hussam Hallak
  • 303
  • 4
  • 21

2 Answers2

5

Twilio developer evangelist here.

You need to catch the exception that is thrown from the request to send a message to the blacklisted number. You can do so with try and catch like this:

foreach ($people as $number => $name) {
    try {
        $sms = $client->account->messages->create(
            $number,
            array(
                'from' => "+18443949780", 
                'body' => "Hey $name, this is Hussam. Testing Twilio SMS API!"
            )
        );
        echo "Sent message to $name.\n";
    } catch (\Twilio\Exceptions\RestException $e) {
        echo "Couldn't send message to $number\n";
    }
}

When you hook this up to a database, you'll want to use the catch to update a field to mark the number as blocked so that you don't try to send to it again.

Let me know if that helps at all.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • No problem! Good luck with the rest of your application! – philnash Dec 06 '16 at 16:56
  • Are you kidding me? Why you crash when someone is blacklisted? Can't you just return an error code? This is so unprofessional. – Jin Jul 27 '17 at 16:29
  • 2
    Hi Jin, the library doesn't crash when someone is blacklisted, but the SDK does throw an error when it receives a non 200 response from the API. You should be putting a try/catch block around calls like this to external APIs anyway, as if there is a network issue or another bad request then the SDK will also throw, so this is nothing too different to that. – philnash Jul 27 '17 at 16:32
  • Unfortunately this try catch solution does not work with the latest sdk. – Peter Drinnan Oct 01 '18 at 03:20
  • Hi @PeterDrinnan, what issues are you finding with the latest SDK? This answer was from almost 2 years ago and things have moved on since then. If you have a specific issue, do start a new question and point me at it and I'll try to help. – philnash Oct 01 '18 at 03:22
  • Thanks for your reply philnash. I posted the solution below. Hopefully someone will find it helpful. – Peter Drinnan Oct 02 '18 at 13:42
  • I confirm that this does not work at stopping the SDK from crashing when trying to send a message to a backlisted number in September 2020. We have over 200 users in our databases and 1 blacklisted number prevents PHP from continuing the queries. I'm looking for solution. – Grogu Sep 07 '20 at 16:47
2

This worked for me with Laravel 5. Notice the use of \Twilio\Exceptions\RestException.

   try {
        $sms = $client->account->messages->create(
            $number,
            array(
                'from' => "+16136543180", 
                'body' => "Hey $name, Are you still mad at us about your cat!"
            )
        );
        echo "Sent message to $name.\n";

     } catch (\Twilio\Exceptions\RestException $e) {
          if ($e->getCode() == 20404) {
              //this will be false condition
              dd('False Result 404');
          } else {
              //some other exception code
              dd($e->getMessage());    
          }
     }
Peter Drinnan
  • 4,344
  • 1
  • 36
  • 29
  • Yes this worked for me. The codes suggested by the other answer does not work anymore in 2020. This should be the accepted answer. – Grogu Sep 07 '20 at 19:00