10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
15 my ($REV) = '$Rev: 339 $' =~ /(\d+)/;
17 authors => 'Dan Boger',
18 contact => 'zigdon@gmail.com',
20 description => 'Send twitter updates using /tweet. '
21 . 'Can optionally set your bitlbee /away message to same',
22 license => 'GNU GPL v2',
23 url => 'http://tinyurl.com/twirssi',
24 changed => 'Mon Dec 1 15:36:01 PST 2008',
34 my $last_poll = time - 300;
39 my ( $data, $server, $win ) = @_;
42 ¬ice("Not logged in! Use /twitter_login username pass!");
46 my ( $target, $text ) = split ' ', $data, 2;
47 unless ( $target and $text ) {
48 ¬ice("Usage: /dm <nick> <message>");
52 &cmd_direct_as( "$user $data", $server, $win );
56 my ( $data, $server, $win ) = @_;
59 ¬ice("Not logged in! Use /twitter_login username pass!");
63 my ( $username, $target, $text ) = split ' ', $data, 3;
64 unless ( $username and $target and $text ) {
65 ¬ice("Usage: /dm_as <username> <nick> <message>");
69 unless ( exists $twits{$username} ) {
70 ¬ice("Unknown username $username");
75 unless ( $twits{$username}
76 ->new_direct_message( { user => $target, text => $text } ) )
78 ¬ice("DM to $target failed");
84 ¬ice("DM caused an error. Aborted");
88 ¬ice("DM sent to $target");
89 $nicks{$target} = time;
93 my ( $data, $server, $win ) = @_;
96 ¬ice("Not logged in! Use /twitter_login username pass!");
100 $data =~ s/^\s+|\s+$//;
102 ¬ice("Usage: /tweet <update>");
106 &cmd_tweet_as( "$user $data", $server, $win );
110 my ( $data, $server, $win ) = @_;
113 ¬ice("Not logged in! Use /twitter_login username pass!");
117 $data =~ s/^\s+|\s+$//;
118 my ( $username, $data ) = split ' ', $data, 2;
120 unless ( $username and $data ) {
121 ¬ice("Usage: /tweet_as <username> <update>");
125 unless ( exists $twits{$username} ) {
126 ¬ice("Unknown username $username");
130 if ( Irssi::settings_get_str("short_url_provider") ) {
131 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
133 my $short = makeashorterlink($url);
134 $data =~ s/\Q$url/$short/g;
139 if ( length $data > 140 ) {
141 "Tweet too long (" . length($data) . " characters) - aborted" );
146 unless ( $twits{$username}->update($data) )
148 ¬ice("Update failed");
154 ¬ice("Update caused an error. Aborted.");
158 foreach ( $data =~ /@([-\w]+)/ ) {
163 if ( Irssi::settings_get_bool("tweet_to_away")
165 and $data !~ /^[dD] / )
168 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
170 $server->send_raw("away :$data");
173 ¬ice( "Can't find bitlbee server.",
174 "Update bitlbee_server or disalbe tweet_to_away" );
178 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
182 my ( $data, $server, $win ) = @_;
185 ¬ice("Not logged in! Use /twitter_login username pass!");
189 $data =~ s/^\s+|\s+$//;
191 ¬ice("Usage: /reply <nick[:num]> <update>");
195 $data =~ s/^\s+|\s+$//;
196 my ( $id, $data ) = split ' ', $data, 2;
197 unless ( $id and $data ) {
198 ¬ice("Usage: /reply_as <nick[:num]> <update>");
202 &cmd_reply_as( "$user $id $data", $server, $win );
206 my ( $data, $server, $win ) = @_;
208 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
209 ¬ice("twirssi_track_replies is required in order to reply to "
210 . "specific tweets. Either enable it, or just use /tweet "
211 . "\@username <text>." );
216 ¬ice("Not logged in! Use /twitter_login username pass!");
220 $data =~ s/^\s+|\s+$//;
221 my ( $username, $id, $data ) = split ' ', $data, 3;
223 unless ( $username and $data ) {
224 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
228 unless ( exists $twits{$username} ) {
229 ¬ice("Unknown username $username");
234 $id =~ s/[^\w\d\-:]+//g;
235 ( $nick, $id ) = split /:/, $id;
236 unless ( exists $id_map{$nick} ) {
237 ¬ice("Can't find a tweet from $nick to reply to!");
241 $id = $id_map{__indexes}{$nick} unless $id;
242 unless ( $id_map{ lc $nick }[$id] ) {
243 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
247 # remove any @nick at the beginning of the reply, as we'll add it anyway
248 $data =~ s/^\s*\@?$nick\s*//;
249 $data = "\@$nick " . $data;
251 if ( Irssi::settings_get_str("short_url_provider") ) {
252 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
254 my $short = makeashorterlink($url);
255 $data =~ s/\Q$url/$short/g;
260 if ( length $data > 140 ) {
262 "Tweet too long (" . length($data) . " characters) - aborted" );
268 $twits{$username}->update(
271 in_reply_to_status_id => $id_map{ lc $nick }[$id]
276 ¬ice("Update failed");
282 ¬ice("Update caused an error. Aborted");
286 foreach ( $data =~ /@([-\w]+)/ ) {
291 if ( Irssi::settings_get_bool("tweet_to_away")
293 and $data !~ /^[dD] / )
296 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
298 $server->send_raw("away :$data");
301 ¬ice( "Can't find bitlbee server.",
302 "Update bitlbee_server or disalbe tweet_to_away" );
306 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
310 my ( $usage_str, $api_name, $post_ref ) = @_;
313 my ( $data, $server, $win ) = @_;
316 ¬ice("Not logged in! Use /twitter_login username pass!");
320 $data =~ s/^\s+|\s+$//;
322 ¬ice("Usage: $usage_str");
327 unless ( $twit->$api_name($data) )
329 ¬ice("$api_name failed");
335 ¬ice("$api_name caused an error. Aborted.");
339 &$post_ref($data) if $post_ref;
344 my ( $data, $server, $win ) = @_;
346 $data =~ s/^\s+|\s+$//g;
347 if ( exists $twits{$data} ) {
348 ¬ice("Switching to $data");
349 $twit = $twits{$data};
352 ¬ice("Unknown user $data");
357 my ( $data, $server, $win ) = @_;
359 $data =~ s/^\s+|\s+$//g;
360 if ( $data and exists $twits{$data} ) {
361 ¬ice("Logging out $data...");
362 $twits{$data}->end_session();
363 delete $twits{$data};
365 ¬ice("Unknown username '$data'");
367 ¬ice("Logging out $user...");
368 $twit->end_session();
370 delete $twits{$user};
372 &cmd_switch( ( keys %twits )[0], $server, $win );
374 Irssi::timeout_remove($poll) if $poll;
381 my ( $data, $server, $win ) = @_;
384 ( $user, $pass ) = split ' ', $data, 2;
385 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
386 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
388 my @user = split /\s*,\s*/, $autouser;
389 my @pass = split /\s*,\s*/, $autopass;
390 if ( @user != @pass ) {
391 ¬ice("Number of usernames doesn't match "
392 . "the number of passwords - auto-login failed" );
395 while ( @user and @pass ) {
403 ¬ice("/twitter_login requires either a username and password "
404 . "or twitter_usernames and twitter_passwords to be set." );
408 %friends = %nicks = ();
410 $twit = Net::Twitter->new(
416 unless ( $twit->verify_credentials() ) {
417 ¬ice("Login as $user failed");
420 &cmd_switch( ( keys %twits )[0], $server, $win );
426 my $rate_limit = $twit->rate_limit_status();
427 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
428 ¬ice("Rate limit exceeded, try again later");
433 $twits{$user} = $twit;
434 Irssi::timeout_remove($poll) if $poll;
435 $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
436 ¬ice("Logged in as $user, loading friends list...");
438 ¬ice( "loaded friends: ", scalar keys %friends );
439 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
440 Irssi::settings_set_bool( "twirssi_first_run", 0 );
441 unless ( exists $friends{twirssi} ) {
442 ¬ice("Welcome to twirssi!"
443 . " Perhaps you should add \@twirssi to your friends list,"
444 . " so you can be notified when a new version is release?"
445 . " Just type /twitter_friend twirssi." );
452 ¬ice("Login failed");
457 my ( $data, $server, $win ) = @_;
459 my $loc = Irssi::settings_get_str("twirssi_location");
462 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
467 if ( not -x "/usr/bin/md5sum" and not $data ) {
469 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
476 eval { use Digest::MD5; };
480 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
485 $md5 = get("http://twirssi.com/md5sum");
489 ¬ice("Failed to download md5sum from peeron! Aborting.");
493 unless ( open( CUR, $loc ) ) {
495 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
500 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
503 if ( $cur_md5 eq $md5 ) {
504 ¬ice("Current twirssi seems to be up to date.");
509 my $URL = "http://twirssi.com/twirssi.pl";
510 ¬ice("Downloading twirssi from $URL");
511 LWP::Simple::getstore( $URL, "$loc.upgrade" );
514 unless ( open( NEW, "$loc.upgrade" ) ) {
516 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
521 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
524 if ( $new_md5 ne $md5 ) {
525 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
530 rename $loc, "$loc.backup"
531 or ¬ice("Failed to back up $loc: $!. Aborting")
533 rename "$loc.upgrade", $loc
534 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
537 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
538 if ( -e "$dir/autorun/$file" ) {
539 ¬ice("Updating $dir/autorun/$file");
540 unlink "$dir/autorun/$file"
541 or ¬ice("Failed to remove old $file from autorun: $!");
542 symlink "../$file", "$dir/autorun/$file"
543 or ¬ice("Failed to create symlink in autorun directory: $!");
546 ¬ice("Download complete. Reload twirssi with /script load $file");
556 print $fh "Loading friends page $page...\n" if ( $fh and &debug );
557 my $friends = $twit->friends( { page => $page } );
558 last unless $friends;
559 $new_friends{ $_->{screen_name} } = time foreach @$friends;
561 last if @$friends == 0 or $page == 10;
566 ¬ice("Error during friends list update. Aborted.");
570 my ( $added, $removed ) = ( 0, 0 );
571 print $fh "Scanning for new friends...\n" if ( $fh and &debug );
572 foreach ( keys %new_friends ) {
573 next if exists $friends{$_};
578 print $fh "Scanning for removed friends...\n" if ( $fh and &debug );
579 foreach ( keys %friends ) {
580 next if exists $new_friends{$_};
585 return ( $added, $removed );
589 print scalar localtime, " - get_updates starting" if &debug;
592 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
595 ->print( "Can't find a window named '"
596 . Irssi::settings_get_str('twitter_window')
597 . "'. Create it or change the value of twitter_window" );
600 ¬ice("Not logged in! Use /twitter_login username pass!");
604 my ( $fh, $filename ) = File::Temp::tempfile();
608 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
609 Irssi::pidwait_add($pid);
610 } elsif ( defined $pid ) { # child
617 &do_updates( $fh, $user, $twit );
618 foreach ( keys %twits ) {
620 &do_updates( $fh, $_, $twits{$_} );
623 my ( $added, $removed ) = &load_friends($fh);
624 if ( $added + $removed ) {
625 print $fh "%R***%n Friends list updated: ",
627 sprintf( "%d added", $added ),
628 sprintf( "%d removed", $removed ) ),
631 print $fh "__friends__\n";
632 foreach ( sort keys %friends ) {
633 print $fh "$_ $friends{$_}\n";
639 print scalar localtime, " - get_updates ends" if &debug;
643 my ( $fh, $username, $obj ) = @_;
645 print scalar localtime, " - Polling for updates for $username" if &debug;
648 $tweets = $obj->friends_timeline(
649 { since => HTTP::Date::time2str($last_poll) } )
654 print $fh "type:error Error during friends_timeline call. Aborted.\n";
658 foreach my $t ( reverse @$tweets ) {
659 my $text = decode_entities( $t->{text} );
661 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
663 if ( Irssi::settings_get_bool("show_reply_context")
664 and $t->{in_reply_to_screen_name} ne $username
665 and $t->{in_reply_to_screen_name}
666 and not exists $friends{ $t->{in_reply_to_screen_name} } )
668 $nicks{ $t->{in_reply_to_screen_name} } = time;
669 my $context = $obj->show_status( $t->{in_reply_to_status_id} );
671 my $ctext = decode_entities( $context->{text} );
673 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
674 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
675 $context->{id}, $username,
676 $context->{user}{screen_name}, $ctext;
679 print "Failed to get context from $t->{in_reply_to_screen_name}"
684 if $t->{user}{screen_name} eq $username
685 and not Irssi::settings_get_bool("show_own_tweets");
686 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
687 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
690 print scalar localtime, " - Polling for replies" if &debug;
692 $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
697 print $fh "type:error Error during replies call. Aborted.\n";
701 foreach my $t ( reverse @$tweets ) {
703 if exists $friends{ $t->{user}{screen_name} };
705 my $text = decode_entities( $t->{text} );
707 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
708 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
709 $t->{id}, $username, $t->{user}{screen_name}, $text;
712 print scalar localtime, " - Polling for DMs" if &debug;
714 $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
716 foreach my $t ( reverse @$tweets ) {
717 my $text = decode_entities( $t->{text} );
719 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
720 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
721 $t->{id}, $username, $t->{sender_screen_name}, $text;
723 print scalar localtime, " - Done" if &debug;
728 my $filename = $data->[0];
730 print scalar localtime, " - checking child log at $filename" if &debug;
731 my $old_last_poll = $last_poll;
732 if ( open FILE, $filename ) {
736 last if /^__friends__/;
738 foreach my $key (qw/id account nick type/) {
743 next if exists $tweet_cache{ $meta{id} };
744 $tweet_cache{ $meta{id} } = time;
746 if ( $meta{account} ne $user ) {
747 $account = "$meta{account}: ";
751 if ( $meta{type} ne 'dm'
752 and Irssi::settings_get_bool("twirssi_track_replies")
756 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
757 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
758 $id_map{__indexes}{ $meta{nick} } = $marker;
759 $marker = ":$marker";
762 if ( $meta{type} eq 'tweet' ) {
763 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
764 } elsif ( $meta{type} eq 'reply' ) {
765 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
766 } elsif ( $meta{type} eq 'dm' ) {
767 push @lines, "[$account%B\@$meta{nick}%n (%WDM%n)] $_\n",;
768 } elsif ( $meta{type} eq 'error' ) {
769 push @lines, "debug: $_\n" if &debug,;
770 } elsif ( $meta{type} eq 'debug' ) {
771 push @lines, "debug: $_\n" if &debug,;
781 my ( $f, $t ) = split ' ', $_;
782 $nicks{$f} = $friends{$f} = $t;
785 if ( $last_poll != $old_last_poll ) {
786 print "new last_poll = $last_poll" if &debug;
787 foreach my $line (@lines) {
789 $window->print( $line, MSGLEVEL_PUBLIC );
790 foreach ( $line =~ /\@([-\w]+)/ ) {
797 or warn "Failed to remove $filename: $!"
800 # keep 10 minutes of cached tweets, to make sure we don't show duplicates.
801 foreach ( keys %tweet_cache ) {
802 next if $tweet_cache{$_} > time - 600;
803 delete $tweet_cache{$_};
810 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
814 return Irssi::settings_get_bool("twirssi_debug");
818 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
822 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
825 $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
826 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
827 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
829 { # /twitter_reply gets a nick:num
830 @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
833 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
835 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
836 my $prefix = $word =~ s/^@//;
837 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
838 push @$complist, grep /^\Q$word/i,
839 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
840 @$complist = map { "\@$_" } @$complist if $prefix;
844 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
845 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
846 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
847 Irssi::settings_add_str( "twirssi", "twirssi_location",
848 ".irssi/scripts/twirssi.pl" );
849 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
850 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
851 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
852 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
853 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
854 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
855 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
856 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
857 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
858 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
861 Irssi::command_bind( "dm", "cmd_direct" );
862 Irssi::command_bind( "dm_as", "cmd_direct_as" );
863 Irssi::command_bind( "tweet", "cmd_tweet" );
864 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
865 Irssi::command_bind( "twitter_reply", "cmd_reply" );
866 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
867 Irssi::command_bind( "twitter_login", "cmd_login" );
868 Irssi::command_bind( "twitter_logout", "cmd_logout" );
869 Irssi::command_bind( "twitter_switch", "cmd_switch" );
870 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
871 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
872 Irssi::command_bind( "reply", "cmd_reply" );
873 Irssi::command_bind( "reply_as", "cmd_reply_as" );
878 print "twits: ", Dumper \%twits;
879 print "friends: ", join ", ", sort keys %friends;
880 print "nicks: ", join ", ", sort keys %nicks;
881 print "last poll: $last_poll";
888 "Twirssi v$VERSION (r$REV); Net::Twitter v$Net::Twitter::VERSION. "
889 . "See details at http://tinyurl.com/twirssi" );
895 "/twitter_friend <username>",
897 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
903 "/twitter_unfriend <username>",
905 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
908 Irssi::command_bind( "twitter_updates", "get_updates" );
909 Irssi::signal_add_last( 'complete word' => \&sig_complete );
911 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
912 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
914 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
916 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
917 eval "use WWW::Shorten::$provider;";
921 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
926 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
927 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
934 ->print( "Create a window named "
935 . Irssi::settings_get_str('twitter_window')
936 . " or change the value of twitter_window. Then, reload twirssi." );