Twitter bot in Empathy
By using an empty Empathy application as the glue (and using some of the wrapper code around Pheantalk for queues), we can easily create a twitter bot that favourites tweets for a given stream and thusly attacting attention to our own profile. The composer.json looks like this:
{
name: "newblog",
description: "A new blog",
require: {
mikejw/elib-base: "dev-develop",
pda/pheanstalk: "dev-master",
fennb/phirehose: "dev-master",
abraham/twitteroauth: "dev-master",
monolog/monolog: "1.13.1"
},
minimum-stability: "dev",
autoload: {
psr-0: {
HFSBot: "src/"
}
}
}
The key libraries being pheanstalk, phirehose and twitteroauth. The following class is used for capturing tweets and pushing them to our queue:
<?php
namespace HFSBot;
use Empathy\ELib\Queue;
class Filter extends \OauthPhirehose
{
private $q;
private $enq_count;
public function __construct(
$token,
$secret,
$method = \Phirehose::METHOD_SAMPLE,
$format = self::FORMAT_JSON
) {
parent::__construct($token, $secret, $method, $format);
$this->q = new Queue('127.0.0.1', 'hose');
$this->enq_count = 0;
}
public function enqueueStatus($status)
{
$data = json_decode($status, true);
if ($this->enq_count < ELIB_PHIREHOSE_QUEUE_LIMIT &&
is_array($data) &&
isset($data['user']['screen_name'])) {
$enqueued = [
'enq_count' => $this->enq_count,
'data' => $status,
'captured' => time()
];
$this->q->put($enqueued);
$this->enq_count++;
}
}
}
The functions in the following class process the individual tweets and create the API call that favourites each one (pending rate limiting):
<?php
namespace HFSBot;
use Abraham\TwitterOAuth\TwitterOAuth;
class Entry
{
public static function prepare() {
//
}
public static function receive($entry)
{
$entry_ob = json_decode($entry);
if (is_object($entry_ob)) {
$connection = new TwitterOAuth(
ELIB_CONSUMER_KEY,
ELIB_CONSUMER_SECRET,
ELIB_OAUTH_TOKEN,
ELIB_OAUTH_SECRET
);
$id = $entry_ob->id;
try {
$connection->post('favorites/create', ['id' => $id]);
if ($connection->getLastHttpCode() == 200) {
// Tweet posted succesfully
} else {
// Handle error case
}
} catch (\Exception $e) {
//
}
}
}
}
In order to run the bot the following scripts can be run using screen to easily put the processes in the background. Like so:
$ cd script $ screen php hose.php $ screen php worker_hose.php
The last thing to do is make sure that you have populated the API key fields in elib.yml to match those reigstered with your twitter app and set the STREAM_FILTER setting with your filter array. That's it. Happy follower harvesting. (This code can be checked out from github at https://github.com/mikejw/hfsbot.)