Posts Tagged ‘php’

Twitter Robot in PHP: Twibots Draft

January 25th, 2010

As I promised quite some time ago, I’m putting out a draft of the Twitter Robot I wrote. Make sure you read Create Your Own Automated Twitter Robot in PHP before going on. The current functionality is as follows:

  • Tweets around the clock
  • Tweets from RSS feeds, supporting prefix and postfix text (for adding hashtags)
  • Retweet via the Twitter Search API and build conversation lists
  • Shoot random sentences at users who mention you, thank them for retweets
  • Control your robot via your own Twitter account by sending him direct messages
  • All this is Twitter OAuth powered, no password required
  • Such robots are called Twibots

Create Your Own Twitter Robot in PHP

Create Your Own Twitter Robot in PHP

Now, before downloading the code, I have to warn you that it’s completely unorganized. The code is horrible, comments are awkward, the database being used is SQLite (just for the fun of it) and it’s very very glitchy. Be prepared for Twitter suspending your account for ’strange activity’ and use this at your own risk, don’t run here blaming me for that ;) I also suggest you’d contact Twitter to get your IP addresses and Twitter account white-listed before you start, especially if you plan to tweet very often (which I wouldn’t recommend). Use this at your own risk, and please keep my copyrights and preferably the OAuth application IDs.

Download: here (version 0.1)

Operation Instructions.. To say the truth it’s pretty tough, no web interface, not buttons, no config files. There are a bunch of files there, some of them useless. There’s the Snoopy class for reading and parsing RSS, there’s the Twitter OAuth class, and two core php files – cron.php and oauth.php. Open up cron.php, there are some comments and examples there. Make sure you get your own bit.ly API key and secret. Also make sure you get a connection with the twibots.sqlite database which has a couple of empty tables. Those will be used for tokens and dump data for unrepeated tweets.

Once you’re done configuring, use the command-line php in order to make it work. It goes something like this:

# php cron.php oauth register
# Please browse to https://twitter.com/…
# php cron.php oauth validate 123465
# Authentication successful, greetings @ev ;)

# php cron.php random
# tweeting a random RSS feed …

# php cron.php reply
# sending replies…

# php cron.php dm
# reading direct messages

# php cron.php retweet
# retweeting…

You’ll have to put that in your crontab file and launch by schedule. Don’t run them too often though, as Twitter doesn’t like flooding, especially from newly created accounts. Any questions or suggestions are welcome in the comments below, but please, don’t tell me the code is horrible, I know it is, and I wouldn’t have posted it if you didn’t ask ;) Cheers!

Permalink, comment (6) or share:
  • Twitter
  • Digg
  • Facebook
  • del.icio.us
  • FriendFeed
  • Technorati
  • Google Bookmarks
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • StumbleUpon
  • Print
  • email

The Twitter OAuth PHP Class Gets Even Better

December 14th, 2009

Or perhaps simpler?.. Together with the Twitter API itself, the TwitterOAuth PHP class (the one by Abraham Williams) is being updated too! According to GitHub the latest changeset was commited on December 3rd so yeah, I tried to take a look at what’s going on there a few days ago and was quite disapointed. Disappointed with the fact that all my previous code was broken without giving any reason.

Just like everybody else, I never read the readme or other documentation files so I dug straight into the class code and examples. Soon after I realized that the new changes were not that bad, so instead of the usual 5 lines of code, I shortened it up to only one. I stopped worrying about parsing XML or JSON, converting them to objects, and I stopped typing in the full address for Twitter API calls. Abraham did all that for us, so all we have left is:

1
2
3
$credentials = $oauth->get("account/verify_credentials");
if ($oauth->http_code == 200)
	echo "Hey there, {$credentials->screen_name}!";

I’m not going to publish all the new features and stuff (read about them at GitHub), but hey, this is quite sweet isn’t it? The only drawback was having to rewrite some parts of the code I wrote for the past few months (the Twitter Robots stuff), but I guess that’s partly my bad as it’s not as organized as it should be. That’s the main reason why I’m not publishing the whole code here yet, have a lot of cleaning up to do ;)

Meanwhile you may take a look at this buddy: @web2feed. I turned off the auto-replies because they were getting quite annoying, and I’ve added a couple of feeds to the big list, oh and it’s DM controlled too!

Permalink, comment (5) or share:
  • Twitter
  • Digg
  • Facebook
  • del.icio.us
  • FriendFeed
  • Technorati
  • Google Bookmarks
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • StumbleUpon
  • Print
  • email

Facebook API Experiments: Twitter Tags

November 17th, 2009

For quite some time now I’ve been dreaming about getting into the Facebook Platform (API, Markup Language, etc) but haven’t had good enough reasons to do so. One good friend of mine Timothy gave me those reasons not so long ago and guess what! I came up with my very first Facebook App! It’s still in the sandbox, don’t rush searching for it in the applications database. I’m not going to share any code as it’s all clumsy but I do want to share some screenshots and my first experience with the Facebook API.

My Very First Facebook App

My Very First Facebook App

One very interesting thing about the API is the testing console, where you could run any Facebook API methods, very useful for debugging. Interface design is very catchy too, with the new Facebook Markup Language and the FBML testing console, so quick and robust! Pepole are still asking for form elements extensions though, such as the checkbox or option – it seems that they come out buggy as fb:editor-custom.

Anyways, the first thing that came into my mind is adding a Twitter Tags tab to a profile or fan page, so I used the Foller.me API and within a few hours I managed to get a fully working (or not) canvas application tab. I’m surprised by how well-written the Facebook PHP Client Library is. All the methods are explained in the code comments and do exactly what they’re expected to. The Facebook Markup Language takes care of application settings, private areas (app configuration, etc) and everything else. The overall Facebook Developers Documentation is okay, I’ll give that an 8 out of 10 and I like them running the MediaWiki software ;) Here are some screenshots of my application:

Still not sure where this is going but Timothy had some great ideas about custom Facebook Apps. I guess a release of the Twitter Tags application would be handy for some profiles (or at least for some more experience), so I might push that forward in the near future and file an “add to facebook database” request to go public. After that we’ll aim for something bigger.

Permalink, comment (2) or share:
  • Twitter
  • Digg
  • Facebook
  • del.icio.us
  • FriendFeed
  • Technorati
  • Google Bookmarks
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • StumbleUpon
  • Print
  • email

Google Docs API: Client Login with PHP and Curl

October 22nd, 2009

A few days ago I started looking deeper into the Google Code APIs and threw a few experiments using the Google Documents List Data API. Unfortunately, the only library they have for the third version of their protocol is written in Java. There is a PHP wrapper for the first version of the protocol, but it totally depends on the Zend Framework. Here’s a little code snippet for logging into a Google Docs account (writely) using ClientLogin with Curl and PHP. The Auth string is stored into the $auth variable for later use.

Playing with the Google Docs API

Playing with the Google Docs API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Construct an HTTP POST request
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
    "accountType" => "HOSTED_OR_GOOGLE",
    "Email" => "yourgoogle@email.com",
    "Passwd" => "yourgooglepassword",
    "service" => "writely",
    "source" => "your application name"
);
 
// Initialize the curl object
$curl = curl_init($clientlogin_url);
 
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 
// Execute
$response = curl_exec($curl);
 
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
 
echo "The auth string is: " . $auth;

ClientLogin assumes you login once and use the auth string for all on-going requests (more info: ClientLogin – Google Code). Here’s a simple example of how to retrieve some data from a Google Docs account, show filename, author and file type. Make sure the simplexml php extension is installed and activated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
    "Authorization: GoogleLogin auth=" . $auth,
    "GData-Version: 3.0",
);
 
// Make the request
curl_setopt($curl, CURLOPT_URL, "http://docs.google.com/feeds/default/private/full");
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
 
$response = curl_exec($curl);
curl_close($curl);
 
// Parse the response
$response = simplexml_load_string($response);
 
// Output data
foreach($response->entry as $file)
{
	echo "File: " . $file->title . "<br />";
	echo "Type: " . $file->content["type"] . "<br />";
	echo "Author: " . $file->author->name . "<br /><br />";
}

It seems though that Google Docs is purely for documents (spreadsheets and presentations) but not for actual files, as a JPEG I uploaded turned into a text/html type. It opens up in the text editor when viewing in Google Docs, and the nearest-to JPEG export format is PDF (just like all the other documents). So I guess there’s no way of reading and manipulating the raw image as if I would read and manipulate a file.

I came across a cool website which I believe the Googlers have made – Data Liberation:

Users should be able to control the data they store in any of Google’s products. Our team’s goal is to make it easier for them to move data in and out.

I’m working on a little project that involves image (and file) hosting, so the products I’m interested in are Google Docs and Picasa Web Albums. It seems that none of the two make it possible to store and work with files as if it was a flash disk or an FTP server. Google Docs is the closest one but there’s a huge limit on what kind of files you can upload and store. Picasa on the other hand is good for image storing, but the only way to export a set of images is to use their desktop software and Picasa Web, and of course no actual control over the files (edit, delete) via their Picasa Web API. If only it were a little bit closer to Amazon S3 …

Oh and you should probably use OAuth or AuthSub when working with Web Applications and Google APIs but anyways, this was just a quick example.

Permalink, comment (11) or share:
  • Twitter
  • Digg
  • Facebook
  • del.icio.us
  • FriendFeed
  • Technorati
  • Google Bookmarks
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • StumbleUpon
  • Print
  • email

Automated Twitter Bot in PHP: Remote Control

October 14th, 2009

Hope you’ve all read the first part of this series – Create Your Own Automated Twitter Robot in PHP and got your own prototype up and running. Today we’ll be adding a remote control feature to our robot. It’ll be working through direct messages and running in crontab every 5 minutes or so. You can extend this as far as you want (adding retweet capabilities, follow/unfollow, direct messaging other people, etc) but we’ll stick to simple status updating in this post, might cover the others later on.

Let's Build Smart, Intelligent TwiBots!

Let's Build Smart, Intelligent TwiBots!

So, direct messaging the robot’s twitter account with the text “update status text” would make him tweet “status text” to the public timeline. Remember we had three branches of actions – feed, reply and rthx? Let’s add a fourth one and call it dm. This branch will simply scan through the account’s latest direct messages, find those sent by you and tweet them out loud. Again, as I said in the first tutorial, this is simply a prototype, just to get things up and running. You’ll have to polish this off for actual use and yeah, storing the access keys, dm_since_id, etc on disk is not such a good idea, you should probably use the database. Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// The id of the latest read direct message will be stored in
// a file called dm_since_id, just like mentions_since_id
// in the previous examples
$since_id = @file_get_contents("dm_since_id", true);
if ($since_id > 0) { }
else { $since_id = 1; }
 
// Retrieve the direct messages into $dms and parse the xml string
$dms = $oauth->OAuthRequest("http://twitter.com/direct_messages.xml" , 
	array("count" => 10, "since_id" =>  $since_id), "GET");
$dms = simplexml_load_string($dms);
 
// If it's valid read the latest id and store into dm_since_id
if (count($dms))
{
	$last_id = ($dms->direct_message[0]->id > $since_id) ? 
		$dms->direct_message[0]->id : $since_id;
	file_put_contents("dm_since_id", (string)$last_id, FILE_USE_INCLUDE_PATH);
}
 
// Loop through the messages
foreach ($dms->direct_message as $dm)
{
	// Make sure you're the sender
	$sender = $dm->sender->screen_name;
	if ($sender == "kovshenin")
	{
		// What should we do
		if (strtolower(substr($dm->text, 0, 7)) == "update ")
		{
			// Construct the message, tweet and wait a few seconds
			$message = substr($dm->text, 7);
			$oauth->OAuthRequest('https://twitter.com/statuses/update.xml', 
				array('status' => $message), 'POST');
			echo "Tweeting: " . $message;
			sleep(rand(5,30));
		}
 
		// Add more actions here
	}
}

Read through the comments in the code and you should be able to get the idea. The direct messages Twitter API method is documented here. Test it out a few times through your SSH client by sending a direct message to your robot with the text “update Updating my status” or whatever, then run:

# php robot.php dm
Tweeting: Updating my status

If everything works fine you might as well add the action to your cron, say 5 minutes:

*/5 * * * * php /home/youruser/twibots/robot.php dm

And done! Your robot is now remote controlled. A few suggestions to more advanced remote controlled operations would be:

  • Retweet capabilities by regular expression
  • Adding and removing feed sources, prefixes and postfixes
  • Turning on and off other operations (feeding, replying, rthxing)
  • Adding people to “reply ignore lists” (ones that talk to your robot too much)
  • Adding people to “rthx ignore lists” (ones that retweet too much, twitterfeed for instance)

I think that’s enough for a start, oh and please don’t build dumb and annoying spammish robots. Stick to intelligent, smart twibots! ;)

Upd. Continued: Twitter Robot in PHP: Twibots Draft

Permalink, comment (5) or share:
  • Twitter
  • Digg
  • Facebook
  • del.icio.us
  • FriendFeed
  • Technorati
  • Google Bookmarks
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • StumbleUpon
  • Print
  • email