9 $Data::Dumper::Indent = 1;
11 use vars qw($VERSION %IRSSI);
13 $VERSION = "2.2.3beta";
14 my ($REV) = '$Rev: 616 $' =~ /(\d+)/;
16 authors => 'Dan Boger',
17 contact => 'zigdon@gmail.com',
19 description => 'Send twitter updates using /tweet. '
20 . 'Can optionally set your bitlbee /away message to same',
21 license => 'GNU GPL v2',
22 url => 'http://twirssi.com',
23 changed => '$Date: 2009-04-21 12:20:40 -0700 (Tue, 21 Apr 2009) $',
33 my $last_friends_poll = time;
39 my %irssi_to_mirc_colors = (
59 my ( $data, $server, $win ) = @_;
61 return unless &logged_in($twit);
63 my ( $target, $text ) = split ' ', $data, 2;
64 unless ( $target and $text ) {
65 ¬ice("Usage: /dm <nick> <message>");
69 &cmd_direct_as( "$user $data", $server, $win );
73 my ( $data, $server, $win ) = @_;
75 return unless &logged_in($twit);
77 my ( $username, $target, $text ) = split ' ', $data, 3;
78 unless ( $username and $target and $text ) {
79 ¬ice("Usage: /dm_as <username> <nick> <message>");
83 return unless $username = &valid_username($username);
86 if ( $twits{$username}
87 ->new_direct_message( { user => $target, text => $text } ) )
89 ¬ice("DM sent to $target");
90 $nicks{$target} = time;
94 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
95 $error = $error->{error};
98 ¬ice("DM to $target failed");
103 ¬ice("DM caused an error: $@");
109 my ( $data, $server, $win ) = @_;
111 return unless &logged_in($twit);
113 $data =~ s/^\s+|\s+$//;
115 ¬ice("Usage: /retweet <nick[:num]> [comment]");
119 my ( $id, $data ) = split ' ', $data, 2;
121 &cmd_retweet_as( "$user $id $data", $server, $win );
125 my ( $data, $server, $win ) = @_;
127 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
128 ¬ice("twirssi_track_replies is required in order to reteet.");
132 return unless &logged_in($twit);
134 $data =~ s/^\s+|\s+$//;
135 my ( $username, $id, $data ) = split ' ', $data, 3;
138 ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
142 return unless $username = &valid_username($username);
145 $id =~ s/[^\w\d\-:]+//g;
146 ( $nick, $id ) = split /:/, $id;
147 unless ( exists $id_map{ lc $nick } ) {
148 ¬ice("Can't find a tweet from $nick to retweet!");
152 $id = $id_map{__indexes}{$nick} unless $id;
153 unless ( $id_map{ lc $nick }[$id] ) {
154 ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
158 unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
159 ¬ice("The text of this tweet isn't saved, sorry!");
163 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
164 my $text = Irssi::settings_get_str("twirssi_retweet_format");
165 $text =~ s/\$n/\@$nick/g;
167 $text =~ s/\${|\$}//g;
168 $text =~ s/\$c/$data/;
170 $text =~ s/\${.*?\$}//;
172 $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
174 $data = &shorten($text);
176 return if &too_long($data);
181 $twits{$username}->update(
184 in_reply_to_status_id => $id_map{ lc $nick }[$id]
189 ¬ice("Update failed");
193 return unless $success;
196 ¬ice("Update caused an error: $@. Aborted");
200 foreach ( $data =~ /@([-\w]+)/ ) {
204 ¬ice("Retweet sent");
208 my ( $data, $server, $win ) = @_;
210 return unless &logged_in($twit);
212 $data =~ s/^\s+|\s+$//;
214 ¬ice("Usage: /tweet <update>");
218 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
222 my ( $data, $server, $win ) = @_;
224 return unless &logged_in($twit);
226 $data =~ s/^\s+|\s+$//;
227 $data =~ s/\s\s+/ /g;
228 my ( $username, $data ) = split ' ', $data, 2;
230 unless ( $username and $data ) {
231 ¬ice("Usage: /tweet_as <username> <update>");
235 return unless $username = &valid_username($username);
237 $data = &shorten($data);
239 return if &too_long($data);
243 unless ( $twits{$username}->update($data) )
245 ¬ice("Update failed");
249 return unless $success;
252 ¬ice("Update caused an error: $@. Aborted.");
256 foreach ( $data =~ /@([-\w]+)/ ) {
260 my $away = &update_away($data);
262 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
266 my ( $data, $server, $win ) = @_;
268 return unless &logged_in($twit);
270 $data =~ s/^\s+|\s+$//;
272 ¬ice("Usage: /reply <nick[:num]> <update>");
276 my ( $id, $data ) = split ' ', $data, 2;
277 unless ( $id and $data ) {
278 ¬ice("Usage: /reply <nick[:num]> <update>");
282 &cmd_reply_as( "$user $id $data", $server, $win );
286 my ( $data, $server, $win ) = @_;
288 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
289 ¬ice("twirssi_track_replies is required in order to reply to "
290 . "specific tweets. Either enable it, or just use /tweet "
291 . "\@username <text>." );
295 return unless &logged_in($twit);
297 $data =~ s/^\s+|\s+$//;
298 my ( $username, $id, $data ) = split ' ', $data, 3;
300 unless ( $username and $data ) {
301 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
305 return unless $username = &valid_username($username);
308 $id =~ s/[^\w\d\-:]+//g;
309 ( $nick, $id ) = split /:/, $id;
310 unless ( exists $id_map{ lc $nick } ) {
311 ¬ice("Can't find a tweet from $nick to reply to!");
315 $id = $id_map{__indexes}{$nick} unless $id;
316 unless ( $id_map{ lc $nick }[$id] ) {
317 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
321 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
323 # remove any @nick at the beginning of the reply, as we'll add it anyway
324 $data =~ s/^\s*\@?$nick\s*//;
325 $data = "\@$nick " . $data;
328 $data = &shorten($data);
330 return if &too_long($data);
335 $twits{$username}->update(
338 in_reply_to_status_id => $id_map{ lc $nick }[$id]
343 ¬ice("Update failed");
347 return unless $success;
350 ¬ice("Update caused an error: $@. Aborted");
354 foreach ( $data =~ /@([-\w]+)/ ) {
358 my $away = &update_away($data);
360 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
364 my ( $usage_str, $api_name, $post_ref ) = @_;
367 my ( $data, $server, $win ) = @_;
369 return unless &logged_in($twit);
371 $data =~ s/^\s+|\s+$//;
373 ¬ice("Usage: $usage_str");
379 unless ( $twit->$api_name($data) )
381 ¬ice("$api_name failed");
385 return unless $success;
388 ¬ice("$api_name caused an error. Aborted.");
392 &$post_ref($data) if $post_ref;
397 my ( $data, $server, $win ) = @_;
399 $data =~ s/^\s+|\s+$//g;
400 $data = &normalize_username($data);
401 if ( exists $twits{$data} ) {
402 ¬ice("Switching to $data");
403 $twit = $twits{$data};
404 if ( $data =~ /(.*)\@(.*)/ ) {
408 ¬ice("Couldn't figure out what service '$data' is on");
411 ¬ice("Unknown user $data");
416 my ( $data, $server, $win ) = @_;
418 $data =~ s/^\s+|\s+$//g;
419 $data = $user unless $data;
420 return unless $data = &valid_username($data);
422 ¬ice("Logging out $data...");
423 $twits{$data}->end_session();
424 delete $twits{$data};
427 &cmd_switch( ( keys %twits )[0], $server, $win );
429 Irssi::timeout_remove($poll) if $poll;
435 my ( $data, $server, $win ) = @_;
438 ( $user, $pass ) = split ' ', $data, 2;
439 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
440 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
442 my @user = split /\s*,\s*/, $autouser;
443 my @pass = split /\s*,\s*/, $autopass;
445 # if a password ends with a '\', it was meant to escape the comma, and
446 # it should be concatinated with the next one
450 while ( $p =~ /\\$/ and @pass ) {
451 $p .= "," . shift @pass;
456 if ( @user != @unescaped ) {
457 ¬ice("Number of usernames doesn't match "
458 . "the number of passwords - auto-login failed" );
461 while ( @user and @unescaped ) {
463 $p = shift @unescaped;
469 ¬ice("/twitter_login requires either a username and password "
470 . "or twitter_usernames and twitter_passwords to be set." );
474 %friends = %nicks = ();
477 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
478 ( $user, $service ) = ( $1, $2 );
480 $service = Irssi::settings_get_str("twirssi_default_service");
482 $defservice = $service = ucfirst lc $service;
484 eval "use Net::$service";
487 "Failed to load Net::$service when trying to log in as $user: $@");
491 $twit = "Net::$service"->new(
497 unless ( $twit->verify_credentials() ) {
498 ¬ice("Login as $user\@$service failed");
501 &cmd_switch( ( keys %twits )[0], $server, $win );
507 my $rate_limit = $twit->rate_limit_status();
508 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
510 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
516 $twits{"$user\@$service"} = $twit;
517 Irssi::timeout_remove($poll) if $poll;
518 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
519 ¬ice("Logged in as $user\@$service, loading friends list...");
521 ¬ice( "loaded friends: ", scalar keys %friends );
522 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
523 Irssi::settings_set_bool( "twirssi_first_run", 0 );
524 unless ( exists $friends{twirssi} ) {
525 ¬ice("Welcome to twirssi!"
526 . " Perhaps you should add \@twirssi to your friends list,"
527 . " so you can be notified when a new version is release?"
528 . " Just type /twitter_friend twirssi." );
535 ¬ice("Login failed");
540 my ( $data, $server, $win ) = @_;
542 unless ( $twit and $twit->can('search') ) {
543 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
544 . "doesn't support searches." );
548 $data =~ s/^\s+|\s+$//;
552 ¬ice("Usage: /twitter_subscribe <topic>");
556 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
557 ¬ice("Already had a subscription for '$data'");
561 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
562 ¬ice("Added subscription for '$data'");
566 my ( $data, $server, $win ) = @_;
568 unless ( $twit and $twit->can('search') ) {
569 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
570 . "doesn't support searches." );
573 $data =~ s/^\s+|\s+$//;
577 ¬ice("Usage: /twitter_unsubscribe <topic>");
581 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
582 ¬ice("No subscription found for '$data'");
586 delete $id_map{__searches}{"$user\@$defservice"}{$data};
587 ¬ice("Removed subscription for '$data'");
590 sub cmd_list_search {
591 my ( $data, $server, $win ) = @_;
594 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
596 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
597 $topics = $topics ? "$topics, $topic" : $topic;
601 ¬ice("Search subscriptions for \@$suser: $topics");
606 ¬ice("No search subscriptions set up");
611 my ( $data, $server, $win ) = @_;
613 my $loc = Irssi::settings_get_str("twirssi_location");
616 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
622 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
623 eval { use Digest::MD5; };
627 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
632 $md5 = get("http://twirssi.com/md5sum");
636 ¬ice("Failed to download md5sum from peeron! Aborting.");
640 unless ( open( CUR, $loc ) ) {
642 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
647 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
650 if ( $cur_md5 eq $md5 ) {
651 ¬ice("Current twirssi seems to be up to date.");
657 Irssi::settings_get_bool("twirssi_upgrade_beta")
658 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
659 : "http://twirssi.com/twirssi.pl";
660 ¬ice("Downloading twirssi from $URL");
661 LWP::Simple::getstore( $URL, "$loc.upgrade" );
663 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
664 unless ( open( NEW, "$loc.upgrade" ) ) {
666 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
671 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
674 if ( $new_md5 ne $md5 ) {
675 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
680 rename $loc, "$loc.backup"
681 or ¬ice("Failed to back up $loc: $!. Aborting")
683 rename "$loc.upgrade", $loc
684 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
687 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
688 if ( -e "$dir/autorun/$file" ) {
689 ¬ice("Updating $dir/autorun/$file");
690 unlink "$dir/autorun/$file"
691 or ¬ice("Failed to remove old $file from autorun: $!");
692 symlink "../$file", "$dir/autorun/$file"
693 or ¬ice("Failed to create symlink in autorun directory: $!");
696 ¬ice("Download complete. Reload twirssi with /script load $file");
706 print $fh "type:debug Loading friends page $page...\n"
707 if ( $fh and &debug );
708 my $friends = $twit->friends( { page => $page } );
709 last unless $friends;
710 $new_friends{ $_->{screen_name} } = time foreach @$friends;
712 last if @$friends == 0 or $page == 10;
717 print $fh "type:debug Error during friends list update. Aborted.\n";
721 my ( $added, $removed ) = ( 0, 0 );
722 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
723 foreach ( keys %new_friends ) {
724 next if exists $friends{$_};
729 print $fh "type:debug Scanning for removed friends...\n"
730 if ( $fh and &debug );
731 foreach ( keys %friends ) {
732 next if exists $new_friends{$_};
737 return ( $added, $removed );
741 print scalar localtime, " - get_updates starting" if &debug;
744 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
747 ->print( "Can't find a window named '"
748 . Irssi::settings_get_str('twitter_window')
749 . "'. Create it or change the value of twitter_window" );
752 return unless &logged_in($twit);
754 my ( $fh, $filename ) = File::Temp::tempfile();
755 binmode( $fh, ":utf8" );
759 Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
760 Irssi::pidwait_add($pid);
761 } elsif ( defined $pid ) { # child
770 foreach ( keys %twits ) {
771 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
775 time - $last_friends_poll >
776 Irssi::settings_get_int('twitter_friends_poll') )
778 my ( $added, $removed ) = &load_friends($fh);
779 if ( $added + $removed ) {
780 print $fh "type:debug %R***%n Friends list updated: ",
782 sprintf( "%d added", $added ),
783 sprintf( "%d removed", $removed ) ),
787 $last_friends_poll = time;
790 print $fh "__friends__\n";
791 foreach ( sort keys %friends ) {
792 print $fh "$_ $friends{$_}\n";
796 print $fh "type:debug Update encountered errors. Aborted\n";
797 print $fh "-- $last_poll";
799 print $fh "-- $new_poll";
804 print scalar localtime, " - get_updates ends" if &debug;
808 my ( $fh, $username, $obj, $cache ) = @_;
810 my $rate_limit = $obj->rate_limit_status();
811 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
812 ¬ice("Rate limit exceeded for $username");
816 print scalar localtime, " - Polling for updates for $username" if &debug;
820 if ( $id_map{__last_id}{$username}{timeline} )
822 $tweets = $obj->friends_timeline( { count => 100 } );
824 $tweets = $obj->friends_timeline();
829 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
830 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
834 unless ( ref $tweets ) {
835 if ( $obj->can("get_error") ) {
836 my $error = "Unknown error";
837 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
838 unless ($@) { $error = $obj->get_error() }
840 "type:debug API Error during friends_timeline call: Aborted\n";
841 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
845 "type:debug API Error during friends_timeline call. Aborted.\n";
850 foreach my $t ( reverse @$tweets ) {
851 my $text = decode_entities( $t->{text} );
852 $text = &hilight($text);
854 if ( Irssi::settings_get_bool("show_reply_context")
855 and $t->{in_reply_to_screen_name} ne $username
856 and $t->{in_reply_to_screen_name}
857 and not exists $friends{ $t->{in_reply_to_screen_name} } )
859 $nicks{ $t->{in_reply_to_screen_name} } = time;
861 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
863 $cache->{ $t->{in_reply_to_status_id} } =
864 $obj->show_status( $t->{in_reply_to_status_id} );
868 $context = $cache->{ $t->{in_reply_to_status_id} };
871 my $ctext = decode_entities( $context->{text} );
872 $ctext = &hilight($ctext);
873 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
875 " -- http://twitter.com/$context->{user}{screen_name}"
876 . "/status/$context->{id}";
878 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
879 $context->{id}, $username,
880 $context->{user}{screen_name}, $ctext;
885 if $t->{user}{screen_name} eq $username
886 and not Irssi::settings_get_bool("show_own_tweets");
887 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
888 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
889 . "/status/$t->{id}";
891 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
892 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
893 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
895 printf $fh "id:%d account:%s type:last_id timeline\n",
896 $new_poll_id, $username;
898 print scalar localtime, " - Polling for replies" if &debug;
901 if ( $id_map{__last_id}{$username}{reply} )
903 $tweets = $obj->replies(
904 { since_id => $id_map{__last_id}{$username}{reply} } )
907 $tweets = $obj->replies() || [];
912 print $fh "type:debug Error during replies call. Aborted.\n";
916 foreach my $t ( reverse @$tweets ) {
918 if exists $friends{ $t->{user}{screen_name} };
920 my $text = decode_entities( $t->{text} );
921 $text = &hilight($text);
922 if ( $t->{truncated} ) {
923 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
924 . "/status/$t->{id}";
926 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
927 $t->{id}, $username, $t->{user}{screen_name}, $text;
928 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
930 printf $fh "id:%d account:%s type:last_id reply\n", $new_poll_id, $username;
932 print scalar localtime, " - Polling for DMs" if &debug;
935 if ( $id_map{__last_id}{$username}{dm} )
937 $tweets = $obj->direct_messages(
938 { since_id => $id_map{__last_id}{$username}{dm} } )
941 $tweets = $obj->direct_messages() || [];
946 print $fh "type:debug Error during direct_messages call. Aborted.\n";
950 foreach my $t ( reverse @$tweets ) {
951 my $text = decode_entities( $t->{text} );
952 $text = &hilight($text);
953 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
954 $t->{id}, $username, $t->{sender_screen_name}, $text;
955 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
957 printf $fh "id:%d account:%s type:last_id dm\n", $new_poll_id, $username;
959 print scalar localtime, " - Polling for subscriptions" if &debug;
960 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
962 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
963 print $fh "type:debug searching for $topic since ",
964 "$id_map{__searches}{$username}{$topic}\n";
966 $search = $obj->search(
969 since_id => $id_map{__searches}{$username}{$topic}
976 "type:debug Error during search($topic) call. Aborted.\n";
980 unless ( $search->{max_id} ) {
981 print $fh "type:debug Invalid search results when searching",
982 " for $topic. Aborted.\n";
986 $id_map{__searches}{$username}{$topic} = $search->{max_id};
987 printf $fh "id:%d account:%s type:searchid topic:%s\n",
988 $search->{max_id}, $username, $topic;
990 foreach my $t ( reverse @{ $search->{results} } ) {
991 my $text = decode_entities( $t->{text} );
992 $text = &hilight($text);
993 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
994 $t->{id}, $username, $t->{from_user}, $topic, $text;
995 $new_poll_id = $t->{id}
997 or $t->{id} < $new_poll_id;
1002 print scalar localtime, " - Done" if &debug;
1009 my $filename = $data->[0];
1010 my $attempt = $data->[1];
1012 print scalar localtime, " - checking child log at $filename ($attempt)"
1014 my ($new_last_poll);
1016 # first time we run we don't want to print out *everything*, so we just
1019 $suppress = 1 unless keys %tweet_cache;
1021 if ( open FILE, $filename ) {
1026 last if /^__friends__/;
1030 foreach my $key (qw/id account nick type topic/) {
1031 if (s/^$key:(\S+)\s*//) {
1036 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1037 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1041 $new_cache{ $meta{id} } = time;
1043 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1049 $meta{account} =~ s/\@(\w+)$//;
1050 $meta{service} = $1;
1052 lc $meta{service} eq
1053 lc Irssi::settings_get_str("twirssi_default_service") )
1055 $account = "$meta{account}: "
1056 if lc "$meta{account}\@$meta{service}" ne lc
1057 "$user\@$defservice";
1059 $account = "$meta{account}\@$meta{service}: ";
1063 if ( $meta{type} ne 'dm'
1064 and Irssi::settings_get_bool("twirssi_track_replies")
1068 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1069 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1070 $id_map{__indexes}{ $meta{nick} } = $marker;
1071 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1072 $marker = ":$marker";
1076 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1078 '@' . substr( $meta{account}, 0, index( $meta{account}, "@" ) );
1079 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1080 and Irssi::settings_get_bool("twirssi_hilights") )
1082 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1083 $hilight = MSGLEVEL_HILIGHT;
1086 if ( $meta{type} =~ /tweet|reply/ ) {
1089 ( MSGLEVEL_PUBLIC | $hilight ),
1090 $meta{type}, $account, $meta{nick}, $marker, $_
1092 } elsif ( $meta{type} eq 'search' ) {
1095 ( MSGLEVEL_PUBLIC | $hilight ),
1096 $meta{type}, $account, $meta{topic},
1097 $meta{nick}, $marker, $_
1100 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1102 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1104 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1107 } elsif ( $meta{type} eq 'dm' ) {
1110 ( MSGLEVEL_MSGS | $hilight ),
1111 $meta{type}, $account, $meta{nick}, $_
1113 } elsif ( $meta{type} eq 'searchid' ) {
1114 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1116 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1118 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1120 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1123 print "Search '$meta{topic}' returned invalid id $meta{id}";
1125 } elsif ( $meta{type} eq 'last_id' ) {
1126 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1128 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1130 } elsif ( $meta{type} eq 'error' ) {
1131 push @lines, [ MSGLEVEL_MSGS, $_ ];
1132 } elsif ( $meta{type} eq 'debug' ) {
1133 print "$_" if &debug,;
1135 print "Unknown line type $meta{type}: $_" if &debug,;
1142 ($new_last_poll) = ($1);
1145 my ( $f, $t ) = split ' ', $_;
1146 $nicks{$f} = $friends{$f} = $t;
1149 if ($new_last_poll) {
1150 print "new last_poll = $new_last_poll" if &debug;
1151 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1153 print "First call, not printing updates" if &debug;
1155 foreach my $line (@lines) {
1156 $window->printformat(
1158 "twirssi_" . $line->[1],
1159 @$line[ 2 .. $#$line ]
1166 or warn "Failed to remove $filename: $!"
1169 # commit the pending cache lines to the actual cache, now that
1170 # we've printed our output
1171 %tweet_cache = ( %tweet_cache, %new_cache );
1173 # keep enough cached tweets, to make sure we don't show duplicates.
1174 foreach ( keys %tweet_cache ) {
1175 next if $tweet_cache{$_} >= $last_poll - 3600;
1176 delete $tweet_cache{$_};
1178 $last_poll = $new_last_poll;
1183 Irssi::settings_get_str("twirssi_replies_store") )
1185 if ( open JSON, ">$file" ) {
1186 print JSON JSON::Any->objToJson( \%id_map );
1189 &ccrap("Failed to write replies to $file: $!");
1199 if ( $attempt < 24 ) {
1200 Irssi::timeout_add_once( 5000, 'monitor_child',
1201 [ $filename, $attempt + 1 ] );
1203 print "Giving up on polling $filename" if &debug;
1204 unlink $filename unless &debug;
1206 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1209 my @time = localtime($last_poll);
1210 if ( time - $last_poll < 24 * 60 * 60 ) {
1211 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1213 $since = scalar localtime($last_poll);
1216 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1221 q{ .--./ / | _.---.| },
1232 &ccrap("Haven't been able to get updated tweets since $since");
1237 return Irssi::settings_get_bool("twirssi_debug");
1241 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1245 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1251 if ( Irssi::settings_get_bool("tweet_to_away")
1253 and $data !~ /^[dD] / )
1256 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1258 $server->send_raw("away :$data");
1261 &ccrap( "Can't find bitlbee server.",
1262 "Update bitlbee_server or disable tweet_to_away" );
1272 my $noalert = shift;
1274 if ( length $data > 140 ) {
1275 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1283 sub valid_username {
1284 my $username = shift;
1286 $username = &normalize_username($username);
1288 unless ( exists $twits{$username} ) {
1289 ¬ice("Unknown username $username");
1299 ¬ice("Not logged in! Use /twitter_login username pass!");
1307 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1310 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1311 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1312 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1314 { # /twitter_reply gets a nick:num
1316 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1317 sort { $nicks{$b} <=> $nicks{$a} }
1319 keys %{ $id_map{__indexes} };
1322 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1323 { # /twitter_unfriend gets a nick
1325 push @$complist, grep /^\Q$word/i,
1326 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1329 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1331 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1332 my $prefix = $word =~ s/^@//;
1333 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1334 push @$complist, grep /^\Q$word/i,
1335 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1336 @$complist = map { "\@$_" } @$complist if $prefix;
1340 sub event_send_text {
1341 my ( $line, $server, $win ) = @_;
1342 my $awin = Irssi::active_win();
1344 # if the window where we got our text was the twitter window, and the user
1345 # wants to be lazy, tweet away!
1346 if ( ( $awin->get_active_name() eq $window->{name} )
1347 and Irssi::settings_get_bool("tweet_window_input") )
1349 &cmd_tweet( $line, $server, $win );
1354 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1355 return $poll if $poll >= 60;
1362 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1363 my $c = Irssi::settings_get_str("twirssi_nick_color");
1364 $c = $irssi_to_mirc_colors{$c};
1365 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1367 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1368 my $c = Irssi::settings_get_str("twirssi_topic_color");
1369 $c = $irssi_to_mirc_colors{$c};
1370 $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1372 $text =~ s/[\n\r]/ /g;
1380 my $provider = Irssi::settings_get_str("short_url_provider");
1383 Irssi::settings_get_bool("twirssi_always_shorten")
1384 or &too_long( $data, 1 )
1390 if ( $provider eq 'Bitly' ) {
1391 @args[ 1, 2 ] = split ',',
1392 Irssi::settings_get_str("short_url_args"), 2;
1393 unless ( @args == 3 ) {
1395 "WWW::Shorten::Bitly requires a username and API key.",
1396 "Set short_url_args to username,API_key or change your",
1397 "short_url_provider."
1403 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1406 my $short = makeashorterlink(@args);
1408 $data =~ s/\Q$url/$short/g;
1410 ¬ice("Failed to shorten $url!");
1419 sub normalize_username {
1422 my ( $username, $service ) = split /\@/, $user, 2;
1424 $service = ucfirst lc $service;
1427 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1428 unless ( exists $twits{"$username\@$service"} ) {
1430 foreach my $t ( sort keys %twits ) {
1431 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1437 ¬ice("Can't find a logged in user '$user'");
1442 return "$username\@$service";
1445 Irssi::signal_add( "send text", "event_send_text" );
1447 Irssi::theme_register(
1449 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1450 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1451 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1452 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1453 'twirssi_error', 'ERROR: $0',
1457 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1458 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1459 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1460 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1461 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1462 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1463 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1464 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1465 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1466 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1467 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1468 'RT $n: "$t" ${-- $c$}' );
1469 Irssi::settings_add_str( "twirssi", "twirssi_location",
1470 ".irssi/scripts/twirssi.pl" );
1471 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1472 ".irssi/scripts/twirssi.json" );
1474 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1476 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1477 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1478 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1479 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1480 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1481 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1482 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1483 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1484 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1485 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1486 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1487 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1488 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1490 $last_poll = time - &get_poll_time;
1491 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1494 ->print( "Couldn't find a window named '"
1495 . Irssi::settings_get_str('twitter_window')
1496 . "', trying to create it." );
1498 Irssi::Windowitem::window_create(
1499 Irssi::settings_get_str('twitter_window'), 1 );
1500 $window->set_name( Irssi::settings_get_str('twitter_window') );
1504 Irssi::command_bind( "dm", "cmd_direct" );
1505 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1506 Irssi::command_bind( "tweet", "cmd_tweet" );
1507 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1508 Irssi::command_bind( "retweet", "cmd_retweet" );
1509 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1510 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1511 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1512 Irssi::command_bind( "twitter_login", "cmd_login" );
1513 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1514 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1515 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1516 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1517 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1518 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1519 Irssi::command_bind( "twitter_updates", "get_updates" );
1520 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1521 Irssi::command_bind( "reply", "cmd_reply" );
1522 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1524 Irssi::command_bind(
1527 print "twits: ", join ", ",
1528 map { "u: $_->{username}\@" . ref($_) } values %twits;
1529 print "selected: $user\@$defservice";
1530 print "friends: ", join ", ", sort keys %friends;
1531 print "nicks: ", join ", ", sort keys %nicks;
1532 print "searches: ", Dumper \%{ $id_map{__searches} };
1533 print "last poll: $last_poll";
1534 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1535 print DUMP Dumper \%tweet_cache;
1537 print "cache written out to /tmp/twirssi.cache.txt";
1541 Irssi::command_bind(
1544 ¬ice("Twirssi v$VERSION (r$REV); "
1545 . "Net::Twitter v$Net::Twitter::VERSION. "
1547 . JSON::Any::handler()
1548 . ". See details at http://twirssi.com/" );
1551 Irssi::command_bind(
1554 "/twitter_friend <username>",
1556 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1559 Irssi::command_bind(
1562 "/twitter_unfriend <username>",
1564 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1567 Irssi::command_bind(
1568 "twitter_device_updates",
1570 "/twitter_device_updates none|im|sms",
1571 "update_delivery_device",
1572 sub { ¬ice("Device updated to $_[0]"); }
1575 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1577 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1578 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1580 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1582 my $file = Irssi::settings_get_str("twirssi_replies_store");
1583 if ( $file and -r $file ) {
1584 if ( open( JSON, $file ) ) {
1589 my $ref = JSON::Any->jsonToObj($json);
1591 my $num = keys %{ $id_map{__indexes} };
1592 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1593 $num, ( $num == 1 ? "" : "s" ) );
1597 ¬ice("Failed to load old replies from $file: $!");
1601 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1602 ¬ice("Loading WWW::Shorten::$provider...");
1603 eval "use WWW::Shorten::$provider;";
1607 "Failed to load WWW::Shorten::$provider - either clear",
1608 "short_url_provider or install the CPAN module"
1613 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1614 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1622 ->print( "Create a window named "
1623 . Irssi::settings_get_str('twitter_window')
1624 . " or change the value of twitter_window. Then, reload twirssi." );
1627 # vim: set sts=4 expandtab: