Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iskigow/1504007 to your computer and use it in GitHub Desktop.
Save iskigow/1504007 to your computer and use it in GitHub Desktop.
Twitter autoresponder bot
Twitter autoresponder bot
=========================
By Daniel15 (dan.cx)
This is a very simple Twitter autoresponder bot. It requires PECL OAuth extension to be installed (run "pecl install oauth", or if on Windows, grab php-oauth.dll. If using cPanel you can install it via WHM). The authentication is designed for command-line usage, it won't work too well via a web browser. You'll have to sign up for an application on Twitter's site to get the consumer key and secret.
Could be modified to be more advanced (match regular expressions to answer questions, etc.)
By Iskigow
Added Match regular expressions...
#!/usr/bin/php
<?php
date_default_timezone_set('America/Campo_Grande');
require('twitterautoreply.php');
// Consumer key and consumer secret
$twitter = new TwitterAutoReply('******', '************************');
// Token and secret
$twitter->setToken('********-*******************', '******************');
$twitter->addReply('"over 9000"', 'WHAT?! NINE THOUSAND?!', "/(over) (9000)/i");
$twitter->addReply('"over nine"', 'WHAT?! NINE THOUSAND?!', "/(over) (nine) (thous[a]+nd)/i");
$twitter->addReply('"mais de 8000"', 'O QUE?! MAIS DE OITO MIL?!', "/(mais) (de) (8000)/i");
$twitter->addReply('"mais de oito mil"', 'O QUE?! MAIS DE OITO MIL?!', "/(mais) (de) (oito) (mil)/i");
$twitter->run();
?>
<?php
// Twitter autoreply
// By Daniel15 <http://dan.cx/>
// Modified by Iskigow
class TwitterAutoReply
{
// Constants
const SEARCH_URL = 'http://search.twitter.com/search.json?q=%s&since_id=%s';
const UPDATE_URL = 'https://api.twitter.com/1/statuses/update.json';
const VERIFY_URL = 'http://api.twitter.com/1/account/verify_credentials.json';
const REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token';
const ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token';
const AUTH_URL = 'https://api.twitter.com/oauth/authorize';
// Variables
private $_replies = array();
private $_regexp = 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 addReply($term, $reply, $regexp)
{
$this->_replies[$term] = $reply;
$this->_regexp[$term] = $regexp;
}
public function run()
{
echo '========= ', date('Y-m-d g:i:s A'), " - Started =========\n";
// 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 the basic terms
echo 'Performing search for "', $term, '"... ';
$search = json_decode(file_get_contents(sprintf(self::SEARCH_URL, urlencode($term), $since_id)));
echo 'Done, ', count($search->results), " results.\n";
// Store the max ID
if ($search->max_id_str > $max_id)
$max_id = $search->max_id_str;
// Filter if the tweets are thouse we search for.
$tweetsValids = $this->tweetsValid($search->results, $term);
// Now let's go through the results
foreach ($tweetsValids as $tweet)
{
$this->sendReply($tweet, $reply);
}
}
file_put_contents('since_id', $max_id);
echo '========= ', date('Y-m-d g:i:s A'), " - Finished =========\n";
}
private function tweetsValid($tweets, $term) {
echo "===> Matching Tweet...\n";
$tweetValid = array();
$index=1;
foreach ($tweets as $tweet) {
if (preg_match ($this->_regexp[$term], $tweet->text) > 0) {
echo "===> Match...\n";
$tweetValid[$index++]=$tweet;
}
}
return $tweetValid;
}
private function sendReply($tweet, $reply)
{
try
{
echo '@', $tweet->from_user, ' said: ', $tweet->text, "\n";
$this->_oauth->fetch(self::UPDATE_URL, array(
'status' => '@' . $tweet->from_user . ' ' . $reply,
'in_reply_to_status_id' => $tweet->id_str,
), OAUTH_HTTP_METHOD_POST);
}
catch (OAuthException $ex)
{
echo 'ERROR: ' . $ex->lastResponse;
die();
}
}
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);
echo 'Please navigate to the following URL to get an authentication token:', "\n";
echo self::AUTH_URL, '?oauth_token=', $request_token_info['oauth_token'], "\n";
echo 'Once done (and you have a PIN number), press ENTER.';
fread(STDIN, 10);
echo 'PIN Number: ';
$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);
echo 'Success, ', $access_token_info['screen_name'], ' has authorized the application. Please change your setToken line to something like the following:', "\n";
echo '$twitter->setToken(\'', $access_token_info['oauth_token'], '\', \'', $access_token_info['oauth_token_secret'], '\');';
die();
}
public function testTweet()
{
$this->_oauth->fetch(self::UPDATE_URL, array(
'status' => 'Test from TwitterAutoReply',
), OAUTH_HTTP_METHOD_POST);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment