karzilla: a green fist above the word SMASH! (Default)

AS ORIGINALLY WRITTEN THIS DOES NOT WORK WITH THE CURRENT API. SEE UPDATES BELOW.

If you follow [twitter.com profile] kareila you have already seen this, but there's a [twitter.com profile] dw_alerts account that posts errors from Dreamwidth's Nagios log, and it was broken until I fixed it a couple of days ago. It wasn't hard. Here's what I did:

Request API keys from Twitter

1] Go to https://dev.twitter.com/apps and sign in with the account you are using with your script (in my case, dw_alerts).

2] Click "Create a new application".

3] Give your application a name - I used "DW Nagios Gateway" - and a description (in my case, also "DW Nagios Gateway"). The only other required field is website - use whatever you feel is appropriate here. Leave "Callback URL" blank, agree to the terms, prove your sentience, and submit the form.

4] Now you should be on the Details page for your new application. Before you do anything else, click the Settings tab and scroll down to the choices for "Application Type." Change the selection from "Read only" to "Read and Write," because you want your script to post messages.

5] Go back to the Details tab and click the button to create access tokens.

6] Now from the OAuth tab, you should be able to copy the four keys you need. In your Perl script, it would look something like this:

my %oauth_info = (
    consumer_key => 'aaaa',
    consumer_secret => 'bbbb',
    access_token => 'cccc',
    access_token_secret => 'dddd',
);

(Those values should be long gibberish looking strings, which I am simplifying here.)

This is what you use instead of a username and password to authenticate using the new API.

Update your code to use the new API

Your mileage may vary, but for my purposes, I was able to use Net::Twitter::Lite instead of the more full-featured Net::Twitter. You also need to install and explicitly use Net::OAuth and Mozilla::CA.

use Net::Twitter::Lite;
use Net::OAuth;
use Mozilla::CA;

Here are the three lines of code I use to post $msg to Twitter:

my $tw = Net::Twitter::Lite->new( %oauth_info, ssl => 1 ) or die;
eval { $tw->update( $msg ) };
warn "Twitter error: $@\n" if $@;

That's it! Let me know if you have any problems.

UPDATE: This broke again a week later, when Twitter completely turned off the 1.0 API. But again, CPAN comes to the rescue and the fix is easy: instead of Net::Twitter::Lite, use Net::Twitter::Lite::WithAPIv1_1. Everything else still works as before.

UPDATE 1/2014: Twitter now requires SSL, so I've added "ssl => 1" and "use Mozilla::CA" to the code above to reflect this.

Page generated May. 29th, 2017 05:41 am
Powered by Dreamwidth Studios