Posts Tagged ‘twitterapi’
December 18th, 2009
It’s a mess around the current working copy of the Twitter API, there are more issues than functionality and the whole naming and renaming is a total disaster. Today for instance I tried a simple search query to the API and kept receiving “400 Bad Request” errors without any further explenation. As soon as I changed the address from search.twitter.com to api.twitter.com/1 (I got this from Abraham Williams’ php code), which is not clearly mentioned anywhere in the Twitter docs, everything started working fine.
Twitter API: Solving Compatibility Issues

But then I realised that the from_user_id field that’s being returned is far from the correct user ID. People in the Twitter Development Talk Google group stated this problem a few times (since March 2009 I believe). It seems that the “wrong” user IDs are meant for the second version of the Twitter API, thus cannot be used before it’s released. But wait! What the hack should I do with my app now? It’s not working y’know! Here you go:
1
2
3
4
5
6
7
8
9
10
| $response = $oauth->get('search', array('q' => $search_query));
foreach($response->results as $result)
{
$id = $result->id;
$text = $result->text;
$user_name = $result->from_user;
$user = $oauth->get("users/show", array("screen_name" => $user_name));
$user_id = $user->id; // Get the old-style user ID
} |
Yeah, that’s one extra API call, but it solves things temporarily ;)
I guess there’s nothing that we could really do right now, and it’s probably true that we’ll have to rewrite some parts of our code as soon as Twitter API v2 is released, but then again, what about the apps which stopped development? Will they stop working? Tonnes of Twitter clients and web apps still use basic authentication. Twitter mentioned that everybody must use OAuth these days, and that basic auth will be closed sooner or later.
Oh well, software comes, software goes. The best thing to do right now would be sign up to Twitter API Announce Google group and follow @twitterapi. By the way, @web2feed can now use the new features of the API to retweet messages based on hashtags and build user lists ;)
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!
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!

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
October 9th, 2009
The ultimate guide to creating your own personalized twitterfeed clone! Kidding… Actualy this is just a mockup, a simple prototype, which is way too fresh for any actual use. We’ll take this forward step by step. I’m not going to give out all my sources but I’ll guide you through authentication, rss lookup, parsing, thanking for retweets, and shooting random stuff at people that mention your robot.
Create a Twitterfeed Clone in PHP

Here’s a brief list of features we will implement:
- Runs in console, no HTTP access
- Authentication via OAuth, tweeting via OAuth
- RSS lookup, parsing, forming tweets in bound of 140 characters including a postfix (hashtag or RT)
- Tweeting ‘thank you for retweeting’ to users that retweet the robot
- Following people that retweet the robot
- Acting strange on users that mention the robot
All this is going to be setup on a linux box running crond and acting every 15 minutes or so. Are you ready? Let’s do it!
Read the rest of this entry »
October 7th, 2009
A few weeks ago we discussed Automated Serverside Tweeting Using OAuth (read this before going on) and I kept looking deeper into security issues, so I found a way to make things slightly simpler. If you played with the OAuth Clients page on Twitter, you know that there are two ways of authentication – web application and client application. Also, I found out that there’s a redirect_to parameter in OAuth authentication, although we’re not going to use the original web redirects this time. If we’re talking about automatic server-side tweeting, then it should be serverside, right? So why not close down HTTP access at all?
Client Applications OAuth with the Twitter API

The downside of all this is that you’re unable to have two applications (web and client) with the same name, thus you cannot create a web application and a client application that would return the same “from” string in tweets, so you should probably divide your app in two parts, say “AppName” (web application) and “AppName Server” (client application) and feel free to link them to the same URL.
Pin based Twitter OAuth works just like the original (web) OAuth (request tokens, access tokens) but instead of returning back to a web page, Twitter gives out a Pin code that you have to input into your app in order to exchange its request token with an access token. It’s fairly simple, but unfortunatelly Abraham Williams didn’t implement this part into his Twitter OAuth php library, but we’re still going to use it, with some slight modifications.
Assuming we’ve initiated an OAuth session and stored the request tokens, here’s the original piece of code that exchanges the request tokens with the access tokens (the ones that actually give you the right to call the Twitter API via OAuth):
1
2
3
4
5
6
7
8
| $oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret']; |
The getAccessToken function is the one that posts the request to exchange request tokens for access tokens. It’s the one we have to modify to implement the pin code solution, so open up twitterOAuth.php, find the function (it’s around line 100) and make it look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| function getAccessToken($token = NULL, $pin = NULL)
{
if ($pin)
$r = $this->oAuthRequest($this->accessTokenURL(),
array("oauth_verifier" => $pin));
else
$r = $this->oAuthRequest($this->accessTokenURL());
$token = $this->oAuthParseResponse($r);
$this->token = new OAuthConsumer($token['oauth_token'],
$token['oauth_token_secret']);
return $token;
} |
What we did is add an extra parameter right after $token which is optional (not to break all the other code) – $pin. Now in terms of OAuth, the pin code is called the OAuth verifier (oauth_verifier), we add it as a parameter to the oAuthRequest call, which then wraps it up into a signed HTTP request to Twitter containing the verifier (line 114).
Back to our script. The rest is simple, just change the getAccessToken call to look like this:
$request = $oauth->getAccessToken(NULL, $pin);
Where $pin would be the pin code provided by Twitter during OAuth. Now, move all your scripts into a secured place, preferably not accessible through HTTP, write a few modifications in order to pass parameters through command line (use $argv[n] instead of $_GET[...]). Here’s a tip on how it should look to get you on the right track. All the work is done through SSH:
# php oauth.php register
Request tokens aquired, proceed to this link: https://twitter.com/oauth/authorize?oauth_token=whatever
# php oauth.php validate 123456
Access tokens stored, identified as @twittername
# php oauth.php reset
Access tokens deleted
That’s the way my script works and voila! No more HTTP! Hmm.. TwiBots? ;)