10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
15 my ($REV) = '$Rev: 334 $' =~ /(\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 ( $nick, $id ) = split /:/, $id;
220 unless ( exists $id_map{$nick} ) {
221 ¬ice("Can't find a tweet from $nick to reply to!");
225 $id = $id_map{__indexes}{$nick} unless $id;
226 unless ( $id_map{$nick}[$id] ) {
227 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
231 # remove any @nick at the beginning of the reply, as we'll add it anyway
232 $data =~ s/^\s*\@?$nick\s*//;
233 $data = "\@$nick " . $data;
235 if ( Irssi::settings_get_str("short_url_provider") ) {
236 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
238 my $short = makeashorterlink($url);
239 $data =~ s/\Q$url/$short/g;
244 if ( length $data > 140 ) {
246 "Tweet too long (" . length($data) . " characters) - aborted" );
251 $twits{$username}->update(
252 { status => $data, in_reply_to_status_id => $id_map{$nick}[$id] }
256 ¬ice("Update failed");
260 foreach ( $data =~ /@([-\w]+)/ ) {
265 if ( Irssi::settings_get_bool("tweet_to_away")
267 and $data !~ /^[dD] / )
270 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
272 $server->send_raw("away :$data");
275 ¬ice( "Can't find bitlbee server.",
276 "Update bitlbee_server or disalbe tweet_to_away" );
280 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
284 my ( $usage_str, $api_name, $post_ref ) = @_;
287 my ( $data, $server, $win ) = @_;
290 ¬ice("Not logged in! Use /twitter_login username pass!");
294 $data =~ s/^\s+|\s+$//;
296 ¬ice("Usage: $usage_str");
300 unless ( $twit->$api_name($data) ) {
301 ¬ice("$api_name failed");
305 &$post_ref($data) if $post_ref;
310 my ( $data, $server, $win ) = @_;
312 $data =~ s/^\s+|\s+$//g;
313 if ( exists $twits{$data} ) {
314 ¬ice("Switching to $data");
315 $twit = $twits{$data};
318 ¬ice("Unknown user $data");
323 my ( $data, $server, $win ) = @_;
325 $data =~ s/^\s+|\s+$//g;
326 if ( $data and exists $twits{$data} ) {
327 ¬ice("Logging out $data...");
328 $twits{$data}->end_session();
329 delete $twits{$data};
331 ¬ice("Unknown username '$data'");
333 ¬ice("Logging out $user...");
334 $twit->end_session();
336 delete $twits{$user};
338 &cmd_switch( ( keys %twits )[0], $server, $win );
340 Irssi::timeout_remove($poll) if $poll;
347 my ( $data, $server, $win ) = @_;
350 ( $user, $pass ) = split ' ', $data, 2;
351 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
352 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
354 my @user = split /\s*,\s*/, $autouser;
355 my @pass = split /\s*,\s*/, $autopass;
356 if ( @user != @pass ) {
357 ¬ice("Number of usernames doesn't match "
358 . "the number of passwords - auto-login failed" );
361 while ( @user and @pass ) {
369 ¬ice("/twitter_login requires either a username and password "
370 . "or twitter_usernames and twitter_passwords to be set." );
374 %friends = %nicks = ();
376 $twit = Net::Twitter->new(
382 unless ( $twit->verify_credentials() ) {
383 ¬ice("Login as $user failed");
386 &cmd_switch( ( keys %twits )[0], $server, $win );
392 my $rate_limit = $twit->rate_limit_status();
393 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
394 ¬ice("Rate limit exceeded, try again later");
399 $twits{$user} = $twit;
400 Irssi::timeout_remove($poll) if $poll;
401 $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
402 ¬ice("Logged in as $user, loading friends list...");
404 ¬ice( "loaded friends: ", scalar keys %friends );
405 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
406 Irssi::settings_set_bool( "twirssi_first_run", 0 );
407 unless ( exists $friends{twirssi} ) {
408 ¬ice("Welcome to twirssi!"
409 . " Perhaps you should add \@twirssi to your friends list,"
410 . " so you can be notified when a new version is release?"
411 . " Just type /twitter_friend twirssi." );
418 ¬ice("Login failed");
423 my ( $data, $server, $win ) = @_;
425 my $loc = Irssi::settings_get_str("twirssi_location");
428 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
433 if ( not -x "/usr/bin/md5sum" and not $data ) {
435 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
442 eval { use Digest::MD5; };
446 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
451 $md5 = get("http://twirssi.com/md5sum");
455 ¬ice("Failed to download md5sum from peeron! Aborting.");
459 unless ( open( CUR, $loc ) ) {
461 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
466 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
469 if ( $cur_md5 eq $md5 ) {
470 ¬ice("Current twirssi seems to be up to date.");
475 my $URL = "http://twirssi.com/twirssi.pl";
476 ¬ice("Downloading twirssi from $URL");
477 LWP::Simple::getstore( $URL, "$loc.upgrade" );
480 unless ( open( NEW, "$loc.upgrade" ) ) {
482 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
487 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
490 if ( $new_md5 ne $md5 ) {
491 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
496 rename $loc, "$loc.backup"
497 or ¬ice("Failed to back up $loc: $!. Aborting")
499 rename "$loc.upgrade", $loc
500 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
503 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
504 if ( -e "$dir/autorun/$file" ) {
505 ¬ice("Updating $dir/autorun/$file");
506 unlink "$dir/autorun/$file"
507 or ¬ice("Failed to remove old $file from autorun: $!");
508 symlink "../$file", "$dir/autorun/$file"
509 or ¬ice("Failed to create symlink in autorun directory: $!");
512 ¬ice("Download complete. Reload twirssi with /script load $file");
520 print $fh "Loading friends page $page...\n" if ( $fh and &debug );
521 my $friends = $twit->friends( { page => $page } );
522 last unless $friends;
523 $new_friends{ $_->{screen_name} } = time foreach @$friends;
525 last if @$friends == 0 or $page == 10;
528 my ( $added, $removed ) = ( 0, 0 );
529 print $fh "Scanning for new friends...\n" if ( $fh and &debug );
530 foreach ( keys %new_friends ) {
531 next if exists $friends{$_};
536 print $fh "Scanning for removed friends...\n" if ( $fh and &debug );
537 foreach ( keys %friends ) {
538 next if exists $new_friends{$_};
543 return ( $added, $removed );
547 print scalar localtime, " - get_updates starting" if &debug;
550 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
553 ->print( "Can't find a window named '"
554 . Irssi::settings_get_str('twitter_window')
555 . "'. Create it or change the value of twitter_window" );
558 ¬ice("Not logged in! Use /twitter_login username pass!");
562 my ( $fh, $filename ) = File::Temp::tempfile();
566 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
567 Irssi::pidwait_add($pid);
568 } elsif ( defined $pid ) { # child
575 &do_updates( $fh, $user, $twit );
576 foreach ( keys %twits ) {
578 &do_updates( $fh, $_, $twits{$_} );
581 my ( $added, $removed ) = &load_friends($fh);
582 if ( $added + $removed ) {
583 print $fh "%R***%n Friends list updated: ",
585 sprintf( "%d added", $added ),
586 sprintf( "%d removed", $removed ) ),
589 print $fh "__friends__\n";
590 foreach ( sort keys %friends ) {
591 print $fh "$_ $friends{$_}\n";
597 print scalar localtime, " - get_updates ends" if &debug;
601 my ( $fh, $username, $obj ) = @_;
603 print scalar localtime, " - Polling for updates for $username" if &debug;
605 $obj->friends_timeline( { since => HTTP::Date::time2str($last_poll) } )
607 foreach my $t ( reverse @$tweets ) {
608 my $text = decode_entities( $t->{text} );
610 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
612 if ( Irssi::settings_get_bool("show_reply_context")
613 and $t->{in_reply_to_screen_name} ne $username
614 and $t->{in_reply_to_screen_name}
615 and not exists $friends{ $t->{in_reply_to_screen_name} } )
617 $nicks{ $t->{in_reply_to_screen_name} } = time;
618 my $context = $obj->show_status( $t->{in_reply_to_status_id} );
620 my $ctext = decode_entities( $context->{text} );
622 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
623 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
624 $context->{id}, $username,
625 $context->{user}{screen_name}, $ctext;
628 print "Failed to get context from $t->{in_reply_to_screen_name}"
633 if $t->{user}{screen_name} eq $username
634 and not Irssi::settings_get_bool("show_own_tweets");
635 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
636 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
639 print scalar localtime, " - Polling for replies" if &debug;
640 $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
642 foreach my $t ( reverse @$tweets ) {
644 if exists $friends{ $t->{user}{screen_name} };
646 my $text = decode_entities( $t->{text} );
648 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
649 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
650 $t->{id}, $username, $t->{user}{screen_name}, $text;
653 print scalar localtime, " - Polling for DMs" if &debug;
655 $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
657 foreach my $t ( reverse @$tweets ) {
658 my $text = decode_entities( $t->{text} );
660 $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
661 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
662 $t->{id}, $username, $t->{sender_screen_name}, $text;
664 print scalar localtime, " - Done" if &debug;
669 my $filename = $data->[0];
671 print scalar localtime, " - checking child log at $filename" if &debug;
672 my $old_last_poll = $last_poll;
673 if ( open FILE, $filename ) {
677 last if /^__friends__/;
679 foreach my $key (qw/id account nick type/) {
684 next if exists $tweet_cache{ $meta{id} };
685 $tweet_cache{ $meta{id} } = time;
687 if ( $meta{account} ne $user ) {
688 $account = "$meta{account}: ";
692 if ( $meta{type} ne 'dm'
693 and Irssi::settings_get_bool("twirssi_track_replies")
697 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
698 $id_map{ $meta{nick} }[$marker] = $meta{id};
699 $id_map{__indexes}{ $meta{nick} } = $marker;
700 $marker = ":$marker";
703 if ( $meta{type} eq 'tweet' ) {
704 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
705 } elsif ( $meta{type} eq 'reply' ) {
706 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
707 } elsif ( $meta{type} eq 'dm' ) {
708 push @lines, "[$account%B\@$meta{nick}%n (%%WDM%%n)] $_\n",;
709 } elsif ( $meta{type} eq 'debug' ) {
710 push @lines, "debug: $_\n" if &debug,;
720 my ( $f, $t ) = split ' ', $_;
721 $nicks{$f} = $friends{$f} = $t;
724 if ( $last_poll != $old_last_poll ) {
725 print "new last_poll = $last_poll" if &debug;
726 foreach my $line (@lines) {
728 $window->print( $line, MSGLEVEL_PUBLIC );
729 foreach ( $line =~ /\@([-\w]+)/ ) {
736 or warn "Failed to remove $filename: $!"
739 # keep 10 minutes of cached tweets, to make sure we don't show duplicates.
740 foreach ( keys %tweet_cache ) {
741 next if $tweet_cache{$_} > time - 600;
742 delete $tweet_cache{$_};
749 Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
753 return Irssi::settings_get_bool("twirssi_debug");
757 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
761 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
764 $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
765 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
766 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
768 { # /twitter_reply gets a nick:num
769 @$complist = grep { $_ ne "__indexes" } grep /^\Q$word/i,
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." );