Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created August 20, 2012 15:15
Show Gist options
  • Save cam-gists/3405084 to your computer and use it in GitHub Desktop.
Save cam-gists/3405084 to your computer and use it in GitHub Desktop.
PHP: Twitter Auto Reply
<?php
class TwitterAutoReply
{
// Constants
const SEARCH_URL = 'http://search.twitter.com/search.json?q=%s&since_id=%s';
const UPDATE_URL = 'https://twitter.com/statuses/update.json';
const VERIFY_URL = 'http://api.twitter.com/1/account/verify_credentials.json';
const REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token';
const ACCESS_TOKEN_URL = 'https://twitter.com/oauth/access_token';
const AUTH_URL = 'http://twitter.com/oauth/authorize';
// Variables
private $_replies = array();
private $_oauth;
// Methods
public function __construct($consumer_key, $consumer_secret)
{
$this->_oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$this->_oauth->disableSSLChecks();
}
public function setToken($token, $secret)
{
$this->_oauth->setToken($token, $secret);
}
public function addReplies($term, $replyarray)
{
// Find the total number of rows in the array
$replycount = count($replyarray);
// Offset for array's zero val
$replycount--;
// Generate a random number as key for the array
$rand = rand(0,$replycount);
// Plug in the key & add that reply!
$this->_replies[$term] = $replyarray[$rand];
}
public function run()
{
// Get the last ID we replied to
$since_id = @file_get_contents('since_id');
if ($since_id == null)
$since_id = 0;
// This will store the ID of the last tweet we get
$max_id = $since_id;
// Verify their Twitter account is valid
if (!$this->verifyAccountWorks())
{
// Get a request token and show instructions
$this->doAuth();
die();
}
// Go through each reply
foreach ($this->_replies as $term => $reply)
{
$search = json_decode(file_get_contents(sprintf(self::SEARCH_URL, urlencode($term), $since_id)));
// Store the max ID
if ($search->max_id_str > $max_id)
$max_id = $search->max_id_str;
// Now let's go through the results
foreach ($search->results as $tweet)
{
$this->sendReply($tweet, $reply);
}
}
file_put_contents('since_id', $max_id);
}
private function sendReply($tweet, $reply)
{
$this->_oauth->fetch(self::UPDATE_URL, array(
'status' => '@' . $tweet->from_user . ' ' . $reply,
'in_reply_to_status_id' => $tweet->id_str,
), OAUTH_HTTP_METHOD_POST);
}
private function verifyAccountWorks()
{
try
{
$response = $this->_oauth->fetch(self::VERIFY_URL, array(), OAUTH_HTTP_METHOD_GET);
return true;
}
catch (Exception $ex)
{
return false;
}
}
private function doAuth()
{
// First get a request token, and prompt them to go to the URL
$request_token_info = $this->_oauth->getRequestToken(self::REQUEST_TOKEN_URL);
fread(STDIN, 10);
$pin = trim(fread(STDIN, 10));
// Now let's swap that for an access token
$this->_oauth->setToken($request_token_info['oauth_token'], $request_token_info['oauth_token_secret']);
$access_token_info = $this->_oauth->getAccessToken(self::ACCESS_TOKEN_URL, null, $pin);
die();
}
public function testTweet()
{
$this->_oauth->fetch(self::UPDATE_URL, array(
'status' => 'Test from TwitterAutoReply',
), OAUTH_HTTP_METHOD_POST);
}
}
/****************************************
EXAMPLE USAGE
*****************************************/
date_default_timezone_set('America/New_York');
// Consumer key and consumer secret
$twitter = new TwitterAutoReply('*', '*');
// Token and secret
$twitter->setToken('*', '*');
// queue up the potential responses in $replyarray
$replyarray = array('reply1','reply2','reply3');
// add the replies
$twitter->addReplies($searchkey, $replyarray);
// execute against twitter api
$twitter->run();
///Requires the pecl oauth extension. Best when run from the command-line (cron job is a nice way to go about it).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment