Twitter bot sample
Connecting Twitter to your bot is really as simple as authenticating your Twitter account from inside IMified. You don't need to write any special code or do anything new with Twitter. Things will just work.
However, since Twitter has some restrictions that aren't present in IM, like a maximum message length of 140 characters, you might want to intercept messages that come via Twitter and format them differently.
We've done just that in one of our example bots. Gridlock is a bot that looks up local traffic conditions using the Yahoo Traffic API. Send it your location (City and state, address, or zip code will all work) and Gridlock will tell you what traffic is in your area.
Gridlock is available on Jabber as gridlock@bot.im or on AIM, Yahoo, or Twitter as gridlockbot
Here's the PHP source code.
<?php
if ($_POST['msg']) {
// This is an inbound message from IMified
$results = get_results($_POST['msg']);
$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);
// Twitter can only handle 140 chars and we need
// room for the twitter username, so shorten this
$postlen = 140 - $_POST['user'] - 3;
if (strlen($response) > $postlen) {
$postlen = $postlen - 3; // allow room for ellipsis
$response = substr($response, 0, $postlen) .'...';
}
} else {
// Strip the extra line breaks
$response = substr($response, 0, -10);
}
print $response;
}
/**
* get_results(string $location)
* Gets traffic from Yahoo Local
*
* @param string $location A location string to search.
* @return array Array of search results
*
*/
function get_results($location) {
$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;
if (!is_array($output)) {
return array('result'=>'');
}
if (!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;
}
?>