10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
15 my ($REV) = '$Rev: 335 $' =~ /(\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");
74 unless ( $twits{$username}
75 ->new_direct_message( { user => $target, text => $text } ) )
77 ¬ice("DM to $target failed");
81 ¬ice("DM sent to $target");
82 $nicks{$target} = time;
86 my ( $data, $server, $win ) = @_;
89 ¬ice("Not logged in! Use /twitter_login username pass!");
93 $data =~ s/^\s+|\s+$//;
95 ¬ice("Usage: /tweet <update>");
99 &cmd_tweet_as( "$user $data", $server, $win );
103 my ( $data, $server, $win ) = @_;
106 ¬ice("Not logged in! Use /twitter_login username pass!");
110 $data =~ s/^\s+|\s+$//;
111 my ( $username, $data ) = split ' ', $data, 2;
113 unless ( $username and $data ) {
114 ¬ice("Usage: /tweet_as <username> <update>");
118 unless ( exists $twits{$username} ) {
119 ¬ice("Unknown username $username");
123 if ( Irssi::settings_get_str("short_url_provider") ) {
124 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
126 my $short = makeashorterlink($url);
127 $data =~ s/\Q$url/$short/g;
132 if ( length $data > 140 ) {
134 "Tweet too long (" . length($data) . " characters) - aborted" );
138 unless ( $twits{$username}->update($data) ) {
139 ¬ice("Update failed");
143 foreach ( $data =~ /@([-\w]+)/ ) {
148 if ( Irssi::settings_get_bool("tweet_to_away")
150 and $data !~ /^[dD] / )
153 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
155 $server->send_raw("away :$data");
158 ¬ice( "Can't find bitlbee server.",
159 "Update bitlbee_server or disalbe tweet_to_away" );
163 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
167 my ( $data, $server, $win ) = @_;
170 ¬ice("Not logged in! Use /twitter_login username pass!");
174 $data =~ s/^\s+|\s+$//;
176 ¬ice("Usage: /reply <nick[:num]> <update>");
180 $data =~ s/^\s+|\s+$//;
181 my ( $id, $data ) = split ' ', $data, 2;
182 unless ( $id and $data ) {
183 ¬ice("Usage: /reply_as <nick[:num]> <update>");
187 &cmd_reply_as( "$user $id $data", $server, $win );
191 my ( $data, $server, $win ) = @_;
193 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
194 ¬ice("twirssi_track_replies is required in order to reply to "
195 . "specific tweets. Either enable it, or just use /tweet "
196 . "\@username <text>." );
201 ¬ice("Not logged in! Use /twitter_login username pass!");
205 $data =~ s/^\s+|\s+$//;
206 my ( $username, $id, $data ) = split ' ', $data, 3;
208 unless ( $username and $data ) {
209 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
213 unless ( exists $twits{$username} ) {
214 ¬ice("Unknown username $username");
219 $id =~ s/[^\w\d\-:]+//g;
220 ( $nick, $id ) = split /:/, $id;
221 unless ( exists $id_map{$nick} ) {
222 ¬ice("Can't find a tweet from $nick to reply to!");
226 $id = $id_map{__indexes}{$nick} unless $id;
227 unless ( $id_map{lc $nick}[$id] ) {
228 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
232 # remove any @nick at the beginning of the reply, as we'll add it anyway
233 $data =~ s/^\s*\@?$nick\s*//;
234 $data = "\@$nick " . $data;
236 if ( Irssi::settings_get_str("short_url_provider") ) {
237 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
239 my $short = makeashorterlink($url);
240 $data =~ s/\Q$url/$short/g;
245 if ( length $data > 140 ) {
247 "Tweet too long (" . length($data) . " characters) - aborted" );
252 $twits{$username}->update(
253 { status => $data, in_reply_to_status_id => $id_map{lc $nick}[$id] }
257 ¬ice("Update failed");
261 foreach ( $data =~ /@([-\w]+)/ ) {
266 if ( Irssi::settings_get_bool("tweet_to_away")
268 and $data !~ /^[dD] / )
271 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
273 $server->send_raw("away :$data");
276 ¬ice( "Can't find bitlbee server.",
277 "Update bitlbee_server or disalbe tweet_to_away" );
281 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
285 my ( $usage_str, $api_name, $post_ref ) = @_;
288 my ( $data, $server, $win ) = @_;
291 ¬ice("Not logged in! Use /twitter_login username pass!");
295 $data =~ s/^\s+|\s+$//;
297 ¬ice("Usage: $usage_str");
301 unless ( $twit->$api_name($data) ) {
302 ¬ice("$api_name failed");
306 &$post_ref($data) if $post_ref;
311 my ( $data, $server, $win ) = @_;
313 $data =~ s/^\s+|\s+$//g;
314 if ( exists $twits{$data} ) {
315 ¬ice("Switching to $data");
316 $twit = $twits{$data};
319 ¬ice("Unknown user $data");
324 my ( $data, $server, $win ) = @_;
326 $data =~ s/^\s+|\s+$//g;
327 if ( $data and exists $twits{$data} ) {
328 ¬ice("Logging out $data...");
329 $twits{$data}->end_session();
330 delete $twits{$data};
332 ¬ice("Unknown username '$data'");
334 ¬ice("Logging out $user...");
335 $twit->end_session();
337 delete $twits{$user};
339 &cmd_switch( ( keys %twits )[0], $server, $win );
341 Irssi::timeout_remove($poll) if $poll;
348 my ( $data, $server, $win ) = @_;
351 ( $user, $pass ) = split ' ', $data, 2;
352 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
353 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
355 my @user = split /\s*,\s*/, $autouser;
356 my @pass = split /\s*,\s*/, $autopass;
357 if ( @user != @pass ) {
358 ¬ice("Number of usernames doesn't match "
359 . "the number of passwords - auto-login failed" );
362 while ( @user and @pass ) {
370 ¬ice("/twitter_login requires either a username and password "
371 . "or twitter_usernames and twitter_passwords to be set." );
375 %friends = %nicks = ();
377 $twit = Net::Twitter->new(
383 unless ( $twit->verify_credentials() ) {
384 ¬ice("Login as $user failed");
387 &cmd_switch( ( keys %twits )[0], $server, $win );
393 my $rate_limit = $twit->rate_limit_status();
394 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
395 ¬ice("Rate limit exceeded, try again later");
400 $twits{$user} = $twit;
401 Irssi::timeout_remove($poll) if $poll;
402 $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
403 ¬ice("Logged in as $user, loading friends list...");
405 ¬ice( "loaded friends: ", scalar keys %friends );
406 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
407 Irssi::settings_set_bool( "twirssi_first_run", 0 );
408 unless ( exists $friends{twirssi} ) {
409 ¬ice("Welcome to twirssi!"
410 . " Perhaps you should add \@twirssi to your friends list,"
411 . " so you can be notified when a new version is release?"
412 . " Just type /twitter_friend twirssi." );
419 ¬ice("Login failed");
424 my ( $data, $server, $win ) = @_;
426 my $loc = Irssi::settings_get_str("twirssi_location");
429 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
434 if ( not -x "/usr/bin/md5sum" and not $data ) {
436 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
443 eval { use Digest::MD5; };
447 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
452 $md5 = get("http://twirssi.com/md5sum");
456 ¬ice("Failed to download md5sum from peeron! Aborting.");
460 unless ( open( CUR, $loc ) ) {
462 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
467 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
470 if ( $cur_md5 eq $md5 ) {
471 ¬ice("Current twirssi seems to be up to date.");
476 my $URL = "http://twirssi.com/twirssi.pl";
477 ¬ice("Downloading twirssi from $URL");
478 LWP::Simple::getstore( $URL, "$loc.upgrade" );
481 unless ( open( NEW, "$loc.upgrade" ) ) {
483 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
488 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
491 if ( $new_md5 ne $md5 ) {
492 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
497 rename $loc, "$loc.backup"
498 or ¬ice("Failed to back up $loc: $!. Aborting")
500 rename "$loc.upgrade", $loc
501 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
504 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
505 if ( -e "$dir/autorun/$file" ) {
506 ¬ice("Updating $dir/autorun/$file");
507 unlink "$dir/autorun/$file"
508 or ¬ice("Failed to remove old $file from autorun: $!");
509 symlink "../$file", "$dir/autorun/$file"
510 or ¬ice("Failed to create symlink in autorun directory: $!");
513 ¬ice("Download complete. Reload twirssi with /script load $file");
521 print $fh "Loading friends page $page...\n" if ( $fh and &debug );
522 my $friends = $twit->friends( { page => $page } );
523 last unless $friends;
524 $new_friends{ $_->{screen_name} } = time foreach @$friends;
526 last if @$friends == 0 or $page == 10;
529 my ( $added, $removed ) = ( 0, 0 );
530 print $fh "Scanning for new friends...\n" if ( $fh and &debug );
531 foreach ( keys %new_friends ) {
532 next if exists $friends{$_};
537 print $fh "Scanning for removed friends...\n" if ( $fh and &debug );
538 foreach ( keys %friends ) {
539 next if exists $new_friends{$_};
544 return ( $added, $removed );
548 print scalar localtime, " - get_updates starting" if &debug;
551 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
554 ->print( "Can't find a window named '"
555 . Irssi::settings_get_str('twitter_window')
556 . "'. Create it or change the value of twitter_window" );
559 ¬ice("Not logged in! Use /twitter_login username pass!");
563 my ( $fh, $filename ) = File::Temp::tempfile();
567 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
568 Irssi::pidwait_add($pid);
569 } elsif ( defined $pid ) { # child
576 &do_updates( $fh, $user, $twit );
577 foreach ( keys %twits ) {
579 &do_updates( $fh, $_, $twits{$_} );
582 my ( $added, $removed ) = &load_friends($fh);
583 if ( $added + $removed ) {
584 print $fh "%R***%n Friends list updated: ",
586 sprintf( "%d added", $added ),
587 sprintf( "%d removed", $removed ) ),
590 print $fh "__friends__\n";
591 foreach ( sort keys %friends ) {
592 print $fh "$_ $friends{$_}\n";
598 print scalar localtime, " - get_updates ends" if &debug;
602 my ( $fh, $username, $obj ) = @_;
604 print scalar localtime, " - Polling for updates for $username" if &debug;
606 $obj->friends_timeline( { since => HTTP::Date::time2str($last_poll) } )
608 foreach my $t ( reverse @$tweets ) {
609 my $text = decode_entities( $t->{text} );
611 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
613 if ( Irssi::settings_get_bool("show_reply_context")
614 and $t->{in_reply_to_screen_name} ne $username
615 and $t->{in_reply_to_screen_name}
616 and not exists $friends{ $t->{in_reply_to_screen_name} } )
618 $nicks{ $t->{in_reply_to_screen_name} } = time;
619 my $context = $obj->show_status( $t->{in_reply_to_status_id} );
621 my $ctext = decode_entities( $context->{text} );
623 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
624 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
625 $context->{id}, $username,
626 $context->{user}{screen_name}, $ctext;
629 print "Failed to get context from $t->{in_reply_to_screen_name}"
634 if $t->{user}{screen_name} eq $username
635 and not Irssi::settings_get_bool("show_own_tweets");
636 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
637 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
640 print scalar localtime, " - Polling for replies" if &debug;
641 $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
643 foreach my $t ( reverse @$tweets ) {
645 if exists $friends{ $t->{user}{screen_name} };
647 my $text = decode_entities( $t->{text} );
649 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
650 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
651 $t->{id}, $username, $t->{user}{screen_name}, $text;
654 print scalar localtime, " - Polling for DMs" if &debug;
656 $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
658 foreach my $t ( reverse @$tweets ) {
659 my $text = decode_entities( $t->{text} );
661 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
662 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
663 $t->{id}, $username, $t->{sender_screen_name}, $text;
665 print scalar localtime, " - Done" if &debug;
670 my $filename = $data->[0];
672 print scalar localtime, " - checking child log at $filename" if &debug;
673 my $old_last_poll = $last_poll;
674 if ( open FILE, $filename ) {
678 last if /^__friends__/;
680 foreach my $key (qw/id account nick type/) {
685 next if exists $tweet_cache{ $meta{id} };
686 $tweet_cache{ $meta{id} } = time;
688 if ( $meta{account} ne $user ) {
689 $account = "$meta{account}: ";
693 if ( $meta{type} ne 'dm'
694 and Irssi::settings_get_bool("twirssi_track_replies")
698 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
699 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
700 $id_map{__indexes}{ $meta{nick} } = $marker;
701 $marker = ":$marker";
704 if ( $meta{type} eq 'tweet' ) {
705 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
706 } elsif ( $meta{type} eq 'reply' ) {
707 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
708 } elsif ( $meta{type} eq 'dm' ) {
709 push @lines, "[$account%B\@$meta{nick}%n (%%WDM%%n)] $_\n",;
710 } elsif ( $meta{type} eq 'debug' ) {
711 push @lines, "debug: $_\n" if &debug,;
721 my ( $f, $t ) = split ' ', $_;
722 $nicks{$f} = $friends{$f} = $t;
725 if ( $last_poll != $old_last_poll ) {
726 print "new last_poll = $last_poll" if &debug;
727 foreach my $line (@lines) {
729 $window->print( $line, MSGLEVEL_PUBLIC );
730 foreach ( $line =~ /\@([-\w]+)/ ) {
737 or warn "Failed to remove $filename: $!"
740 # keep 10 minutes of cached tweets, to make sure we don't show duplicates.
741 foreach ( keys %tweet_cache ) {
742 next if $tweet_cache{$_} > time - 600;
743 delete $tweet_cache{$_};
750 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
754 return Irssi::settings_get_bool("twirssi_debug");
758 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
762 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
765 $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
766 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
767 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
769 { # /twitter_reply gets a nick:num
770 @$complist = grep /^\Q$word/i, sort keys %{$id_map{__indexes}};
773 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
775 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
776 my $prefix = $word =~ s/^@//;
777 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
778 push @$complist, grep /^\Q$word/i,
779 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
780 @$complist = map { "\@$_" } @$complist if $prefix;
784 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
785 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
786 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
787 Irssi::settings_add_str( "twirssi", "twirssi_location",
788 ".irssi/scripts/twirssi.pl" );
789 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
790 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
791 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
792 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
793 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
794 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
795 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
796 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
797 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
798 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
801 Irssi::command_bind( "dm", "cmd_direct" );
802 Irssi::command_bind( "dm_as", "cmd_direct_as" );
803 Irssi::command_bind( "tweet", "cmd_tweet" );
804 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
805 Irssi::command_bind( "twitter_reply", "cmd_reply" );
806 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
807 Irssi::command_bind( "twitter_login", "cmd_login" );
808 Irssi::command_bind( "twitter_logout", "cmd_logout" );
809 Irssi::command_bind( "twitter_switch", "cmd_switch" );
810 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
811 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
812 Irssi::command_bind( "reply", "cmd_reply" );
813 Irssi::command_bind( "reply_as", "cmd_reply_as" );
818 print "twits: ", Dumper \%twits;
819 print "friends: ", join ", ", sort keys %friends;
820 print "nicks: ", join ", ", sort keys %nicks;
821 print "last poll: $last_poll";
828 "Twirssi v$VERSION (r$REV); Net::Twitter v$Net::Twitter::VERSION. "
829 . "See details at http://tinyurl.com/twirssi" );
835 "/twitter_friend <username>",
837 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
843 "/twitter_unfriend <username>",
845 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
848 Irssi::command_bind( "twitter_updates", "get_updates" );
849 Irssi::signal_add_last( 'complete word' => \&sig_complete );
851 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
852 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
854 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
856 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
857 eval "use WWW::Shorten::$provider;";
861 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
866 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
867 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
874 ->print( "Create a window named "
875 . Irssi::settings_get_str('twitter_window')
876 . " or change the value of twitter_window. Then, reload twirssi." );