10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
15 my ($REV) = '$Rev: 349 $' =~ /(\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 11:16:45 -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 "type:debug Loading friends page $page...\n"
557 if ( $fh and &debug );
558 my $friends = $twit->friends( { page => $page } );
559 last unless $friends;
560 $new_friends{ $_->{screen_name} } = time foreach @$friends;
562 last if @$friends == 0 or $page == 10;
567 print $fh "type:error Error during friends list update. Aborted.\n";
571 my ( $added, $removed ) = ( 0, 0 );
572 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
573 foreach ( keys %new_friends ) {
574 next if exists $friends{$_};
579 print $fh "type:debug Scanning for removed friends...\n"
580 if ( $fh and &debug );
581 foreach ( keys %friends ) {
582 next if exists $new_friends{$_};
587 return ( $added, $removed );
591 print scalar localtime, " - get_updates starting" if &debug;
594 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
597 ->print( "Can't find a window named '"
598 . Irssi::settings_get_str('twitter_window')
599 . "'. Create it or change the value of twitter_window" );
602 ¬ice("Not logged in! Use /twitter_login username pass!");
606 my ( $fh, $filename ) = File::Temp::tempfile();
610 Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
611 Irssi::pidwait_add($pid);
612 } elsif ( defined $pid ) { # child
620 $error += &do_updates( $fh, $user, $twit );
621 foreach ( keys %twits ) {
623 $error += &do_updates( $fh, $_, $twits{$_} );
626 my ( $added, $removed ) = &load_friends($fh);
627 if ( $added + $removed ) {
628 print $fh "type:debug %R***%n Friends list updated: ",
630 sprintf( "%d added", $added ),
631 sprintf( "%d removed", $removed ) ),
634 print $fh "__friends__\n";
635 foreach ( sort keys %friends ) {
636 print $fh "$_ $friends{$_}\n";
640 print $fh "type:error Update encountered errors. Aborted\n";
641 print $fh $last_poll;
648 print scalar localtime, " - get_updates ends" if &debug;
652 my ( $fh, $username, $obj ) = @_;
654 print scalar localtime, " - Polling for updates for $username" if &debug;
657 $tweets = $obj->friends_timeline(
658 { since => HTTP::Date::time2str($last_poll) } );
662 print $fh "type:error Error during friends_timeline call. Aborted.\n";
666 unless ( ref $tweets ) {
667 if ( $obj->can("get_error") ) {
668 print $fh "type:error API Error during friends_timeline call: ",
669 JSON::Any->jsonToObj( $obj->get_error() ), " Aborted.\n";
672 "type:error API Error during friends_timeline call. Aborted.\n";
677 foreach my $t ( reverse @$tweets ) {
678 my $text = decode_entities( $t->{text} );
680 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
682 if ( Irssi::settings_get_bool("show_reply_context")
683 and $t->{in_reply_to_screen_name} ne $username
684 and $t->{in_reply_to_screen_name}
685 and not exists $friends{ $t->{in_reply_to_screen_name} } )
687 $nicks{ $t->{in_reply_to_screen_name} } = time;
688 my $context = $obj->show_status( $t->{in_reply_to_status_id} );
690 my $ctext = decode_entities( $context->{text} );
692 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
693 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
694 $context->{id}, $username,
695 $context->{user}{screen_name}, $ctext;
698 print "Failed to get context from $t->{in_reply_to_screen_name}"
703 if $t->{user}{screen_name} eq $username
704 and not Irssi::settings_get_bool("show_own_tweets");
705 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
706 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
709 print scalar localtime, " - Polling for replies" if &debug;
711 $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
716 print $fh "type:error Error during replies call. Aborted.\n";
720 foreach my $t ( reverse @$tweets ) {
722 if exists $friends{ $t->{user}{screen_name} };
724 my $text = decode_entities( $t->{text} );
726 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
727 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
728 $t->{id}, $username, $t->{user}{screen_name}, $text;
731 print scalar localtime, " - Polling for DMs" if &debug;
734 $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
739 print $fh "type:error Error during direct_messages call. Aborted.\n";
743 foreach my $t ( reverse @$tweets ) {
744 my $text = decode_entities( $t->{text} );
746 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
747 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
748 $t->{id}, $username, $t->{sender_screen_name}, $text;
750 print scalar localtime, " - Done" if &debug;
757 my $filename = $data->[0];
758 my $attempt = $data->[1];
760 print scalar localtime, " - checking child log at $filename ($attempt)"
763 if ( open FILE, $filename ) {
767 last if /^__friends__/;
769 foreach my $key (qw/id account nick type/) {
770 if (s/^$key:(\S+)\s*//) {
775 next if exists $meta{id} and exists $tweet_cache{ $meta{id} };
776 $tweet_cache{ $meta{id} } = time;
778 if ( $meta{account} ne $user ) {
779 $account = "$meta{account}: ";
783 if ( $meta{type} ne 'dm'
784 and Irssi::settings_get_bool("twirssi_track_replies")
788 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
789 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
790 $id_map{__indexes}{ $meta{nick} } = $marker;
791 $marker = ":$marker";
794 if ( $meta{type} eq 'tweet' ) {
795 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
796 } elsif ( $meta{type} eq 'reply' ) {
797 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
798 } elsif ( $meta{type} eq 'dm' ) {
799 push @lines, "[$account%B\@$meta{nick}%n (%WDM%n)] $_\n",;
800 } elsif ( $meta{type} eq 'error' ) {
801 push @lines, "ERROR: $_\n";
802 } elsif ( $meta{type} eq 'debug' ) {
803 print "$_" if &debug,;
805 print "Unknown line type $meta{type}: $_" if &debug,;
815 my ( $f, $t ) = split ' ', $_;
816 $nicks{$f} = $friends{$f} = $t;
819 if ($new_last_poll) {
820 print "new last_poll = $new_last_poll" if &debug;
821 foreach my $line (@lines) {
823 $window->print( $line, MSGLEVEL_PUBLIC );
824 foreach ( $line =~ /\@([-\w]+)/ ) {
831 or warn "Failed to remove $filename: $!"
834 # keep enough cached tweets, to make sure we don't show duplicates.
835 foreach ( keys %tweet_cache ) {
836 next if $tweet_cache{$_} >= $last_poll;
837 delete $tweet_cache{$_};
839 $last_poll = $new_last_poll;
844 Irssi::settings_get_str("twirssi_replies_store") )
846 if ( open JSON, ">$file" ) {
847 print JSON JSON::Any->objToJson( \%id_map );
850 ¬ice("Failed to write replies to $file: $!");
859 if ( $attempt < 12 ) {
860 Irssi::timeout_add_once( 5000, 'monitor_child',
861 [ $filename, $attempt + 1 ] );
863 ¬ice("Giving up on polling $filename");
864 unlink $filename unless &debug;
869 return Irssi::settings_get_bool("twirssi_debug");
873 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
877 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
879 # /twitter_reply gets a nick:num
880 if ( $linestart =~ /^\/twitter_reply(?:_as)?\s*$/ ) {
881 @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
884 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
886 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
887 my $prefix = $word =~ s/^@//;
888 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
889 push @$complist, grep /^\Q$word/i,
890 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
891 @$complist = map { "\@$_" } @$complist if $prefix;
895 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
896 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
897 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
898 Irssi::settings_add_str( "twirssi", "twirssi_location",
899 ".irssi/scripts/twirssi.pl" );
900 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
901 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
902 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
903 ".irssi/scripts/twirssi.json" );
904 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
905 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
906 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
907 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
908 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
909 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
910 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
913 Irssi::command_bind( "dm", "cmd_direct" );
914 Irssi::command_bind( "dm_as", "cmd_direct_as" );
915 Irssi::command_bind( "tweet", "cmd_tweet" );
916 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
917 Irssi::command_bind( "twitter_reply", "cmd_reply" );
918 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
919 Irssi::command_bind( "twitter_login", "cmd_login" );
920 Irssi::command_bind( "twitter_logout", "cmd_logout" );
921 Irssi::command_bind( "twitter_switch", "cmd_switch" );
922 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
926 print "twits: ", join ", ",
927 map { "u: $_->{username}" } values %twits;
928 print "friends: ", join ", ", sort keys %friends;
929 print "nicks: ", join ", ", sort keys %nicks;
930 print "id_map: ", Dumper \%{ $id_map{__indexes} };
931 print "last poll: $last_poll";
938 "Twirssi v$VERSION (r$REV); Net::Twitter v$Net::Twitter::VERSION. "
939 . "See details at http://tinyurl.com/twirssi" );
945 "/twitter_friend <username>",
947 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
953 "/twitter_unfriend <username>",
955 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
958 Irssi::command_bind( "twitter_updates", "get_updates" );
959 Irssi::signal_add_last( 'complete word' => \&sig_complete );
961 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
962 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
964 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
966 my $file = Irssi::settings_get_str("twirssi_replies_store");
967 if ( $file and -r $file ) {
968 if ( open( JSON, $file ) ) {
973 my $ref = JSON::Any->jsonToObj($json);
975 my $num = keys %{ $id_map{__indexes} };
976 ¬ice( sprintf "Loaded old replies from %d contact%s.",
977 $num, ( $num == 1 ? "" : "s" ) );
980 ¬ice("Failed to load old replies from $file: $!");
984 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
985 eval "use WWW::Shorten::$provider;";
989 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
994 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
995 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1002 ->print( "Create a window named "
1003 . Irssi::settings_get_str('twitter_window')
1004 . " or change the value of twitter_window. Then, reload twirssi." );