Twilio Cookbook
上QQ阅读APP看书,第一时间看更新

Setting up a company directory

A company directory is a very handy thing to have when you want a company phone number to be published and then have it contact other people in your company. It's also nice to make it searchable and that is what we are doing today.

This particular company directory has served me well at several companies I've worked with over the years and I'm especially pleased with its ability to convert names into their matching digits on a phone pad using this function:

  function stringToDigits($str) {
    $str = strtolower($str);
    $from = 'abcdefghijklmnopqrstuvwxyz';
    $to = '22233344455566677778889999';
    return preg_replace('/[^0-9]/', '', strtr($str, $from, $to));
  }

This function works such that a name such as Stringer (my last name), gets converted into 78746437. Then, as the caller does a search, it will return an employee whose name matches the digits entered and will then connect the call.

Getting ready

The complete source code for this recipe can be found at Chapter1/Recipe6.

How to do it...

We're going to build a basic, searchable company directory that will let callers either enter an extension or search by their last name.

  1. Download the Twilio Helper Library (from https://github.com/twilio/twilio-php/zipball/master) and unzip it.
  2. Upload the Services/ folder to your website.
  3. Upload config.php to your website and make sure the following variables are set:
    <?php
      $accountsid = '';  //  YOUR TWILIO ACCOUNT SID
      $authtoken = '';  //  YOUR TWILIO AUTH TOKEN
      $fromNumber = '';  //  PHONE NUMBER CALLS WILL COME FROM
    ?>
  4. Let's create the file called company-directory-map.php, which sets up the map for the company directory:
    <?php
      $directory = array(
        '0'=> array(
          'phone'=>'415-555-1111',
          'firstname' => 'John',
          'lastname' => 'Smith'
        ),
        '1234'=> array(
          'phone'=>'415-555-2222',
          'firstname' => 'Joe',
          'lastname' => 'Doe'
        ),
        '4321'=> array(
          'phone'=>'415-555-3333',
          'firstname' => 'Eric',
          'lastname' => 'Anderson'
        ),
      );
      $indexes = array();
      foreach($directory as $k=>$row){
        $digits = stringToDigits( $row['lastname'] );
        $indexes[ $digits] = $k;
      }
      function stringToDigits($str) {
        $str = strtolower($str);
        $from = 'abcdefghijklmnopqrstuvwxyz';
        $to = '22233344455566677778889999';
        return preg_replace('/[^0-9]/', '', strtr($str, $from,$to));
      }
      function getPhoneNumberByExtension($ext){
        global $directory;
        if( isset( $directory[$ext] ) ){
          return $directory[$ext];
        }
        return false;
      }
      function getPhoneNumberByDigits($digits){
        global $directory,$indexes;
        $search = false;
        foreach( $indexes as $i=>$ext ){
          if( stristr($i,$digits) ){
            $line = $directory[ $ext ];
            $search = array();
            $search['name']= $line['firstname']."".$line['lastname'];
            $search['extension']=$ext;
          }
        }
        return $search;
      }
    ?>

    This file handles the list of extensions, and also takes care of the functions that handle the searching. One of the steps it performs is to loop through each extension and convert the last name into digits corresponding with a phone pad.

  5. Now, we'll create company-directory.php to handle the logic for incoming calls:
    <?php
      session_start();
      include 'Services/Twilio.php';
      include 'config.php';
      include('company-directory-map.php');
      $first = true;
      if (isset($_REQUEST['Digits'])) {
        $digits = $_REQUEST['Digits'];
        if( $digits == "*"){
          header("Location: company-directory-lookup?Digits=".$digits);
          exit();
        }
      } else {
        $digits='';
      }
      if( strlen($digits) ){
        $first = false; 
        $phone_number = getPhoneNumberByExtension($digits);
        if($phone_number!=null){
          $r = new Services_Twilio_Twiml();
          $r->say("Thank you, dialing now");
          $r->dial($phone_number);
          header ("Content-Type:text/xml");
          print $r;
          exit();
        }
      }
      $r = new Services_Twilio_Twiml();
      $g = $r->gather();
      if($first){
        $g->say("Thank you for calling our company.");
      }else{
        $g->say('I\'m sorry, we could not find the extension '. $_REQUEST['Digits']);
      }
      $g->say(" If you know your party's extension, please enter the extension now, followed by the pound sign. To search the directory, press star. Otherwise, stay on the line for the receptionist.");
      $r->say("Connecting you to the operator, please stay on the line.");
      $r->dial($receptionist_phone_number);
      header ("Content-Type:text/xml");
      print $r;
      exit;
    ?>

    All incoming calls will first come into this file and, from there, will either be redirected straight to an extension or start the lookup process based on the last name.

  6. And finally, we create company-directory-lookup.php that adds the ability to perform search operations:
    <?php
      session_start();
      include 'Services/Twilio.php';
      include 'config.php';
      include('company-directory-map.php');
      $error = false;
      if (isset($_REQUEST['Digits'])){
        $digits = $_REQUEST['Digits'];
      }else{
        $digits='';
      }
      if(strlen($digits)){
        $result = getPhoneNumberByDigits($digits);
        if($result != false){
          $number = getPhoneNumberByExtension($result['extension']);
          $r = new Services_Twilio_Twiml();
          $r->say($result['name']."'s extension is".$result['extension']." Connecting you now");
          $r->dial($number);
          header ("Content-Type:text/xml");
          print $r;
          exit();
        } else {
          $error=true;
        }
      }
      $r = new Services_Twilio_Twiml();
      if($error)    $r->say("No match found for $digits");
      $g = $r->gather();
      $g->say("Enter the first four digits of the last name of the party you wish to reach, followed by the poun dsign");
      $r->say("I did not receive a response from you");
      $r->redirect("company-directory.php");
      header ("Content-Type:text/xml");
      print $r;
    ?>

    This file handles our lookups; as a caller types digits into a phone dial pad, this script will loop through the extensions to find a name that matches the digits entered.

  7. Finally, we need to have a number point to this script. Upload company-directory.php somewhere and then point your Twilio phone number to it:

    Insert the URL in the Voice Request URL field on this page. Then, any calls that you receive at this number will be processed via company-directory.php.

How it works...

In steps 1 and 2, we downloaded and installed the Twilio Helper Library for PHP.

In step 3, we uploaded config.php that contains our authentication information to talk to Twilio's API.

In step 4, we set up the $directory array in company-directory-map.php, which is the core of this system; it handles the extension number for each employee as well as containing his/her phone number, first name, and last name.

When a caller chooses to search for an employee, the last name is converted into corresponding digits similar to what you see on a phone.

So for example, Stringer becomes 78746437; as the caller does a search, it will return an employee whose name matches and will then connect the call.

Finally, in step 7, we set up our phone number in Twilio to point to the location where company-directory.php has been uploaded so that all calls to that phone number go straight to company-directory.php.

You now have a nice, searchable company directory. I've been using this directory myself for the last two years at various companies and it works nicely.