How To: Growl and Twitter

THIS POST HAS BEEN SUPERSEDED BY Twitter + Growl = Trowel v1.0

 

OK, so I’m new to Twitter. I didn’t (don’t) get it. Who wants to know what I’m doing? Well as I keep telling myself thats not the point. The point is to spread information, I had a lot of fun on Election night tweeting away about the coverage and calling states (I was surprisingly accurate).

The one thing that did annoy me was it added another website to check – not just a lunch but a refresh every 5 minutes. Something had to be done.

For anyone who has Adium installed on their Mac, you will be aware of Growl it’s a notification system that has yet to reach it’s full potential. As with background messages I wanted my incoming Tweets to be shown in small unobtrusive transparent bubble.

To cut a long story short – I couldn’t find anything. I found a few Ruby scripts (that didn’t work), I tried some nice applications but I didn’t want to run another app I wanted Growl!

So an hour or 2 or Googling and research for scripts I found some Perl modules that I could combine to produce the desired output.

My steps and code are listed below, its not 100% fool proof – please leave comments on how I can improve it.

 

1. Installing the Modules

You will need only 3 modules Mac::GrowlNet::Twitter and Date::Format, if your lucky Date::Format might even be already installed. Type the following commands into terminal.

$ sudo perl -MCPAN -e shell

This will launch a CPAN command line session to install the modules type (at the prompt):

> install Mac::Growl

Agree to any dependancies, when it done type:

> install Net::Twitter

Again agree to all dependancies, and lastly:

> install Date::Format

> exit

If you had any problems it may be because You need Apple’s Development tools installed, these are a free download form Apple. Please leave any problems in the comments.

 

2. Coding

Now for the code, just copy the following into a empty text file and save as some thing sensible like growl_tweet.pl:

#! /usr/bin/perl -wT

use Mac::Growl ':all';
use Net::Twitter;
use Date::Format;

my $app    = 'Growl/Twitter';
my @names  = ('New Tweet');

RegisterNotifications($app, \@names, [$names[0]]);

my $tweet = Net::Twitter->new( username=>'##REPLACE WITH USERNAME##', password=>'##REPLACE WITH PASSWORD##' );

my $last_id = undef;
my $switch = 0;

while(1)
{
 my @tt = ();

 if($last_id)
 {
 @tt = $tweet->friends_timeline({count => 200, since_id => $last_id });
 }
 else
 {
 @tt = $tweet->friends_timeline({count => 5 });
 }

 foreach my $t (@{$tt[0]})
 {
 if(!$switch) { $last_id = $t->{id}; $switch++; };

 PostNotification($app, $names[0], $t->{user}{screen_name}, $t->{text});

 printf("%s: %s\n", $t->{user}{screen_name}, $t->{text});

 print "sleep 4\n";

 sleep(4);
 }

 $switch = 0;
 print "sleep 37\n";
 sleep(37);
}

exit;

 

3. Running

Now, simply run the script:

$ perl ./growl_tweet.pl

And bingo! All your tweets appear! Leave a comment if it works and especially if it doesn’t – if there is enough interest I might consider adding features and real installer!

 

4. Here’s one I made earlier

If you would like the code, you can down load it here (with out any formatting issues).

http://www.echo-technology.co.uk/development/twitter+growl/growl.pl.txt

Tags: , , ,

22 Responses to “How To: Growl and Twitter”

  1. Richard Stelling says:

    Don’t forget! You need to install Growl too!

  2. Scott says:

    Hello,

    One small problem. If someone copies and pastes right from here the quotes will be all wrong. The website here has the quotes as the fancy left and right facing single and double quotes. I had to go a change all those.

    A simple recommendation of mine would be to have a download of the perl script. Otherwise you will probably get lots of people asking for help.

    cheers, scott.

  3. Scott says:

    The script works great! Thanks for all the hard work.

  4. Thanks Scott,

    I glad some one else had the need, I was starting to think I was alone in the Twitter+Growl world.

    You might want to look out for:

    “Cannot decode string with wide characters at /System/Library/Perl/5.8.8/darwin-thread-multi-2level/Encode.pm line 166.”

    It will cause the script to terminate and you will need to restart it. When I get some time I will fix it… unless anyone else already has (hint).

  5. If your getting this error:

    make: *** No targets specified and no makefile found. Stop.

    When trying to install any of the Perl modules, check this:

    1. You have Apple’s development tools installed
    2. You run the CPAN module with root permissions to it can copy, create and delete files. Remember to use the sudo command

    $ sudo perl -MCPAN -e shell

  6. Luke Westlie says:

    Thanks for this article Richard, I find it incredibly useful.

  7. Lon says:

    Richard: Wonderful, works great, useful + informative. Thank you!

  8. jamEs says:

    I don’t get where or how to save the growl_tweet.pl. Could you possibly outline the terminal process to create the file and save the file? That bit is a little vague for a person like myself who doesn’t know terminal very well.

  9. Bhima says:

    What would be really great would be to display the profile image of the tweet in the Growl Notification…. but perusing perl twitter module I don’t see a method for profile images which are not you own… Am I missing something?

  10. Bhima says:

    One other thing… Mac::Growl expects strings to be passed as UTF-8. So you need to encode the text to UTF-8 before you pass it to Mac::Growl. That’s the problem with “wide characters”

    Look at the Mac::Growl CPAN site for more info: http://search.cpan.org/~cnandor/Mac-Growl-0.67/lib/Mac/Growl.pm

  11. Bhima says:

    I still have problems with script running into an error and exiting… the error that is plaguing me now is: “malformed JSON string, neither array, object, number, string or atom”.

    I thought that bracketing it in an “eval or do” block would help but I get the error “Can’t call method “Eval” without a package or object reference” when I implement it.

    I’m not really a Perl expert, so I am sort of stuck.

  12. Mads Hartmann says:

    Hey, thanks a lot for the script!

    Any chance you’ll extend it so it supports profile images aswell?

    Thanks,
    Mads

  13. Mads Hartmann says:

    Uh, one question:

    Does Terminal have to be open for the script to notify Growl?

    Mads

  14. Moriarty says:

    Hey,

    This indeed is incredibly useful. I tried to work with the ruby scripts out there, but none of them worked.

    Since I couldn’t install Mac::Growl, I change this script to use growlnotify:
    Erase the RegisterNotifications and replace PostNotification with:

    my $message = “$t->{text}”;
    my $cmd = “/usr/local/bin/growlnotify -n Twitter -m \”$message\” -t \”$t->{user}{screen_name}\”";
    system $cmd;

    However, I have this problem. After several hours of running I get:

    malformed JSON string, neither array, object, number, string or atom, at character offset 0 ["<!DOCTYPE html PUBLI..."] at /opt/local/lib/perl5/site_perl/5.8.8/JSON/Any.pm line 483

    And the script quits. Any workarounds for it?

    Cheers,
    M.

  15. Mads, yes – I have a version that has loads more features in the final days of beta testing.

  16. Bhima says:

    Hi Richard, I think this script is a great idea but I think so far, (perhaps ultimately?) it is a suboptimal solution. My thinking is along these lines:

    1: As I recall, Perl comes with XCode. So, if you don’t already have Perl & CPAN installed you are in for a long download just to get this little script working. I admit that I never cease to marvel at the ease of using CPAN and installing modules but not everyone has both Perl and CPAN installed on their Mac. Maybe Perl comes with Leopard these days? If that’s true I suppose it’s a little easier… but it isn’t the magical easy of a user that already has CPAN up and running. Applescript is already on all Macs, and the growl support for applescript is installed with growl.

    2: Sticking the username and password in the code as constants is also suboptimal. Applescript allows for an elegant keychain scripting solution and there is a Perl module for keychain scripting (LWP::UserAgent::Keychain). However I was unable to successfully install it. I had thought of just using Applescript instead of Perl. However there is no twitter scripting addition for Applescript to replace Net::Twitter in Perl… so the script would probably require an amount of manual XML parsing which I have no tolerance of (yet). Alternately maybe it would be possible to port Net::Twitter to an OSAX but I have no idea how and it is “outside of the scope” of the O’Reilly Applescript book I have. (At this point I find this pretty intriguing and I am pursuing this further but have nothing to show for it)

    3: You need to have terminal open to have it work (I have tinkered with versions of this script running from Geektool and have met with various levels of success).

    4: While I have successfully fetched the URI for the avatar of the tweet originator, I can not entice Mac::Growl to use it. I have tried a variety of utf8 encoding and escaping / un-escaping to no real avail. I asked Pudge about this but he has not responded. Because I have not worked out the XML parsing in Applescript, I have not bothered to discover if growl icon method works with URIs in Applescript. The only idea I have for this is to create a local cache of avatars and point growl to the local copy. However I have not yet tried to implement this.

    So, I look forward to your updated script and I hope you’ve found elegant solutions to some of the problems that I have been unable to overcome :)

    To answer some unanswered questions here:

    For the people encountering errors which cause the script to exit: As it is this script assumes everything always works and twitter is always available, and everything arrives in the correct encoding (none of which is really true). I think the most common error management design pattern in Perl is to wrap the potentially offending code block in an “if then warn” structure. I’ve used eval / warn like this:

    eval {@tt = $tweet->friends_timeline( {count => 200, since_id => $last_id})};
    warn $@ if $@;

    Mac:: Growl requires input be encoded with utf8. (this is the source of the “Cannot decode string with wide characters” errors) Which I solved by using the perl module Encode as described on the Mac::Growl page at CPAN. I also tried using utf8 which is also described there but it did not work.

    For the guy asking how to save a file in Terminal: Don’t bother with terminal, use XCode, the Script Editor, or even Text Edit. Just open a new file, paste the posted code in it, change the quotes, and save with a .pl extension. Or you can download the linked pl.txt file and remove the txt extension (this is what I did but I still wound up having to fix the quotes)

  17. SlaunchaMan says:

    Awesome! I made a LaunchAgent to make this run in the background while I’m logged in. Save this as ~/Library/LaunchAgents/uk.echo-technology.twitter+growl.plist :

    Label
    uk.echo-technology.twitter+growl
    OnDemand

    KeepAlive

    Program
    /path/to/twitter+growl.pl

    Be sure to change the path to reflect what it is on your system. Enjoy!

  18. SlaunchaMan says:

    Looks like my XML got messed up. Here’s the plist again:

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN” “http://www.apple.com/DTDs/PropertyList-1.0.dtd”>
    <plist version=”1.0″>
    <dict>
    <key>Label</key>
    <string>uk.echo-technology.twitter+growl</string>
    <key>OnDemand</key>
    <false/>
    <key>KeepAlive</key>
    <true/>
    <key>Program</key>
    <string>/path/to/twitter+growl.pl</string>
    </dict>
    </plist>

  19. Jeremy Sample says:

    I was able to install the modules fine but when I try to run perl ./growl_tweet.pl I get the following error:

    “-T” is on the #! line, it must also be used on the command line at ./growl_tweet.pl line 1.

  20. Altimor says:

    I had the same error than Jeremy Sample…
    I have the Apple Developper Tools, and installed all the scripts properly, but the last one just doesn’t work.

  21. Copprhead says:

    If you get the “-T is on the #! line…”, either run it with “perl -T ./growl_tweet.pl” or make it executable with “chmod +x growl_tweet.pl” and then run it directly via “./growl_tweet.pl”.

  22. Matt says:

    How many Deps are there for Net::Twitter… dang!

Leave a Reply