PDA

View Full Version : twitter api stuff



iBrightDev
June 28th, 2009, 11:53
well, i was wanting to past the most recent @reply from my account to a website, but, coudnt seem to find anything out there for it. i found hundreds of things about posting the most recent user comments, but, that isnt what i wanted. so, i started messing with the things i found and eventually got my script to return the most recent @reply. but, then i ran into another obstacle, logging into the twitter api as a valid user. well, i figured CURL would be able to solve this issue, but, i had never used CURL and was not to sure how to go about that either. so, more googleing had to take place. long story short, i finally got curl working and was able to do what i wanted and figured i would share it with my fellow FWSers in case anyone was wanting something like this.




$glbl = new specialIncludes();
$twtr = new twitter("YOUR TWITTER USERNAME HERE", "YOUR TWITTER PASSWORD HERE");

// GLOBAL FUNCTIONS
class specialIncludes {

public function trunc($phrase, $url, $limit, $target) {
global $bL;

if ($target != null) {
$target = ' target="_' . $target . '"';
}

$max_words = $limit;
$phrase_array = explode(' ',$phrase);
if(count($phrase_array) > $max_words && $max_words > 0)
$phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'<a href="' . $url . '"' . $target . '>...</a>';
return $phrase;

}
}

class twitter {

private $Username;
private $Password;

private $UrlTwitter = 'http://twitter.com/';
private $UrlStatus = 'http://twitter.com/statuses/';

function __construct ($user, $password) {
$this->Username = $user;
$this->Password = $password;
}

public function replies($count) {
global $glbl;

$url = 'http://twitter.com/statuses/replies/' . $this->Username . '.xml?callback=twitterCallback2&count=' . $count;

if(function_exists(curl_init)) {

//Create the connection handle
$ch = curl_init($url);

//Set cURL options
curl_setopt($ch, CURLOPT_URL, $url); //URL to connect to
curl_setopt($ch, CURLOPT_GET, 1); //Use GET method
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); //Use basic authentication
curl_setopt($ch, CURLOPT_USERPWD, "$this->Username:$this->Password"); //Set u/p
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //Do not check SSL certificate (but use SSL of course), live dangerously!
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Return the result as string

// Result from querying URL. Will parse as xml
$output = curl_exec($ch);

$Headers = curl_getinfo($ch);

if($Headers['http_code'] == 200) {

$data = simplexml_load_string($output);
$protc = "protected";
$twtr_user_id = (string) $data->status->user->id;
$twtr_user_name = (string) $data->status->user->name;
$twtr_user_screen_name = (string) $data->status->user->screen_name;
$twtr_user_location = (string) $data->status->user->location ;
$twtr_user_description = (string) $data->status->user->description;
$twtr_user_pimgurl = (string) $data->status->user->profile_image_url;
$twtr_user_url = (string) $data->status->user->url;

$twtr_status_created_at = (string) $data->status->created_at;
$twtr_status_id = (string) $data->status->id;
$twtr_status_text = (string) $data->status->text;
$twtr_status_source = (string) $data->status->source;

// Fri Jun 05 10:46:56 +0000 2009
$twtr_post_date = $twtr_status_created_at;
list($wk_day, $month, $day, $day_time, $plus_time, $year) = split(" ", $twtr_post_date);
$twtr_post_date = "$month $day, $year";

// Build a pattern that is going to be used in a @reply replace
$pattern = "#(^|[\n ])@([^ \"\t\n\r<]*)#ise";
// Build the link for the @reply replace
$replace = "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'";
// Find instances of a user @reply, and replace it with a link
$twtr_status_text = preg_replace($pattern, $replace, $twtr_status_text);
// Build a url for a more link
$twtr_more_link = 'http://twitter.com/' . $twtr_user_screen_name . '/statuses/' . $twtr_status_id;
// Truncate the text if needed
$twtr_status_text = $glbl -> trunc($twtr_status_text, $twtr_more_link, 25, 'blank');

$tweet .= '<span class="small"><strong>' . $twtr_user_screen_name . ' said:</strong> </span>'.$bL;
$tweet .= '<span class="small">' . $twtr_status_text . '</span> <a style="font-size:85%; display: none;" href="http://twitter.com/' . $twtr_user_screen_name . '/statuses/' . $twtr_status_id . '">' . $twtr_post_date . '</a>';

return $tweet;

} else {
if ($Headers['http_code'] == 401) {
$this->Error(4);

} elseif ($Headers['http_code'] == 404) {
$this->Error(5);
}
}

// close cURL resource.
curl_close($ch);

}

} // END LOG_API


private function Error($Error) {
// List of Errors
$e[1] = 'Username and/or password not set';
$e[2] = 'CURL library not installed';
$e[3] = 'Post value too long/not set';
$e[4] = 'Invalid username/password';
$e[5] = 'Invalud URL for CURL request';
$e[6] = 'Invalid ID value entered';
$e[7] = 'You are not authorized to view this page';
$e[8] = 'All variables for requested function not set';
$e[9] = 'For and/or Message not set';
// Display Error
if (array_key_exists($Error, $e)){
echo $e[$Error];
} else {
echo 'Invalid Error Code';
}
} // End Error()


}



here is the html i used to utilize the twitter class i created.




<div class="float-left btm-txt">
<!-- TWITTER -->
<div id="twitter_div">
<ul id="twitter_update_list">
<li class="small"><?=$twtr->replies(1)?></li>
</ul>
<div class="follow_us"><a href="http://twitter.com/YOUR TWITTER USERNAME HERE" title="Follow me on Twitter" target="Twitter">Follow us on twitter</a></div>
</div>
<!-- END TWITTER -->
</div>



now, there is one problem that i have run into, and maybe someone will post a solution before i get around to figuring it out myself.

in this little bit of code...

<?=$twtr->replies(1)?>

we can change the "1" to a "3", no quotes, and have it pull more results in the xml, but, i cant seem to get it to spit out the other results, just the first one. now exactly sure why. so, if anyone knows what i need to add to the script, please, let me know.

right now, you can see the code in action here...
demo here (http://dynamicpagesolutions.com/new/justin/)

iBrightDev
June 30th, 2009, 14:16
well, since i cant edit my previous message, i will just post the new code where i can actually get as many results to return as i want.

new code...




$glbl = new specialIncludes();
$twtr = new ibd_twitter("YOUR TWITTER USERNAME HERE", "YOUR TWITTER PASSWORD HERE");

// GLOBAL FUNCTIONS
class specialIncludes {

public function trunc($phrase, $url, $limit, $target) {
global $bL;

if ($target != null) {
$target = ' target="_' . $target . '"';
}

$max_words = $limit;
$phrase_array = explode(' ',$phrase);
if(count($phrase_array) > $max_words && $max_words > 0)
$phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'<a class="hellip" href="' . $url . '"' . $target . ' title="read more">...</a>';
return $phrase;

}

}

class ibd_twitter {

private $Username;
private $Password;

private $UrlTwitter = 'http://twitter.com/';
private $UrlStatus = 'http://twitter.com/statuses/';

function __construct ($user, $password) {
$this->Username = $user;
$this->Password = $password;
}


// METHOD TO MAKE TWITTER API CALL FOR THE USERS TIMELINE IN XML
function twitter_status($twitter_xml_file) {

$c = curl_init();
curl_setopt($c, CURLOPT_URL, "$twitter_xml_file");
curl_setopt($c, CURLOPT_GET, 1); //Use GET method
curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); //Use basic authentication
curl_setopt($c, CURLOPT_USERPWD, "$this->Username:$this->Password"); //Set u/p
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false); //Do not check SSL certificate (but use SSL of course), live dangerously!
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($c, CURLOPT_TIMEOUT, 5);

$response = curl_exec($c);
$responseInfo = curl_getinfo($c);

curl_close($c);

if (intval($responseInfo['http_code']) == 200) {

if (class_exists('SimpleXMLElement')) {
$xml = new SimpleXMLElement($response);
return $xml;
} else {
return $response;
}

} else {

if ($responseInfo['http_code'] == 401) {
$this->Error(4);

} elseif ($responseInfo['http_code'] == 404) {
$this->Error(5);
}

}

} // END TWITTER_STATUS


// METHOD TO GET THE USERS MOST RECENT @REPLY MESSAGES
public function replies($count) {
global $glbl;

// IF THE NUMBER OF RESULTS IS NOT SET, FORCE ONE TO BE SET
if ($count == null)
$count = 1;
else
$count = $count;

// GET THE XML FILE NAME BEING USED
$url = $this->xml_file(1);

date_default_timezone_set("America/Phoenix");
if ( $twitter_xml = $this->twitter_status($url) ) {

foreach ($twitter_xml->status as $key => $status) {

$tweet .= $this->msg_cleanup($status->user->screen_name, $status->id, $status->text, $status->created_at);
++$i;
if ($i == $count) break;

}

} else {
$tweet .= '<li class="small"><strong>Twitter seems to be unavailable at the moment</strong></li>';
}

return $this->build_twtr_msg($tweet);

} // END REPLIES


// METHOD TO CLEAN UP THE RETURNED XML DATA
private function msg_cleanup($twtr_user_screen_name, $twtr_status_id, $twtr_status_text, $twtr_status_created_at) {
global $glbl;

$dateFormat="M jS Y";
$timeFormat = "g:i a";

$twtr_post_date = date($dateFormat,strtotime($twtr_status_created_at)).' at '.date($timeFormat,strtotime($twtr_status_created_at));

// Turn links into links
$twtr_status_text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&amp;//=]+)', '<a href="\\1" target="_blank">\\1</a>', $twtr_status_text);

// Turn twitter @username into links to the users Twitter page
$twtr_status_text = preg_replace('/(^|\s)@(\w+)/', '\1<a href="http://www.twitter.com/\2" target="_blank">@\2</a>', $twtr_status_text);

// Turn #hashtags into searches
$twtr_status_text = preg_replace('/(^|\s)#(\w+)/', '\1<a href="http://search.twitter.com/search?q=%23\2" target="_blank">#\2</a>', $twtr_status_text);

// Build a url for a more link
$twtr_more_link = 'http://twitter.com/' . $twtr_user_screen_name . '/statuses/' . $twtr_status_id;

// Truncate the text if needed
$twtr_status_text = $glbl -> trunc($twtr_status_text, $twtr_more_link, 25, 'blank');

$tweet .= '<li class="small">'.$bL;
$tweet .= '<span class="small"><strong>' . $twtr_user_screen_name . ' said:</strong> </span>'.$bL;
$tweet .= '<span class="small">' . $twtr_status_text . '</span> <a class="post_time" href="http://twitter.com/' . $twtr_user_screen_name . '/statuses/' . $twtr_status_id . '" target="_blank">' . $twtr_post_date . '</a>'.$bL;
$tweet .= '</li>'.$bL;

return $tweet;

}


// METHOD TO BUILD THE TWITTER HTML TO BE RETURNED
private function build_twtr_msg($twtr_msg) {

$tweet .= '<!-- TWITTER -->'.$bL.
'<div id="twitter_div">'.$bL.
'<ul id="twitter_update_list">'.$bL;

$tweet .= $twtr_msg;

$tweet .= '</ul>'.$bL.
'<div class="follow_us"><a href="http://twitter.com/'.$this->Username.'" title="Follow me on Twitter" target="Twitter">Follow us on twitter</a></div>'.$bL.
'</div>'.$bL.
'<!-- END TWITTER -->'.$bL;

return $tweet;

}


// METHOD TO DEFINE THE XML FILE THAT IS TO BE USED
private function xml_file($xml_file) {
// List of Twitter XML files
$f[1] = $this->UrlStatus.'replies/'; // @REPLY MESSAGES FILE
$f[2] = $this->UrlStatus.'update/'; // UPDATE STATUS FILE
$f[3] = $this->UrlStatus.'friends_timeline/'; // UPDATES FROM PEOPLE YOU FOLLOW
$f[4] = $this->UrlStatus.'public_timeline/'; // PUBLIC STATUSES
$f[5] = $this->UrlStatus.'friends/'; // RETURNS UP TO 100 OF THE AUTHENTICATING USERS YOU FOLLOW WHO HAVE MOST RECENTLY UPDATED
$f[6] = $this->UrlStatus.'followers/'; // RETURNS AUTHENTICATING USER'S FOLLOWERS
$f[7] = $this->UrlStatus.'featured/'; // RETURNS A LIST OF THE USERS CURRENTLY FEATURED ON THE SITE WITH THEIR CURRENT STATUSES INLINE
// Display Error
if (array_key_exists($xml_file, $f)){
return $f[$xml_file].$this->Username.'.xml';
} else {
echo 'Invalid XML FILE';
}
} // END XML_FILE


// METHOD TO RETURN APPROPRIATE ERRORS WHEN CALLED
private function Error($Error) {
// List of Errors
$e[1] = 'Username and/or password not set';
$e[2] = 'CURL library not installed';
$e[3] = 'Post value too long/not set';
$e[4] = 'Invalid username/password';
$e[5] = 'Invalud URL for CURL request';
$e[6] = 'Invalid ID value entered';
$e[7] = 'You are not authorized to view this page';
$e[8] = 'All variables for requested function not set';
$e[9] = 'For and/or Message not set';
// Display Error
if (array_key_exists($Error, $e)){
echo $e[$Error];
} else {
echo 'Invalid Error Code';
}
} // END ERROR()


} // END IBD_TWITTER CLASS



here is the html i used to utilize the twitter class i created.




<?=$twtr->replies(1);?>



you do not need to put a number in, <?=$twtr->replies(1);?>, where "replies(1)" is, but if you do not put a number, then the script will, by default, set it to 1. you can set it to 3, 5, 100, or whatever floats your boat.

there is more built in to this class that was is really needed to make this work, but, that is cause i plan to expand on this later on, and have things like the normal user messages, status, etc. so, i hope you enjoy this class.