A Twitbot Using OAUTH

The story line:

I am a late comer to Twitter. My first objective was to twit the latest posts in forums I administer. I am webmaster of a Muslim portal. The portal contains several forums. Stammy script from Paul Stammatiou with some simple modifications was my solution for automatically twitting latest posts from forums to Twitter.

I was idly sitting down happy with my code twitting latest forum posts in Twitter. I was announcing in the forums about Twitter services, and seemed to be happy ever after, until one morning looking around Twitter’s website  found out that basic authentication was scheduled to be fased out from August 16th, 2010.

When checking into the docs about new authentication based on OAUTH I became simply desperate. What? I need to install OAUTH library using PECL, and blah blah blah?  Day by day, I got more and more confused, until one afternoon, two days ago, I found out Abraham Williams ‘s library. I didn’t need to install Php-Devel, etc. Those that have are learning to install OAUTH with PECL, know what I am talking about… Then I discovered Abu Ashraf Masnun ‘s website with simple solutions. I am no PHP programmer, and I have little time, due to my professional life, so complicated solutions are not my favourite adoes. So here’s how I did it!

The solution:

Firstly and foremost you need access tokens ( a consumer key and a secret key). These are obtained in Twitter’s developpers page and at first go. I wil not dwelve into howto, as whoever is interested just needs to google to find out how to get these key tokens. With this process, your website’s folder, say twitbot, will have your due authorizations from Twitter to automatically post there with read/write permissions. Again I will not explain here how to do it. The process will provide you with total four keys: consumer key, consumer secret, access key and access secret.

Download Abraham’s latest files and upload twitteroauth folder into your website’s above mentioned twitbot folder and from where you obtained due read/write permissions from Twitter as again I wrote above.

Write a secrets.php file with following code:


<?php
$consumer_key = "OBTAINED FROM TWITTER";
$consumer_secret = "OBTAINED FROM TWITTERY";
$access_key = "OBTAINED FROM TWITTER";
$access_secret = "OBTAINED FROM TWITTER";
?>

Upload this file into twitteroauth folder in your website.

chmod 644 the whole folder.

Next download the zipped file from Stammatiou’s website.

Upload parse.php file into your twitbot folder. In my case I had to change the following in parse.php file (my forums are in portuguese language):


var $default_cp = 'ISO-8859-1';
var $cp = ' UTF-8';

$cp is UTF-8 because this is the default charset of Twitter. $default_cp is ISO-8859-1because of my forums charset.

Next write your index.php file as follows with edits as shown:

<?php
/*
RSS to Twitter v0.1
by paul stamatiou
of http://paulstamatiou.com
based on code from
http://morethanseven.net/posts/posting-to-twitter-using-php
mods and adaptation from Tayeb Habib https://redacacia.wordpress.com and http://myciw.org
*/
include('parse.php');
require_once('twitteroauth/twitteroauth.php');
require_once('twitteroauth/secrets.php');

 

$connection = new TwitterOAuth ($consumer_key ,$consumer_secret , $access_key , $access_secret );
$newpost=4;
while ($newpost>=0)
{
$feed = "YOUR RSS FEED LINK"; //the feed you want to micro-syndicate
$rss = new lastRSS;
if ($rs = $rss->get($feed)){
$title = $rs[items][$newpost][title];
$url = $rs[items][$newpost][link];
} else { die('Error: RSS file not found, dude.'); }
$tiny_url = file_get_contents("http://tinyurl.com/api-create.php?url=" . $url);
$parameters = array('status' => $title." ".$tiny_url);

 

$connection->post('statuses/update',$parameters);
$newpost--;
}
?>

As you will note, the code parses latest 5 posts and twits or retwits into Twitter. When retwiting Twitter recognises duplications and will not upload the twit. The twitter scripts are sufficiently clever to do.

You can manually run index.php or automatize using cron to run it say every so many minutes.

My twitbot‘s results can be viewd at:

http://www.twitter.com/myciwportal

I hope this post will help those are at this moment seeking OAUTH Twitter solutions, as I was two days ago, and solve the OAUTH puzzle.

My special thanks are due to Stammatiou (belately for my first code and aptation of latest code), Abraham and Masnun.

—————
An addenda August 21st, 2010:

There has an issue with my script since August 15th. It was not updating.

I wrote in Masnun’s blog about this issue. I thought that the fact my script not updating had to do with Abraham’s library, or there were new Twitter arrangements, since Twitter was officially bringing down Basic authentication.

On visiting Masnun’s blog I read Abraham’s post in response to Paolo. I added to my script the following suggestion from Abraham to Paulo:

print_r($connection->post(‘statuses/update’, array(‘new status text here’));

and got the following error:

stdClass Object ( [request] => /1/statuses/update.json [error] => Invalid / used nonce )

I searched information on nonce error. and I learnt that there may be problems with timestamp.

Hence I ran the command in my server:

date

and in fact my server was 13 minutes behind.

Now twitter allows up to 5 minutes time difference, no more. So I ran the following command:

ntpdate pool.ntp.org

More on ntp servers at:

http://support.ntp.org/bin/view/Servers/WebHome

My server was now in sync with ntp time servers and most likely with twitter. I ran my script and there at twitter account my latest feeds from my rss feeder were being diaplaed.

I have now established cron in my server to run every night and to put it into sync with ntp pool of servers.

Servers do lag behind in time. That’s what was was happening to my server.

May be this infomation may be useful to those users of my script and twitter account not being updated. I suggesting changing in the script the following code:

$connection->post(‘statuses/update’,$parameters);

with:

print_r ($connection->post(‘statuses/update’,$parameters));

So every feed updating will be shown on your terminal screen and respective results.

Advertisements

About Tayeb

Electronics engineer, part-time webmaster and owner of "Aliatron", a tech-oriented company registered in Portugal and Mozambique.
This entry was posted in Information Technolody, Internet of Things and tagged , , , , , , , , , , . Bookmark the permalink.

26 Responses to A Twitbot Using OAUTH

  1. maSnun says:

    This is a very cool implementation. BTW, Abraham Williams, not Willson. Thanks.

    • thabib says:

      Welcome to my blog dear Abu Ashraf. Thanks for pointing out the typo. I am always relating Abraham’s name with his most probable family origins in Wales, United Kingdom, and ended up with Wilson instead of Williams.

      I have edited the post and changed his name as you may see. Finding out the typo, shows also that you honoured me with reading my post. Thanks Abu Ashraf for reading the post.

      I hope these simple ideas of breaking OAUTH puzzle will help all those that are interested.

      I must congratulate you for your geneorosity in sharing knowledge. After reading what you have done, and on Abraham and what he does, I became inspired in starting this often postponed blog. I wanted to do it for a long time, a place on the Internet where I could share the tech things I do.

      Did you read my post on why the name redacacia?

      Tayeb

  2. ajaxified says:

    Thank You very much for this tutorial. However Abraham Williams ‘s library ie: twitteroauth.php is not closed with “?>” . That drove me crazy for a few minutes 🙂
    Anyway i took the liberty of putting everything together and releasing ready to go product including all the credits for newbies and not only RSS to Twitter API app I hope that’s OK with You.
    Paul.

  3. Pingback: Posting from an RSS feed to twitter using OAuth « mabujo

  4. Rob Q. says:

    I receive the following message when authorizing my twitter acct to use the script (it does it but I get the error message) and then a second time when I’m trying to send a tweet with index.php. Any ideas what I can do to remedy?

    /twitteroauth/twitteroauth.php on line 137

  5. Rob Q. says:

    Sorry – full error message here:

    Fatal error: Call to undefined function json_decode() in /www/xxxxxx/public_html/tweets/twitteroauth/twitteroauth.php on line 137

  6. Tayeb says:

    Welcome to my blog. It sounds to me to be an error of inexistence of json function in your server’s PHP. What’s your version of PHP?

  7. Rob Q. says:

    It’s a hosted solution at http://www.enginehosting.com and I believe the current version is PHP 5.1.6

  8. vahn says:

    Hi Tayeb,

    I’ve been fighting with this thing for over a week and still couldnt find the answer on how to implement twitter oauth.

    I kept getting this response

    stdClass Object ( [request] => /1/statuses/update.json [error] => Invalid / used nonce )

    Yes, I get all four credentials. consumer key,secret,token and token secret.
    I did include the parse.php thing

    and I notice you mention about time difference on server (that I do not understand).

    how to change the time on server? I’m currently using shared hosting though..

    also, I notice different API urls on twitteroauth.php
    ( http://twitter.com/oauth_clients uses https://api.twitter.com/xxxxx,
    while http://dev.twitter.com uses https://api.twitter.com/xxxxxx). which one should i use?

    I’m so frustrated… I just want to update my tweet on a periodical basic..

    thanks in advance

    • Tayeb says:

      Welcome to the blog vahn. As I have written here, I also had the same problem.

      But as I have access to my server’s shell I could issue the command to update the server time.

      You may need to ask the techies of your ISP to do it. This is really the problem.

  9. Ryan says:

    This is awesome. Thanks!

  10. Matteo says:

    Thank you so much, I had the same issue and I was able to fix it by synchronizing my server time (it was 3500 seconds after the ntpdate server)

  11. Hi there,
    Can anyone help.. I’m a bit of a noob.. not sure what this means.
    http://public.cameronbetts.com/NPStuff/index.php

  12. Paul says:

    Tayeb, firstly, great work 🙂

    I’m trying to put together a Twitter feed or shortened URLs that comes from an RSS feed of a custom Google News search.

    Ok?

    I’ve got the twitter feed working, but there is a problem if/when you click on one of the tinyurl-shortened links.

    For example:

    This is one of the shortened URLs – http://tinyurl.com/38sj85m

    It expands to this – http://www.google.com/url?sa=t&fd=R&usg=AFQjCNF4tJGwAbnSOagm7DhnYT6QHJDQJQ&url=http://www.theroar.com.au/2010/11/18/gallop-unsurprised-by-tigers-roar-at-gws-giants/

    If I remove everything from the start up to “url=”, then the article correctly displays. However, with the Google bit at the front it results in a “redirect” error.

    I don’t know enough about this stuff to know if it’s Google, TinyURL, or these scripts that are causing the problem.

    My preference would be to remove the Google bit of the URL, leaving me with just the actual article.

    I’m using rss2html.php to pull in the stream, and then another php script (custom one of Tayeb’s original) to post to Twitter.

    ANY suggestions are more than welcome

    • Tayeb says:

      Welcome to my blog dear Paul. It seems the problem lies with the way you pull the rss feed. The URL being generated is what tinyurl picks from your rss feed. You need to sort out the feeds and check if they contain the urls you mention.

      • june says:

        @tayeb: i’m having the same problem as paul. I’m changing the parse.php using magpie and i can parse the g00gle news rss just fine and and the link is working. But the problem is it will only tweet 1 news no more than that. Any ideas how to tweet more than 1 at a time (i.e 5 tweets)?

        Thanks

      • Tayeb says:

        No idea unless I test your code. Do you output all of tweets? May be google is limiting the number of tweets?

  13. Tim says:

    Hi Thabib,

    I dropped by, and implemented the script, and it’s working well 🙂

    Question:

    For instance I have 5 twitter accounts, and would like to publisch different RSS feeds to to twitter account 1, 2, 3 etc. I would like to publisch with one “application” to all those twitter accounts, is that possible?

    This since I have already my access key and secret key generated by creating the application.

    Can I make 5 seperate folders on my server, put the script in, and just change the cunsumer key and secret? and posting “from” my only registrered application?

    Point is that I would like to post from one application “name” since each twitter post says: about 2 hours ago via “application name”. Otherwise I have to create an application for each twitter account, and should change the name because twitter don’t want “double” application names.

    Twitterfeed does do the same thing,… posting for every one from one application name called “twitterfeed”.

    Also another question,… can I parse multiple RSS feeds from one index.php:

    $feed = “YOUR RSS FEED LINK”; //the feed you want to micro-syndicate
    $rss = new lastRSS;

    Hopefully someone can help me,..

    Regards,

    Tim

  14. Tayeb says:

    Welocme to my blog.

    Well actually all the things you want to do you may be able to do. You need to do a bit of writing of code to do what you want to do.

    The best approach is to solve each problem one by one.

    Let me know if you need any specific hint.

    Tayeb

  15. Pingback: Fixing: Fatal Error Call To Undefined Function Json_decode | RedAcacia

  16. june says:

    Hi Tayeb:

    I’m having trouble posting g00gle news rss to twitter because last rss (parse.php) will make the link broken (you can click them but google will say not found) and title broken also. But if I use magpie rss it will parse the g00gle news rss just fine there’s only one problem…

    it will only post one news at a time. unlike last rss where it will post the way we set at the $newpost= value.magpie ignores it completely.

    i hope you can help me.

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s