10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
15 my ($REV) = '$Rev: 347 $' =~ /(\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 => '$Date: 2009-01-06 09:54:25 -0800 (Tue, 06 Jan 2009) $',
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 disable 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{ lc $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, 0 ] );
609 Irssi::pidwait_add($pid);
610 } elsif ( defined $pid ) { # child
618 $error += &do_updates( $fh, $user, $twit );
619 foreach ( keys %twits ) {
621 $error += &do_updates( $fh, $_, $twits{$_} );
624 my ( $added, $removed ) = &load_friends($fh);
625 if ( $added + $removed ) {
626 print $fh "%R***%n Friends list updated: ",
628 sprintf( "%d added", $added ),
629 sprintf( "%d removed", $removed ) ),
632 print $fh "__friends__\n";
633 foreach ( sort keys %friends ) {
634 print $fh "$_ $friends{$_}\n";
638 print $fh "type:error Update encountered errors. Aborted\n";
639 print $fh $last_poll;
646 print scalar localtime, " - get_updates ends" if &debug;
650 my ( $fh, $username, $obj ) = @_;
652 print scalar localtime, " - Polling for updates for $username" if &debug;
655 $tweets = $obj->friends_timeline(
656 { since => HTTP::Date::time2str($last_poll) } )
661 print $fh "type:error Error during friends_timeline call. Aborted.\n";
665 foreach my $t ( reverse @$tweets ) {
666 my $text = decode_entities( $t->{text} );
668 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
670 if ( Irssi::settings_get_bool("show_reply_context")
671 and $t->{in_reply_to_screen_name} ne $username
672 and $t->{in_reply_to_screen_name}
673 and not exists $friends{ $t->{in_reply_to_screen_name} } )
675 $nicks{ $t->{in_reply_to_screen_name} } = time;
676 my $context = $obj->show_status( $t->{in_reply_to_status_id} );
678 my $ctext = decode_entities( $context->{text} );
680 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
681 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
682 $context->{id}, $username,
683 $context->{user}{screen_name}, $ctext;
686 print "Failed to get context from $t->{in_reply_to_screen_name}"
691 if $t->{user}{screen_name} eq $username
692 and not Irssi::settings_get_bool("show_own_tweets");
693 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
694 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
697 print scalar localtime, " - Polling for replies" if &debug;
699 $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
704 print $fh "type:error Error during replies call. Aborted.\n";
708 foreach my $t ( reverse @$tweets ) {
710 if exists $friends{ $t->{user}{screen_name} };
712 my $text = decode_entities( $t->{text} );
714 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
715 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
716 $t->{id}, $username, $t->{user}{screen_name}, $text;
719 print scalar localtime, " - Polling for DMs" if &debug;
722 $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
727 print $fh "type:error Error during direct_messages call. Aborted.\n";
731 foreach my $t ( reverse @$tweets ) {
732 my $text = decode_entities( $t->{text} );
734 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
735 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
736 $t->{id}, $username, $t->{sender_screen_name}, $text;
738 print scalar localtime, " - Done" if &debug;
744 my ( $data, $attempt ) = @_;
745 my $filename = $data->[0];
747 print scalar localtime, " - checking child log at $filename" if &debug;
748 my $old_last_poll = $last_poll;
749 if ( open FILE, $filename ) {
753 last if /^__friends__/;
755 foreach my $key (qw/id account nick type/) {
760 next if exists $tweet_cache{ $meta{id} };
761 $tweet_cache{ $meta{id} } = time;
763 if ( $meta{account} ne $user ) {
764 $account = "$meta{account}: ";
768 if ( $meta{type} ne 'dm'
769 and Irssi::settings_get_bool("twirssi_track_replies")
773 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
774 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
775 $id_map{__indexes}{ $meta{nick} } = $marker;
776 $marker = ":$marker";
779 if ( $meta{type} eq 'tweet' ) {
780 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
781 } elsif ( $meta{type} eq 'reply' ) {
782 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
783 } elsif ( $meta{type} eq 'dm' ) {
784 push @lines, "[$account%B\@$meta{nick}%n (%WDM%n)] $_\n",;
785 } elsif ( $meta{type} eq 'error' ) {
786 push @lines, "error: $_\n" if &debug,;
787 } elsif ( $meta{type} eq 'debug' ) {
788 push @lines, "debug: $_\n" if &debug,;
798 my ( $f, $t ) = split ' ', $_;
799 $nicks{$f} = $friends{$f} = $t;
802 if ( $last_poll != $old_last_poll ) {
803 print "new last_poll = $last_poll" if &debug;
804 foreach my $line (@lines) {
806 $window->print( $line, MSGLEVEL_PUBLIC );
807 foreach ( $line =~ /\@([-\w]+)/ ) {
814 or warn "Failed to remove $filename: $!"
817 # keep enough cached tweets, to make sure we don't show duplicates.
818 foreach ( keys %tweet_cache ) {
819 next if $tweet_cache{$_} >= $old_last_poll;
820 delete $tweet_cache{$_};
826 Irssi::settings_get_str("twirssi_replies_store") )
828 if ( open JSON, ">$file" ) {
829 print JSON JSON::Any->objToJson( \%id_map );
832 ¬ice("Failed to write replies to $file: $!");
841 if ( $attempt < 12 ) {
842 Irssi::timeout_add_once( 5000, 'monitor_child',
843 [ $filename, $attempt + 1 ] );
845 ¬ice("Giving up on polling $filename");
846 unlink $filename unless &debug;
851 return Irssi::settings_get_bool("twirssi_debug");
855 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
859 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
861 # /twitter_reply gets a nick:num
862 if ( $linestart =~ /^\/twitter_reply(?:_as)?\s*$/ ) {
863 @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
866 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
868 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
869 my $prefix = $word =~ s/^@//;
870 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
871 push @$complist, grep /^\Q$word/i,
872 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
873 @$complist = map { "\@$_" } @$complist if $prefix;
877 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
878 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
879 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
880 Irssi::settings_add_str( "twirssi", "twirssi_location",
881 ".irssi/scripts/twirssi.pl" );
882 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
883 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
884 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
885 ".irssi/scripts/twirssi.json" );
886 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
887 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
888 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
889 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
890 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
891 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
892 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
895 Irssi::command_bind( "dm", "cmd_direct" );
896 Irssi::command_bind( "dm_as", "cmd_direct_as" );
897 Irssi::command_bind( "tweet", "cmd_tweet" );
898 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
899 Irssi::command_bind( "twitter_reply", "cmd_reply" );
900 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
901 Irssi::command_bind( "twitter_login", "cmd_login" );
902 Irssi::command_bind( "twitter_logout", "cmd_logout" );
903 Irssi::command_bind( "twitter_switch", "cmd_switch" );
904 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
908 print "twits: ", join ", ",
909 map { "u: $_->{username}" } values %twits;
910 print "friends: ", join ", ", sort keys %friends;
911 print "nicks: ", join ", ", sort keys %nicks;
912 print "id_map: ", Dumper \%{ $id_map{__indexes} };
913 print "last poll: $last_poll";
920 "Twirssi v$VERSION (r$REV); Net::Twitter v$Net::Twitter::VERSION. "
921 . "See details at http://tinyurl.com/twirssi" );
927 "/twitter_friend <username>",
929 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
935 "/twitter_unfriend <username>",
937 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
940 Irssi::command_bind( "twitter_updates", "get_updates" );
941 Irssi::signal_add_last( 'complete word' => \&sig_complete );
943 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
944 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
946 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
948 my $file = Irssi::settings_get_str("twirssi_replies_store");
949 if ( $file and -r $file ) {
950 if ( open( JSON, $file ) ) {
955 my $ref = JSON::Any->jsonToObj($json);
957 my $num = keys %{ $id_map{__indexes} };
958 ¬ice( sprintf "Loaded old replies from %d contact%s.",
959 $num, ( $num == 1 ? "" : "s" ) );
962 ¬ice("Failed to load old replies from $file: $!");
966 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
967 eval "use WWW::Shorten::$provider;";
971 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
976 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
977 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
984 ->print( "Create a window named "
985 . Irssi::settings_get_str('twitter_window')
986 . " or change the value of twitter_window. Then, reload twirssi." );