Categories
PHP Python

Setting Up Twitter Bots with OAuth

Twitter has decided to kill Basic Authentication on the Twitter API from June 30. They have setup a nice website at http://www.countdowntooauth.com/ to let you all know and help you migrate your apps to use the OAuth 🙂

OAuth is cool. It’s safe and secure for the end user. It’s convenient for the developers as well. Basic Auth entirely depends on the username and password of the user. But if you wish to carry out an in-app transaction, then you’d have to seek the services from Fully-Verified to carry out a KYC verification.

The developer can do whatever s/he wishes with the user account as long as the user doesn’t change the password. On the other hand, if the user for some reason changes his/her password, the application will no longer be able to access the account and provide the desired service. OAuth helps both parties here! When the user authenticates an app via OAuth, it provides the developer with an access token ( a key and a secret ) which is by no way related to the user’s password. It’s unique for every user and application pair. That is every user will have an unique access token only for that application. Now even if the user changes the password, the access token will remain unchanged. The developer can safely store the token and use that to access the user’s account without hassle. Similarly, if the user wants to revoke the access permitted to an application, he or she can easily do that. In that case, the access token becomes invalid and the application loses access to that account.

In the Basic Auth age, it was very easy to develop twitter bots. You just setup the username and password into a configuration file, call the REST API with the login details and you’re done! Yeah, it was quite easy. But it’s not harder now 🙂 Don’t fret, OAuth is also very simple and easy to implement for twitter bots. While you need to go through a two phase OAuth dance to authorize other users, Twitter displays the access token of the developer directly into the dashboard! Thanks to Twitter for making things so plain for developers! With your own access token, you can authorize your apps directly without any further verification.

To get the access token, first go to : http://dev.twitter.com. Login if you’re not already logged in. Use the twitter ID you want to run as a bot. Go to http://dev.twitter.com/apps by clicking the “Your Apps” on top right corner. You will see a list of applications under the logged in twitter account. One big advantage of the basic auth was that you didn’t need to create applications. But now you need! Create an application if you don’t already have one created. In most cases you won’t have one since this is probably the first time you’re using OAuth. In that situation, please create an application. Note down the Consumer Key and Consumer Secret after visiting the application page by clicking on any of the application name. Now, on the right hand navigation bar, you’ll see “My Access Token”. Please visit that section and retrieve your Access Token and Access Token Secret. That’s all we needed. Now let’s do some coding to demonstrate the use of these keys and secrets.

We first need to get a Twitter Client library. If you’re already using one, just check to make sure that it has OAuth support. The work flow is simple. First construct the client with the consumer key and consumer secret. Then set the access token key and the access token secret. Now use the client to make Twitter API calls, in our case, to update statuses!

You can get the OAuth libraries from : http://dev.twitter.com/pages/oauth_libraries . But I recommend using Tweepy with Python and Abraham’s TwitterOAuth with PHP . They are not generic OAuth clients. They were built for Twitter and you don’t need to configure any extra parameters to make it work with Twitter.

Here’s the code samples on how to use the libraries to update status via OAuth.

PHP (Abraham’s TwitterOAuth)

post('statuses/update', array('status' => "Hello Twitter OAuth!"));
?>

Python (Tweepy)

consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
bot = tweepy.API(auth)

bot.update_status("Hello Twitter OAuth!")

51 replies on “Setting Up Twitter Bots with OAuth”

Hi Abraham Williams! How can I get values for these below?
$access_key = “”;
$access_secret = “”;

I generated Consumer key and Consumer secret like this values below:
Consumer key
taQbNpMGzqb7X1hTSmtls
Consumer secret
AkfQXUT3PAVP4QSAMoYiP87xn9Rd99d5HNsGrnEFZrs
So I don’t know how to generate the access_key and access_secret access_secret or Access token. Help me please.

Dear Masnun,

I am stuck with the following:

$estado = $titulo . ” ” . $tiny_url;

How can I pass $estado to last bit of your php code:

$connection->post(‘statuses/update’, array(‘status’ => “Hello Twitter OAuth!”));

i.e. want the status “Hello Tweeter OAuth!” to be the content of $estado.

I am not a php programmer so perhaps this is obvious to a php programmer.

Tayeb
in sunny Portugal!

Dear Abraham,

Thanks a lot for your post.

I got it working yesterday after posting the message in Masnun’s blog. My approach was:

$estado = array(‘status’ => $titulo . ” ” . $tiny_url);

and then the last code became:

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

So now my twitbot with oauth authentication, feeds into my Twitter page the latest posts in my vbulletin forums. Latest posts are retwitted by CRON every 1/2 hour. At the moment the keys are kept in a separate php hidden file. I will eventually hide these keys in a mysql database.

Your library was extremely useful as I’d become desperate after using unworkable solutions (for me) that required for example installing oauth with pecl. Rss-to-twitter providers didn’t seem to be reliable, the latest rejected by me being Feedburner from Google that seems to be a disaster. My twitbot was previously working with basic authentication.

I am planning to publish my solution for the benefit all those that want to keep their twitting bots working after Twitter’s August 16th deadline, when Twitter is planning to shut down simple authentication. I am sure many may be as desperate as I was till last night.

You can view my twitting bot’s results at:

http://twitter.com/myciwportal

Thanks a lot Abraham for your excellent oauth library, and to the owner of this page Masnun, him for simplifying the use of your library.

Tayeb
in sunny Portugal!

You’re most welcome. I appreciate if you make your code/solution open source and share it with the world!

Thanks to Abraham, he kept an eye on the follow up comments and responded before I could 😀

Dear Masnun,

Thanks a lot for your follow up. Yes, I plan to make the code/solution open source.

I regularly publish my works in portuguese and make them public. I have now decided to start out a blog in english, where I’ll publish the codes/solutions for the things I do/did including my recent twitbot with oauth authentication.

If you check my portals (in english http://www.myiwc.com presently closed down, and in portuguese http://www.myciw.org still active) you’ll see I have in the past made a number of php apps that I ended up offering as open source.

Tayeb
in sunny Portugal!

Hi
I saw what you write, but I do not think the solution for me.
I would use my app to write weather forecast for twitter users. How do I use the access token? I should probably retrieve the user’s Access token and Access Token Secret? How can I do it?
Thank you in advanced

Pietro from sunny Italy

Do you want a bot? Or do you want the user to be able to login using their twitter credentials? For the first one, you need your tokens. For the second, you need users’.

thanks a lot for you answer
i want to do the second one
but i dont understand how i can get users’ credentials using Abraham library.
can you help me?

ciao

Pietro just a little apart from the discussion… when you wrote “sunny Italy” I hope you understood that I used the words “sunny Portugal” without trying to imply that other countries are not sunny, or are less sunny. Masnun seems to live or took his photo in a sunny country where there is plenty of sun…

If you google around you will find the codes you are seeking for, with usage of Abraham’s library, or you could adapt them easily.

Dear Masnun and Abraham,

Just ot announce here that I have already published my Twitbot solution with recourse to Twitter’s OAUTH in my new english language blog. You can check everything at the following URL:

http://redacacia.wordpress.com/2010/08/05/a-twitbot-using-oauth/

I hope my solution, which in reality is really a mix of other already public domain solutions, will help those who are at this moment, as desperate as I was 2 days ago, in solving Twitter’s OAUTH puzzle and meet August 16th, 2010, Twitter deadline!

My special thanks is to both of you for latest codes, and Stammatiou for my previous codes.

Tayeb
in sunny Portugal! (without offenses to Pietro or for that matter Masnun 😉 )

i was kidding
can you tell me where i can find more information about what i wont to do.
I dont undersatnt how to get users’ credentials.

Pietro
from the real sunny country 😉

Dear Pietro,

I love Italy. Some of my best friends are italians.

Search for twitbot or twittbot and perhaps add feed. I found again something last night.

Tayeb
in sunny Portugal

No way to read at the moment the response from Twitter? Like an error 200 or something

Hi there.

In the last weeks I have read a lot of tutorial “How to update Twitter status with twitteroauth” and I have tried a lot of them, but I am not able to make it work 🙁

If I use the one described in this post (thank for sharing masnun 😉 ) my status does not be updated 🙁

Here below the $connection array print_r:

TwitterOAuth Object ( [http_code] => [url] => [host] => https://api.twitter.com/1/ [timeout] => 30 [connecttimeout] => 30 [ssl_verifypeer] => [format] => json [decode_json] => 1 [http_info] => [useragent] => TwitterOAuth v0.2.0-beta2 [sha1_method] => OAuthSignatureMethod_HMAC_SHA1 Object ( ) [consumer] => OAuthConsumer Object ( [key] => my_key [secret] => my_secret [callback_url] => ) [token] => OAuthConsumer Object ( [key] => my oauth token [secret] => my token secret [callback_url] => ) )

It is “a little bit” frustrating: it seems so simple, but it does not work for me 🙁

Thanks in advanced and have a great day

Paolo

Abraham might be able to provide details on this error. Looks cryptic to me. AFAIK, Abraham is following up this post. We can expect a reply from him. 🙂

@Paolo: What do you get when you do:

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

Your comment does not include any actual error message just a standard TwitterOAuth object.

Dear Abrtaham,

Since August 15th my script based on Masnun’s proposal does not update my twitter status. I checked with print_r as suggested and I am getting the following error:

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

Any idea of why if it worked before?

Tayeb

Abraham sorry for not spelling your name correctly.

My thanks Masnun for allwing me to post a question to Abraham here in your blog. Hoepfully he’ll answer or may be you have a suggestion.

Dear Masnun and Abraham,

I have solved the issue of my script not updating my twitter account. What I did was to investigate nonce error and its causes. It has to do with timestamp.

So as I wrote in my previous post my script was not updating twits as from August 15th. I thought that was odd at first, and I contacted Abraham directly by email asking him if there were any issues with his library, or if there are new Twitter arrangements, since Twitter was officially bringing down Basic authentication. Abraham may have not received my email or must have been quite busy ( he is under no obligation towards me, I must stress ) as he did not respond.

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 )

So after posting here the error, 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 others.

Tayeb

Dear Abraham,

Thanks a lot for your follow up.

I am glad you didn’t make your suggestions and I figured out myself. There’s more fun in learning by investigating and doing it oneself.

Do give me the pleasure of meeting you and accepting a meal from me if you ever visit Portugal.

Tayeb

Thanks for the description, very useful! A couple of suggestions…

Maybe you should say a sentence or two more about setting up the application at Twitter, which you skip over. That form is a little baffling if you don’t know much about OAuth, so it would be useful to say something like “Set the ‘Application Type’ to ‘Client’ and ‘Default Access Type’ to ‘Read & Write’.”

It would also be useful to know how to test for an error after posting the status. For the PHP version, maybe something like:

$response = $connection->post('statuses/update', array('status' => "Hello Twitter OAuth!"));
if ($connection->lastStatusCode() != 200) {
print $response->error;
}

Although lastStatusCode() appears not to be working properly at the moment…

[…] do last week was to transition the PLAY Pilots twitter bot to use OAuth. I just found this article “Setting Up Twitter Bots with OAuth” that describes exactly what I did (without having read it). Twitter’s documentation is a bit […]

@Abraham thank you very much for your prompt reply and SORRY for the delay of mine 🙁

If I put in the status update script the code line that you told me does not happen anything 🙁

The script runs and at the end the web page remains blank/white: no error, no messages, no status update 🙁

I also tried to include a test for an error after posting the status (as suggested by @Phil Gyford) but the script page does not show any error: the page still remains white and no status update arghhhhhhhh >:(

Thank you in advanced for your kind help, have a great sunday

Paolo

@Abraham the code is exactly (copy/paste) the php script that maSnun shows in this post.

I also tried to create a twitter test account to obtain another “quartet” of keys (customer and access keys and secrets) but the result is still the same 🙁

Could be an hosting service problem?

Thank you in advanced for your help, have a nice day

Paolo

@Paolo: Does the following output anything to the screen?

var_dump($connection->post(…..));
var_dump($connection->http_code); // make sure this is after the post

If not check your web servers error log.

@Abraham if I use your lines code the script gives me back a Parse error: syntax error, unexpected ‘.’, expecting ‘)’

if I include the ….. between the single quotes ‘…..’ the script’s output is:

NULL int(0)

I hope this helps you … helping me 😉

Thank you masnun for a very useful post. At least I am not getting any errors now with Abraham’s TwitterOAuth.

No errors, but no status update in Twitter, either.

So I ran Abraham’s var_dump suggestions and got:

string(75) “{“request”:”/1/statuses/update.json”,”error”:”Could not authenticate you.”}” int(401)

Now, maybe I am doing something off target. I’m using your code only to call twitteroauth.php (I’ve replaced Abraham’s index.php which gave me errors).

My app shows up correctly in my settings/connection page.

Any help will bring vast amounts of positive karma upon you 🙂

Hi Tayeb and thanks for your reply. Most things are blatantly obvious after the event, but it had been a mystery to me where the various keys were supposed to go in the code.

The following just seemed to be proper defining of (empty) variables.

$consumer_key = “”;
$consumer_secret = “”;
$access_key = “”;
$access_secret = “”;

It all would have made more sense to me if the example code in the post had included some dummy stuff as values for the variables, with a statement like “Replace the values with the keys you get from Twitter”.

$consumer_key = “n5hrjruieudyshdbenn5bg4b”;
$consumer_secret = “yueud7tyertsdu”;
$access_key = “7e8syeurtydys”;
$access_secret = “89e8dyetsr”;

I know it goes into the “duh” category, but for those of us who are brand new…

Thanks again for your help.

Hello,

I have tried oAuth method to update status to twitter. However, it only shows updated text when I do login to account on twitter. It doesn’t show tweet posted using PHP publicly. i.e If I write http://www.twitter.com/ without loging into to twitter it doesn’t show tweets updated using PHP script. But after logging into my account if I write http://www.twitter.com/ it shows all tweets I submitted using PHP

Please help.

Below is the code I have used to update status on twitter.

<?
include_once('lib/twitteroauth.php');

define('CONSUMER_KEY','’);
define(‘CONSUMER_SECRET’,”);

function getConnectionWithAccessToken($oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
return $connection;
}

$connection = getConnectionWithAccessToken(“”, “”);
$content = $connection->post(‘http://api.twitter.com/1/statuses/update.json’,array(“status”=>”Hello From PHP “,”include_entities” => 1,”trim_user”=>1));
?>

Comments are closed.