Gridlock Bot Sample application

One of our demo applications is the Gridlock bot that uses the Yahoo Traffic API to provide traffic alerts over IM, Twitter, and SMS.

To test the bot, you can send a message to gridlockbot on AIM or Twitter, gridlock@bot.im on Jabber or Google Talk, or (773) 273-9921 over SMS (US only).

Here's the code behind the bot.

<?php
$location = empty($_POST['msg']) ? false : $_POST['msg'];

if ($location) {
  // This is an inbound message from IMified
  $results = get_results($location);
  $response = '';
  foreach ($results as $incident) {
    if ($_POST['network'] == 'twitter') {
      // Twitter messages can only be 140 characters
      // so we only want the titles of the incidents.
      // Format these as a comma separated string
      // since HTML can't be displayed in twitter
      $response .= $incident['Title'] .', ';
    } else {
      // This is an IM message, so include more detail
      $response .= $incident['Title'] .'<br/>';
      $response .= $incident['Description'] .'<br/><br/>';
    }
  }

  if ($_POST['network'] == 'twitter') {
    // Strip the extra ', '
    $response = substr($response, 0, -2);
    $postlen = 140 - $_POST['user'] - 3;
    if (strlen($response) > $postlen) {
      // Twitter can only handle 140 chars and we need
      // room for the twitter username, so shorten this 
      $postlen = $postlen - 3; // allow room for ellipsis
      $response = substr($response, 0, $postlen) .'...';
    }
  }
  if ($_POST['network'] == 'sms') {
    // Strip the extra ', '
    $response = substr($response, 0, -2);
    $postlen = 160 - 3;
    if (strlen($response) > $postlen) {
      // SMS can only handle 160 chars, so shorten this 
      $postlen = $postlen - 3; // allow room for ellipsis
      $response = substr($response, 0, $postlen) .'...';
    }
  }

  print $response;
}

/**
 * get_results(string $location)
 * Gets traffic from Yahoo Local
 */
function get_results($location) {
  global $debug;
  $location = urlencode($location);
  $url =  'http://local.yahooapis.com/MapsService/V1/trafficData?';
  $url .= 'appid=IMifiedDemo&output=php&severity=3&location='. $location;

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $output = unserialize(curl_exec($ch));
  curl_close($ch);
  $response = array();
  $i = 1;
  // Sometimes Yahoo's response contains just a Result, sometimes a ResultSet.
  // Handle both
  if (!is_array($output) || (!array_key_exists('Result',$output) && !array_key_exists('Result',$output['ResultSet']))) {
    return array(array('Title' => 'No incidents reported.'));
  }
  if (array_key_exists(0, $output['ResultSet']['Result'])) {
    $resultset = $output['ResultSet']['Result'];
  } else {
    $resultset = $output['ResultSet'];
  }
  foreach ($resultset as $result) {
    if (is_array($result) && array_key_exists('Title', $result)) {
      $response[] = $result;      
    }
  }
  return $response;
}
?>