10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
14 $VERSION = "2.2.5beta";
15 my ($REV) = '$Rev: 675 $' =~ /(\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://twirssi.com',
24 changed => '$Date: 2009-07-22 10:06:58 -0700 (Wed, 22 Jul 2009) $',
34 my $last_friends_poll = 0;
42 my %irssi_to_mirc_colors = (
62 my ( $data, $server, $win ) = @_;
64 return unless &logged_in($twit);
66 my ( $target, $text ) = split ' ', $data, 2;
67 unless ( $target and $text ) {
68 ¬ice("Usage: /dm <nick> <message>");
72 &cmd_direct_as( "$user $data", $server, $win );
76 my ( $data, $server, $win ) = @_;
78 return unless &logged_in($twit);
80 my ( $username, $target, $text ) = split ' ', $data, 3;
81 unless ( $username and $target and $text ) {
82 ¬ice("Usage: /dm_as <username> <nick> <message>");
86 return unless $username = &valid_username($username);
89 if ( $twits{$username}
90 ->new_direct_message( { user => $target, text => $text } ) )
92 ¬ice("DM sent to $target");
93 $nicks{$target} = time;
97 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
98 $error = $error->{error};
100 die $error if $error;
101 ¬ice("DM to $target failed");
106 ¬ice("DM caused an error: $@");
112 my ( $data, $server, $win ) = @_;
114 return unless &logged_in($twit);
116 $data =~ s/^\s+|\s+$//;
118 ¬ice("Usage: /retweet <nick[:num]> [comment]");
122 my ( $id, $data ) = split ' ', $data, 2;
124 &cmd_retweet_as( "$user $id $data", $server, $win );
128 my ( $data, $server, $win ) = @_;
130 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
131 ¬ice("twirssi_track_replies is required in order to reteet.");
135 return unless &logged_in($twit);
137 $data =~ s/^\s+|\s+$//;
138 my ( $username, $id, $data ) = split ' ', $data, 3;
141 ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
145 return unless $username = &valid_username($username);
148 $id =~ s/[^\w\d\-:]+//g;
149 ( $nick, $id ) = split /:/, $id;
150 unless ( exists $id_map{ lc $nick } ) {
151 ¬ice("Can't find a tweet from $nick to retweet!");
155 $id = $id_map{__indexes}{$nick} unless $id;
156 unless ( $id_map{ lc $nick }[$id] ) {
157 ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
161 unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
162 ¬ice("The text of this tweet isn't saved, sorry!");
166 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
167 my $text = Irssi::settings_get_str("twirssi_retweet_format");
168 $text =~ s/\$n/\@$nick/g;
170 $text =~ s/\${|\$}//g;
171 $text =~ s/\$c/$data/;
173 $text =~ s/\${.*?\$}//;
175 $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
177 $data = &shorten($text);
179 return if &too_long($data);
184 $twits{$username}->update(
187 # in_reply_to_status_id => $id_map{ lc $nick }[$id]
192 ¬ice("Update failed");
196 return unless $success;
199 ¬ice("Update caused an error: $@. Aborted");
203 foreach ( $data =~ /@([-\w]+)/ ) {
207 ¬ice("Retweet sent");
211 my ( $data, $server, $win ) = @_;
213 return unless &logged_in($twit);
215 $data =~ s/^\s+|\s+$//;
217 ¬ice("Usage: /tweet <update>");
221 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
225 my ( $data, $server, $win ) = @_;
227 return unless &logged_in($twit);
229 $data =~ s/^\s+|\s+$//;
230 $data =~ s/\s\s+/ /g;
231 my ( $username, $data ) = split ' ', $data, 2;
233 unless ( $username and $data ) {
234 ¬ice("Usage: /tweet_as <username> <update>");
238 return unless $username = &valid_username($username);
240 $data = &shorten($data);
242 return if &too_long($data);
246 unless ( $twits{$username}->update($data) )
248 ¬ice("Update failed");
252 return unless $success;
255 ¬ice("Update caused an error: $@. Aborted.");
259 foreach ( $data =~ /@([-\w]+)/ ) {
263 my $away = &update_away($data);
265 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
269 my ( $data, $server, $win ) = @_;
271 return unless &logged_in($twit);
273 $data =~ s/^\s+|\s+$//;
275 ¬ice("Usage: /reply <nick[:num]> <update>");
279 my ( $id, $data ) = split ' ', $data, 2;
280 unless ( $id and $data ) {
281 ¬ice("Usage: /reply <nick[:num]> <update>");
285 &cmd_reply_as( "$user $id $data", $server, $win );
289 my ( $data, $server, $win ) = @_;
291 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
292 ¬ice("twirssi_track_replies is required in order to reply to "
293 . "specific tweets. Either enable it, or just use /tweet "
294 . "\@username <text>." );
298 return unless &logged_in($twit);
300 $data =~ s/^\s+|\s+$//;
301 my ( $username, $id, $data ) = split ' ', $data, 3;
303 unless ( $username and $data ) {
304 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
308 return unless $username = &valid_username($username);
311 $id =~ s/[^\w\d\-:]+//g;
312 ( $nick, $id ) = split /:/, $id;
313 unless ( exists $id_map{ lc $nick } ) {
314 ¬ice("Can't find a tweet from $nick to reply to!");
318 $id = $id_map{__indexes}{$nick} unless $id;
319 unless ( $id_map{ lc $nick }[$id] ) {
320 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
324 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
326 # remove any @nick at the beginning of the reply, as we'll add it anyway
327 $data =~ s/^\s*\@?$nick\s*//;
328 $data = "\@$nick " . $data;
331 $data = &shorten($data);
333 return if &too_long($data);
338 $twits{$username}->update(
341 in_reply_to_status_id => $id_map{ lc $nick }[$id]
346 ¬ice("Update failed");
350 return unless $success;
353 ¬ice("Update caused an error: $@. Aborted");
357 foreach ( $data =~ /@([-\w]+)/ ) {
361 my $away = &update_away($data);
363 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
367 my ( $usage_str, $api_name, $post_ref ) = @_;
370 my ( $data, $server, $win ) = @_;
372 return unless &logged_in($twit);
374 $data =~ s/^\s+|\s+$//;
376 ¬ice("Usage: $usage_str");
382 unless ( $twit->$api_name($data) )
384 ¬ice("$api_name failed");
388 return unless $success;
391 ¬ice("$api_name caused an error. Aborted.");
395 &$post_ref($data) if $post_ref;
400 my ( $data, $server, $win ) = @_;
402 $data =~ s/^\s+|\s+$//g;
403 $data = &normalize_username($data);
404 if ( exists $twits{$data} ) {
405 ¬ice("Switching to $data");
406 $twit = $twits{$data};
407 if ( $data =~ /(.*)\@(.*)/ ) {
411 ¬ice("Couldn't figure out what service '$data' is on");
414 ¬ice("Unknown user $data");
419 my ( $data, $server, $win ) = @_;
421 $data =~ s/^\s+|\s+$//g;
422 $data = $user unless $data;
423 return unless $data = &valid_username($data);
425 ¬ice("Logging out $data...");
426 $twits{$data}->end_session();
427 delete $twits{$data};
430 &cmd_switch( ( keys %twits )[0], $server, $win );
432 Irssi::timeout_remove($poll) if $poll;
438 my ( $data, $server, $win ) = @_;
441 ( $user, $pass ) = split ' ', $data, 2;
442 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
443 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
445 my @user = split /\s*,\s*/, $autouser;
446 my @pass = split /\s*,\s*/, $autopass;
448 # if a password ends with a '\', it was meant to escape the comma, and
449 # it should be concatinated with the next one
453 while ( $p =~ /\\$/ and @pass ) {
454 $p .= "," . shift @pass;
459 if ( @user != @unescaped ) {
460 ¬ice("Number of usernames doesn't match "
461 . "the number of passwords - auto-login failed" );
464 while ( @user and @unescaped ) {
466 $p = shift @unescaped;
472 ¬ice("/twitter_login requires either a username and password "
473 . "or twitter_usernames and twitter_passwords to be set." );
477 %friends = %nicks = ();
480 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
481 ( $user, $service ) = ( $1, $2 );
483 $service = Irssi::settings_get_str("twirssi_default_service");
485 $defservice = $service = ucfirst lc $service;
487 eval "use Net::$service";
490 "Failed to load Net::$service when trying to log in as $user: $@");
494 $twit = "Net::$service"->new(
500 unless ( $twit->verify_credentials() ) {
501 ¬ice("Login as $user\@$service failed");
504 &cmd_switch( ( keys %twits )[0], $server, $win );
510 my $rate_limit = $twit->rate_limit_status();
511 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
513 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
519 $twits{"$user\@$service"} = $twit;
520 Irssi::timeout_remove($poll) if $poll;
521 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
522 ¬ice("Logged in as $user\@$service, loading friends list...");
524 ¬ice( "loaded friends: ", scalar keys %friends );
525 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
526 Irssi::settings_set_bool( "twirssi_first_run", 0 );
527 unless ( exists $friends{twirssi} ) {
528 ¬ice("Welcome to twirssi!"
529 . " Perhaps you should add \@twirssi to your friends list,"
530 . " so you can be notified when a new version is release?"
531 . " Just type /twitter_follow twirssi." );
538 ¬ice("Login failed");
543 my ( $data, $server, $win ) = @_;
545 unless ( $twit and $twit->can('search') ) {
546 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
547 . "doesn't support searches." );
551 $data =~ s/^\s+|\s+$//;
555 ¬ice("Usage: /twitter_subscribe <topic>");
559 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
560 ¬ice("Already had a subscription for '$data'");
564 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
565 ¬ice("Added subscription for '$data'");
569 my ( $data, $server, $win ) = @_;
571 unless ( $twit and $twit->can('search') ) {
572 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
573 . "doesn't support searches." );
576 $data =~ s/^\s+|\s+$//;
580 ¬ice("Usage: /twitter_unsubscribe <topic>");
584 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
585 ¬ice("No subscription found for '$data'");
589 delete $id_map{__searches}{"$user\@$defservice"}{$data};
590 ¬ice("Removed subscription for '$data'");
593 sub cmd_list_search {
594 my ( $data, $server, $win ) = @_;
597 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
599 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
600 $topics = $topics ? "$topics, $topic" : $topic;
604 ¬ice("Search subscriptions for \@$suser: $topics");
609 ¬ice("No search subscriptions set up");
614 my ( $data, $server, $win ) = @_;
616 my $loc = Irssi::settings_get_str("twirssi_location");
619 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
625 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
626 eval { use Digest::MD5; };
630 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
635 $md5 = get("http://twirssi.com/md5sum");
639 ¬ice("Failed to download md5sum from peeron! Aborting.");
643 unless ( open( CUR, $loc ) ) {
645 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
650 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
653 if ( $cur_md5 eq $md5 ) {
654 ¬ice("Current twirssi seems to be up to date.");
660 Irssi::settings_get_bool("twirssi_upgrade_beta")
661 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
662 : "http://twirssi.com/twirssi.pl";
663 ¬ice("Downloading twirssi from $URL");
664 LWP::Simple::getstore( $URL, "$loc.upgrade" );
666 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
667 unless ( open( NEW, "$loc.upgrade" ) ) {
669 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
674 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
677 if ( $new_md5 ne $md5 ) {
678 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
683 rename $loc, "$loc.backup"
684 or ¬ice("Failed to back up $loc: $!. Aborting")
686 rename "$loc.upgrade", $loc
687 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
690 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
691 if ( -e "$dir/autorun/$file" ) {
692 ¬ice("Updating $dir/autorun/$file");
693 unlink "$dir/autorun/$file"
694 or ¬ice("Failed to remove old $file from autorun: $!");
695 symlink "../$file", "$dir/autorun/$file"
696 or ¬ice("Failed to create symlink in autorun directory: $!");
699 ¬ice("Download complete. Reload twirssi with /script load $file");
709 print $fh "type:debug Loading friends page $page...\n"
710 if ( $fh and &debug );
711 my $friends = $twit->friends( { page => $page } );
712 last unless $friends;
713 $new_friends{ $_->{screen_name} } = time foreach @$friends;
715 last if @$friends == 0 or $page == 10;
720 print $fh "type:debug Error during friends list update. Aborted.\n";
724 my ( $added, $removed ) = ( 0, 0 );
725 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
726 foreach ( keys %new_friends ) {
727 next if exists $friends{$_};
732 print $fh "type:debug Scanning for removed friends...\n"
733 if ( $fh and &debug );
734 foreach ( keys %friends ) {
735 next if exists $new_friends{$_};
740 return ( $added, $removed );
744 print scalar localtime, " - get_updates starting" if &debug;
747 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
750 ->print( "Can't find a window named '"
751 . Irssi::settings_get_str('twitter_window')
752 . "'. Create it or change the value of twitter_window" );
755 return unless &logged_in($twit);
757 my ( $fh, $filename ) = File::Temp::tempfile();
758 binmode( $fh, ":utf8" );
762 Irssi::timeout_add_once( 5000, 'monitor_child', [ "$filename.done", 0 ] );
763 Irssi::pidwait_add($pid);
764 } elsif ( defined $pid ) { # child
773 foreach ( keys %twits ) {
774 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
777 print $fh "__friends__\n";
779 time - $last_friends_poll >
780 Irssi::settings_get_int('twitter_friends_poll') )
782 print $fh "__updated ", time, "\n";
783 my ( $added, $removed ) = &load_friends($fh);
784 if ( $added + $removed ) {
785 print $fh "type:debug %R***%n Friends list updated: ",
787 sprintf( "%d added", $added ),
788 sprintf( "%d removed", $removed ) ),
793 foreach ( sort keys %friends ) {
794 print $fh "$_ $friends{$_}\n";
798 print $fh "type:debug Update encountered errors. Aborted\n";
799 print $fh "-- $last_poll";
801 print $fh "-- $new_poll";
804 rename $filename, "$filename.done";
807 &ccrap("Failed to fork for updating: $!");
809 print scalar localtime, " - get_updates ends" if &debug;
813 my ( $fh, $username, $obj, $cache ) = @_;
815 my $rate_limit = $obj->rate_limit_status();
816 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
817 ¬ice("Rate limit exceeded for $username");
821 print scalar localtime, " - Polling for updates for $username" if &debug;
825 if ( $id_map{__last_id}{$username}{timeline} )
827 $tweets = $obj->friends_timeline( { count => 100 } );
829 $tweets = $obj->friends_timeline();
834 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
835 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
839 unless ( ref $tweets ) {
840 if ( $obj->can("get_error") ) {
841 my $error = "Unknown error";
842 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
843 unless ($@) { $error = $obj->get_error() }
845 "type:debug API Error during friends_timeline call: Aborted\n";
846 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
850 "type:debug API Error during friends_timeline call. Aborted.\n";
855 foreach my $t ( reverse @$tweets ) {
856 my $text = decode_entities( $t->{text} );
857 $text =~ s/[\n\r]/ /g;
859 if ( Irssi::settings_get_bool("show_reply_context")
860 and $t->{in_reply_to_screen_name} ne $username
861 and $t->{in_reply_to_screen_name}
862 and not exists $friends{ $t->{in_reply_to_screen_name} } )
864 $nicks{ $t->{in_reply_to_screen_name} } = time;
866 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
868 $cache->{ $t->{in_reply_to_status_id} } =
869 $obj->show_status( $t->{in_reply_to_status_id} );
873 $context = $cache->{ $t->{in_reply_to_status_id} };
876 my $ctext = decode_entities( $context->{text} );
877 $ctext =~ s/[\n\r]/ /g;
878 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
880 " -- http://twitter.com/$context->{user}{screen_name}"
881 . "/status/$context->{id}";
883 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
884 $context->{id}, $username,
885 $context->{user}{screen_name}, $ctext;
890 if $t->{user}{screen_name} eq $username
891 and not Irssi::settings_get_bool("show_own_tweets");
892 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
893 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
894 . "/status/$t->{id}";
896 printf $fh "id:%u account:%s nick:%s type:%s %s\n",
897 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
898 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
900 printf $fh "id:%u account:%s type:last_id timeline\n",
901 $new_poll_id, $username;
903 print scalar localtime, " - Polling for replies" if &debug;
906 if ( $id_map{__last_id}{$username}{reply} )
908 $tweets = $obj->replies(
909 { since_id => $id_map{__last_id}{$username}{reply} } )
912 $tweets = $obj->replies() || [];
917 print $fh "type:debug Error during replies call. Aborted.\n";
921 foreach my $t ( reverse @$tweets ) {
923 if exists $friends{ $t->{user}{screen_name} };
925 my $text = decode_entities( $t->{text} );
926 $text =~ s/[\n\r]/ /g;
927 if ( $t->{truncated} ) {
928 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
929 . "/status/$t->{id}";
931 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
932 $t->{id}, $username, $t->{user}{screen_name}, $text;
933 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
935 printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
937 print scalar localtime, " - Polling for DMs" if &debug;
940 if ( $id_map{__last_id}{$username}{dm} )
942 $tweets = $obj->direct_messages(
943 { since_id => $id_map{__last_id}{$username}{dm} } )
946 $tweets = $obj->direct_messages() || [];
951 print $fh "type:debug Error during direct_messages call. Aborted.\n";
955 foreach my $t ( reverse @$tweets ) {
956 my $text = decode_entities( $t->{text} );
957 $text =~ s/[\n\r]/ /g;
958 printf $fh "id:%u account:%s nick:%s type:dm %s\n",
959 $t->{id}, $username, $t->{sender_screen_name}, $text;
960 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
962 printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
964 print scalar localtime, " - Polling for subscriptions" if &debug;
965 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
967 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
968 print $fh "type:debug searching for $topic since ",
969 "$id_map{__searches}{$username}{$topic}\n";
971 $search = $obj->search(
974 since_id => $id_map{__searches}{$username}{$topic}
981 "type:debug Error during search($topic) call. Aborted.\n";
985 unless ( $search->{max_id} ) {
986 print $fh "type:debug Invalid search results when searching",
987 " for $topic. Aborted.\n";
991 $id_map{__searches}{$username}{$topic} = $search->{max_id};
992 printf $fh "id:%u account:%s type:searchid topic:%s\n",
993 $search->{max_id}, $username, $topic;
995 foreach my $t ( reverse @{ $search->{results} } ) {
996 my $text = decode_entities( $t->{text} );
997 $text =~ s/[\n\r]/ /g;
998 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
999 $t->{id}, $username, $t->{from_user}, $topic, $text;
1000 $new_poll_id = $t->{id}
1002 or $t->{id} < $new_poll_id;
1007 print scalar localtime, " - Done" if &debug;
1014 my $filename = $data->[0];
1015 my $attempt = $data->[1];
1017 print scalar localtime, " - checking child log at $filename ($attempt)"
1019 my ($new_last_poll);
1021 # first time we run we don't want to print out *everything*, so we just
1024 if ( open FILE, $filename ) {
1028 last if /^__friends__/;
1029 unless (/\n$/) { # skip partial lines
1030 # print "Skipping partial line: $_" if &debug;
1037 foreach my $key (qw/id account nick type topic/) {
1038 if (s/^$key:(\S+)\s*//) {
1043 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1044 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1048 $new_cache{ $meta{id} } = time;
1050 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1056 $meta{account} =~ s/\@(\w+)$//;
1057 $meta{service} = $1;
1059 lc $meta{service} eq
1060 lc Irssi::settings_get_str("twirssi_default_service") )
1062 $account = "$meta{account}: "
1063 if lc "$meta{account}\@$meta{service}" ne lc
1064 "$user\@$defservice";
1066 $account = "$meta{account}\@$meta{service}: ";
1070 if ( $meta{type} ne 'dm'
1071 and Irssi::settings_get_bool("twirssi_track_replies")
1075 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1076 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1077 $id_map{__indexes}{ $meta{nick} } = $marker;
1078 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1079 $marker = ":$marker";
1083 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1084 my $nick = "\@$meta{account}";
1085 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1086 and Irssi::settings_get_bool("twirssi_hilights") )
1088 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1089 $hilight = MSGLEVEL_HILIGHT;
1092 if ( $meta{type} =~ /tweet|reply/ ) {
1095 ( MSGLEVEL_PUBLIC | $hilight ),
1096 $meta{type}, $account, $meta{nick}, $marker, $_
1098 } elsif ( $meta{type} eq 'search' ) {
1101 ( MSGLEVEL_PUBLIC | $hilight ),
1102 $meta{type}, $account, $meta{topic},
1103 $meta{nick}, $marker, $_
1106 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1108 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1110 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1113 } elsif ( $meta{type} eq 'dm' ) {
1116 ( MSGLEVEL_MSGS | $hilight ),
1117 $meta{type}, $account, $meta{nick}, $_
1119 } elsif ( $meta{type} eq 'searchid' ) {
1120 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1123 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1125 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1127 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1130 print "Search '$meta{topic}' returned invalid id $meta{id}";
1132 } elsif ( $meta{type} eq 'last_id' ) {
1133 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1135 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1137 } elsif ( $meta{type} eq 'error' ) {
1138 push @lines, [ MSGLEVEL_MSGS, $_ ];
1139 } elsif ( $meta{type} eq 'debug' ) {
1140 print "$_" if &debug,;
1142 print "Unknown line type $meta{type}: $_" if &debug,;
1148 if (/^__updated (\d+)$/) {
1149 $last_friends_poll = $1;
1150 print "Friend list updated" if &debug;
1155 ($new_last_poll) = ($1);
1158 my ( $f, $t ) = split ' ', $_;
1159 $nicks{$f} = $friends{$f} = $t;
1162 if ($new_last_poll) {
1163 print "new last_poll = $new_last_poll" if &debug;
1164 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1166 print "First call, not printing updates" if &debug;
1168 foreach my $line (@lines) {
1169 $window->printformat(
1171 "twirssi_" . $line->[1],
1172 @$line[ 2 .. $#$line-1 ],
1173 &hilight($line->[-1])
1180 or warn "Failed to remove $filename: $!"
1183 # commit the pending cache lines to the actual cache, now that
1184 # we've printed our output
1185 %tweet_cache = ( %tweet_cache, %new_cache );
1187 # keep enough cached tweets, to make sure we don't show duplicates.
1188 foreach ( keys %tweet_cache ) {
1189 next if $tweet_cache{$_} >= $last_poll - 3600;
1190 delete $tweet_cache{$_};
1192 $last_poll = $new_last_poll;
1197 Irssi::settings_get_str("twirssi_replies_store") )
1199 if ( open JSON, ">$file" ) {
1200 print JSON JSON::Any->objToJson( \%id_map );
1203 &ccrap("Failed to write replies to $file: $!");
1214 if ( $attempt < 24 ) {
1215 Irssi::timeout_add_once( 5000, 'monitor_child',
1216 [ $filename, $attempt + 1 ] );
1218 print "Giving up on polling $filename" if &debug;
1219 unlink $filename unless &debug;
1221 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1224 my @time = localtime($last_poll);
1225 if ( time - $last_poll < 24 * 60 * 60 ) {
1226 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1228 $since = scalar localtime($last_poll);
1231 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1236 q{ .--./ / | _.---.| },
1248 if ( time - $last_poll < 600 ) {
1249 &ccrap("Haven't been able to get updated tweets since $since");
1255 return Irssi::settings_get_bool("twirssi_debug");
1259 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1263 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1269 if ( Irssi::settings_get_bool("tweet_to_away")
1271 and $data !~ /^[dD] / )
1274 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1276 $server->send_raw("away :$data");
1279 &ccrap( "Can't find bitlbee server.",
1280 "Update bitlbee_server or disable tweet_to_away" );
1290 my $noalert = shift;
1292 if ( length $data > 140 ) {
1293 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1301 sub valid_username {
1302 my $username = shift;
1304 $username = &normalize_username($username);
1306 unless ( exists $twits{$username} ) {
1307 ¬ice("Unknown username $username");
1317 ¬ice("Not logged in! Use /twitter_login username pass!");
1325 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1328 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1329 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1330 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1332 { # /twitter_reply gets a nick:num
1334 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1335 sort { $nicks{$b} <=> $nicks{$a} }
1337 keys %{ $id_map{__indexes} };
1340 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1341 { # /twitter_unfriend gets a nick
1343 push @$complist, grep /^\Q$word/i,
1344 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1347 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1349 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1350 my $prefix = $word =~ s/^@//;
1351 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1352 push @$complist, grep /^\Q$word/i,
1353 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1354 @$complist = map { "\@$_" } @$complist if $prefix;
1358 sub event_send_text {
1359 my ( $line, $server, $win ) = @_;
1360 my $awin = Irssi::active_win();
1362 # if the window where we got our text was the twitter window, and the user
1363 # wants to be lazy, tweet away!
1364 if ( ( $awin->get_active_name() eq $window->{name} )
1365 and Irssi::settings_get_bool("tweet_window_input") )
1367 &cmd_tweet( $line, $server, $win );
1372 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1373 return $poll if $poll >= 60;
1380 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1381 my $c = Irssi::settings_get_str("twirssi_nick_color");
1382 $c = $irssi_to_mirc_colors{$c};
1383 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1385 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1386 my $c = Irssi::settings_get_str("twirssi_topic_color");
1387 $c = $irssi_to_mirc_colors{$c};
1388 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1390 $text =~ s/[\n\r]/ /g;
1398 my $provider = Irssi::settings_get_str("short_url_provider");
1401 Irssi::settings_get_bool("twirssi_always_shorten")
1402 or &too_long( $data, 1 )
1408 if ( $provider eq 'Bitly' ) {
1409 @args[ 1, 2 ] = split ',',
1410 Irssi::settings_get_str("short_url_args"), 2;
1411 unless ( @args == 3 ) {
1413 "WWW::Shorten::Bitly requires a username and API key.",
1414 "Set short_url_args to username,API_key or change your",
1415 "short_url_provider."
1421 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1424 my $short = makeashorterlink(@args);
1426 $data =~ s/\Q$url/$short/g;
1428 ¬ice("Failed to shorten $url!");
1434 return decode "utf8", $data;
1437 sub normalize_username {
1440 my ( $username, $service ) = split /\@/, $user, 2;
1442 $service = ucfirst lc $service;
1445 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1446 unless ( exists $twits{"$username\@$service"} ) {
1448 foreach my $t ( sort keys %twits ) {
1449 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1455 ¬ice("Can't find a logged in user '$user'");
1460 return "$username\@$service";
1463 Irssi::signal_add( "send text", "event_send_text" );
1465 Irssi::theme_register(
1467 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1468 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1469 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1470 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1471 'twirssi_error', 'ERROR: $0',
1475 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1476 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1477 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1478 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1479 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1480 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1481 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1482 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1483 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1484 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1485 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1486 'RT $n: "$t" ${-- $c$}' );
1487 Irssi::settings_add_str( "twirssi", "twirssi_location",
1488 ".irssi/scripts/twirssi.pl" );
1489 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1490 ".irssi/scripts/twirssi.json" );
1492 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1494 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1495 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1496 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1497 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1498 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1499 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1500 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1501 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1502 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1503 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1504 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1505 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1506 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1508 $last_poll = time - &get_poll_time;
1509 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1512 ->print( "Couldn't find a window named '"
1513 . Irssi::settings_get_str('twitter_window')
1514 . "', trying to create it." );
1516 Irssi::Windowitem::window_create(
1517 Irssi::settings_get_str('twitter_window'), 1 );
1518 $window->set_name( Irssi::settings_get_str('twitter_window') );
1522 Irssi::command_bind( "dm", "cmd_direct" );
1523 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1524 Irssi::command_bind( "tweet", "cmd_tweet" );
1525 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1526 Irssi::command_bind( "retweet", "cmd_retweet" );
1527 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1528 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1529 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1530 Irssi::command_bind( "twitter_login", "cmd_login" );
1531 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1532 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1533 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1534 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1535 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1536 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1537 Irssi::command_bind( "twitter_updates", "get_updates" );
1538 Irssi::command_bind( "bitlbee_away", "update_away" );
1539 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1540 Irssi::command_bind( "reply", "cmd_reply" );
1541 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1543 Irssi::command_bind(
1546 print "twits: ", join ", ",
1547 map { "u: $_->{username}\@" . ref($_) } values %twits;
1548 print "selected: $user\@$defservice";
1549 print "friends: ", join ", ", sort keys %friends;
1550 print "nicks: ", join ", ", sort keys %nicks;
1551 print "searches: ", Dumper \%{ $id_map{__searches} };
1552 print "last poll: $last_poll";
1553 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1554 print DUMP Dumper \%tweet_cache;
1556 print "cache written out to /tmp/twirssi.cache.txt";
1560 Irssi::command_bind(
1563 ¬ice("Twirssi v$VERSION (r$REV); "
1564 . "Net::Twitter v$Net::Twitter::VERSION. "
1566 . JSON::Any::handler()
1567 . ". See details at http://twirssi.com/" );
1570 Irssi::command_bind(
1573 "/twitter_follow <username>",
1575 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1578 Irssi::command_bind(
1581 "/twitter_unfriend <username>",
1583 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1586 Irssi::command_bind(
1587 "twitter_device_updates",
1589 "/twitter_device_updates none|im|sms",
1590 "update_delivery_device",
1591 sub { ¬ice("Device updated to $_[0]"); }
1594 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1596 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1597 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1599 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1601 my $file = Irssi::settings_get_str("twirssi_replies_store");
1602 if ( $file and -r $file ) {
1603 if ( open( JSON, $file ) ) {
1608 my $ref = JSON::Any->jsonToObj($json);
1610 my $num = keys %{ $id_map{__indexes} };
1611 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1612 $num, ( $num == 1 ? "" : "s" ) );
1616 ¬ice("Failed to load old replies from $file: $!");
1620 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1621 ¬ice("Loading WWW::Shorten::$provider...");
1622 eval "use WWW::Shorten::$provider;";
1626 "Failed to load WWW::Shorten::$provider - either clear",
1627 "short_url_provider or install the CPAN module"
1632 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1633 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1641 ->print( "Create a window named "
1642 . Irssi::settings_get_str('twitter_window')
1643 . " or change the value of twitter_window. Then, reload twirssi." );
1646 # vim: set sts=4 expandtab: