9 $Data::Dumper::Indent = 1;
11 use vars qw($VERSION %IRSSI);
13 $VERSION = "2.2.5beta";
14 my ($REV) = '$Rev: 663 $' =~ /(\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-07-08 16:25:21 -0700 (Wed, 08 Jul 2009) $',
33 my $last_friends_poll = 0;
41 my %irssi_to_mirc_colors = (
61 my ( $data, $server, $win ) = @_;
63 return unless &logged_in($twit);
65 my ( $target, $text ) = split ' ', $data, 2;
66 unless ( $target and $text ) {
67 ¬ice("Usage: /dm <nick> <message>");
71 &cmd_direct_as( "$user $data", $server, $win );
75 my ( $data, $server, $win ) = @_;
77 return unless &logged_in($twit);
79 my ( $username, $target, $text ) = split ' ', $data, 3;
80 unless ( $username and $target and $text ) {
81 ¬ice("Usage: /dm_as <username> <nick> <message>");
85 return unless $username = &valid_username($username);
88 if ( $twits{$username}
89 ->new_direct_message( { user => $target, text => $text } ) )
91 ¬ice("DM sent to $target");
92 $nicks{$target} = time;
96 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
97 $error = $error->{error};
100 ¬ice("DM to $target failed");
105 ¬ice("DM caused an error: $@");
111 my ( $data, $server, $win ) = @_;
113 return unless &logged_in($twit);
115 $data =~ s/^\s+|\s+$//;
117 ¬ice("Usage: /retweet <nick[:num]> [comment]");
121 my ( $id, $data ) = split ' ', $data, 2;
123 &cmd_retweet_as( "$user $id $data", $server, $win );
127 my ( $data, $server, $win ) = @_;
129 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
130 ¬ice("twirssi_track_replies is required in order to reteet.");
134 return unless &logged_in($twit);
136 $data =~ s/^\s+|\s+$//;
137 my ( $username, $id, $data ) = split ' ', $data, 3;
140 ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
144 return unless $username = &valid_username($username);
147 $id =~ s/[^\w\d\-:]+//g;
148 ( $nick, $id ) = split /:/, $id;
149 unless ( exists $id_map{ lc $nick } ) {
150 ¬ice("Can't find a tweet from $nick to retweet!");
154 $id = $id_map{__indexes}{$nick} unless $id;
155 unless ( $id_map{ lc $nick }[$id] ) {
156 ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
160 unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
161 ¬ice("The text of this tweet isn't saved, sorry!");
165 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
166 my $text = Irssi::settings_get_str("twirssi_retweet_format");
167 $text =~ s/\$n/\@$nick/g;
169 $text =~ s/\${|\$}//g;
170 $text =~ s/\$c/$data/;
172 $text =~ s/\${.*?\$}//;
174 $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
176 $data = &shorten($text);
178 return if &too_long($data);
183 $twits{$username}->update(
186 # in_reply_to_status_id => $id_map{ lc $nick }[$id]
191 ¬ice("Update failed");
195 return unless $success;
198 ¬ice("Update caused an error: $@. Aborted");
202 foreach ( $data =~ /@([-\w]+)/ ) {
206 ¬ice("Retweet sent");
210 my ( $data, $server, $win ) = @_;
212 return unless &logged_in($twit);
214 $data =~ s/^\s+|\s+$//;
216 ¬ice("Usage: /tweet <update>");
220 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
224 my ( $data, $server, $win ) = @_;
226 return unless &logged_in($twit);
228 $data =~ s/^\s+|\s+$//;
229 $data =~ s/\s\s+/ /g;
230 my ( $username, $data ) = split ' ', $data, 2;
232 unless ( $username and $data ) {
233 ¬ice("Usage: /tweet_as <username> <update>");
237 return unless $username = &valid_username($username);
239 $data = &shorten($data);
241 return if &too_long($data);
245 unless ( $twits{$username}->update($data) )
247 ¬ice("Update failed");
251 return unless $success;
254 ¬ice("Update caused an error: $@. Aborted.");
258 foreach ( $data =~ /@([-\w]+)/ ) {
262 my $away = &update_away($data);
264 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
268 my ( $data, $server, $win ) = @_;
270 return unless &logged_in($twit);
272 $data =~ s/^\s+|\s+$//;
274 ¬ice("Usage: /reply <nick[:num]> <update>");
278 my ( $id, $data ) = split ' ', $data, 2;
279 unless ( $id and $data ) {
280 ¬ice("Usage: /reply <nick[:num]> <update>");
284 &cmd_reply_as( "$user $id $data", $server, $win );
288 my ( $data, $server, $win ) = @_;
290 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
291 ¬ice("twirssi_track_replies is required in order to reply to "
292 . "specific tweets. Either enable it, or just use /tweet "
293 . "\@username <text>." );
297 return unless &logged_in($twit);
299 $data =~ s/^\s+|\s+$//;
300 my ( $username, $id, $data ) = split ' ', $data, 3;
302 unless ( $username and $data ) {
303 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
307 return unless $username = &valid_username($username);
310 $id =~ s/[^\w\d\-:]+//g;
311 ( $nick, $id ) = split /:/, $id;
312 unless ( exists $id_map{ lc $nick } ) {
313 ¬ice("Can't find a tweet from $nick to reply to!");
317 $id = $id_map{__indexes}{$nick} unless $id;
318 unless ( $id_map{ lc $nick }[$id] ) {
319 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
323 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
325 # remove any @nick at the beginning of the reply, as we'll add it anyway
326 $data =~ s/^\s*\@?$nick\s*//;
327 $data = "\@$nick " . $data;
330 $data = &shorten($data);
332 return if &too_long($data);
337 $twits{$username}->update(
340 in_reply_to_status_id => $id_map{ lc $nick }[$id]
345 ¬ice("Update failed");
349 return unless $success;
352 ¬ice("Update caused an error: $@. Aborted");
356 foreach ( $data =~ /@([-\w]+)/ ) {
360 my $away = &update_away($data);
362 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
366 my ( $usage_str, $api_name, $post_ref ) = @_;
369 my ( $data, $server, $win ) = @_;
371 return unless &logged_in($twit);
373 $data =~ s/^\s+|\s+$//;
375 ¬ice("Usage: $usage_str");
381 unless ( $twit->$api_name($data) )
383 ¬ice("$api_name failed");
387 return unless $success;
390 ¬ice("$api_name caused an error. Aborted.");
394 &$post_ref($data) if $post_ref;
399 my ( $data, $server, $win ) = @_;
401 $data =~ s/^\s+|\s+$//g;
402 $data = &normalize_username($data);
403 if ( exists $twits{$data} ) {
404 ¬ice("Switching to $data");
405 $twit = $twits{$data};
406 if ( $data =~ /(.*)\@(.*)/ ) {
410 ¬ice("Couldn't figure out what service '$data' is on");
413 ¬ice("Unknown user $data");
418 my ( $data, $server, $win ) = @_;
420 $data =~ s/^\s+|\s+$//g;
421 $data = $user unless $data;
422 return unless $data = &valid_username($data);
424 ¬ice("Logging out $data...");
425 $twits{$data}->end_session();
426 delete $twits{$data};
429 &cmd_switch( ( keys %twits )[0], $server, $win );
431 Irssi::timeout_remove($poll) if $poll;
437 my ( $data, $server, $win ) = @_;
440 ( $user, $pass ) = split ' ', $data, 2;
441 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
442 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
444 my @user = split /\s*,\s*/, $autouser;
445 my @pass = split /\s*,\s*/, $autopass;
447 # if a password ends with a '\', it was meant to escape the comma, and
448 # it should be concatinated with the next one
452 while ( $p =~ /\\$/ and @pass ) {
453 $p .= "," . shift @pass;
458 if ( @user != @unescaped ) {
459 ¬ice("Number of usernames doesn't match "
460 . "the number of passwords - auto-login failed" );
463 while ( @user and @unescaped ) {
465 $p = shift @unescaped;
471 ¬ice("/twitter_login requires either a username and password "
472 . "or twitter_usernames and twitter_passwords to be set." );
476 %friends = %nicks = ();
479 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
480 ( $user, $service ) = ( $1, $2 );
482 $service = Irssi::settings_get_str("twirssi_default_service");
484 $defservice = $service = ucfirst lc $service;
486 eval "use Net::$service";
489 "Failed to load Net::$service when trying to log in as $user: $@");
493 $twit = "Net::$service"->new(
499 unless ( $twit->verify_credentials() ) {
500 ¬ice("Login as $user\@$service failed");
503 &cmd_switch( ( keys %twits )[0], $server, $win );
509 my $rate_limit = $twit->rate_limit_status();
510 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
512 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
518 $twits{"$user\@$service"} = $twit;
519 Irssi::timeout_remove($poll) if $poll;
520 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
521 ¬ice("Logged in as $user\@$service, loading friends list...");
523 ¬ice( "loaded friends: ", scalar keys %friends );
524 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
525 Irssi::settings_set_bool( "twirssi_first_run", 0 );
526 unless ( exists $friends{twirssi} ) {
527 ¬ice("Welcome to twirssi!"
528 . " Perhaps you should add \@twirssi to your friends list,"
529 . " so you can be notified when a new version is release?"
530 . " Just type /twitter_follow twirssi." );
537 ¬ice("Login failed");
542 my ( $data, $server, $win ) = @_;
544 unless ( $twit and $twit->can('search') ) {
545 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
546 . "doesn't support searches." );
550 $data =~ s/^\s+|\s+$//;
554 ¬ice("Usage: /twitter_subscribe <topic>");
558 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
559 ¬ice("Already had a subscription for '$data'");
563 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
564 ¬ice("Added subscription for '$data'");
568 my ( $data, $server, $win ) = @_;
570 unless ( $twit and $twit->can('search') ) {
571 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
572 . "doesn't support searches." );
575 $data =~ s/^\s+|\s+$//;
579 ¬ice("Usage: /twitter_unsubscribe <topic>");
583 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
584 ¬ice("No subscription found for '$data'");
588 delete $id_map{__searches}{"$user\@$defservice"}{$data};
589 ¬ice("Removed subscription for '$data'");
592 sub cmd_list_search {
593 my ( $data, $server, $win ) = @_;
596 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
598 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
599 $topics = $topics ? "$topics, $topic" : $topic;
603 ¬ice("Search subscriptions for \@$suser: $topics");
608 ¬ice("No search subscriptions set up");
613 my ( $data, $server, $win ) = @_;
615 my $loc = Irssi::settings_get_str("twirssi_location");
618 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
624 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
625 eval { use Digest::MD5; };
629 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
634 $md5 = get("http://twirssi.com/md5sum");
638 ¬ice("Failed to download md5sum from peeron! Aborting.");
642 unless ( open( CUR, $loc ) ) {
644 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
649 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
652 if ( $cur_md5 eq $md5 ) {
653 ¬ice("Current twirssi seems to be up to date.");
659 Irssi::settings_get_bool("twirssi_upgrade_beta")
660 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
661 : "http://twirssi.com/twirssi.pl";
662 ¬ice("Downloading twirssi from $URL");
663 LWP::Simple::getstore( $URL, "$loc.upgrade" );
665 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
666 unless ( open( NEW, "$loc.upgrade" ) ) {
668 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
673 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
676 if ( $new_md5 ne $md5 ) {
677 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
682 rename $loc, "$loc.backup"
683 or ¬ice("Failed to back up $loc: $!. Aborting")
685 rename "$loc.upgrade", $loc
686 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
689 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
690 if ( -e "$dir/autorun/$file" ) {
691 ¬ice("Updating $dir/autorun/$file");
692 unlink "$dir/autorun/$file"
693 or ¬ice("Failed to remove old $file from autorun: $!");
694 symlink "../$file", "$dir/autorun/$file"
695 or ¬ice("Failed to create symlink in autorun directory: $!");
698 ¬ice("Download complete. Reload twirssi with /script load $file");
708 print $fh "type:debug Loading friends page $page...\n"
709 if ( $fh and &debug );
710 my $friends = $twit->friends( { page => $page } );
711 last unless $friends;
712 $new_friends{ $_->{screen_name} } = time foreach @$friends;
714 last if @$friends == 0 or $page == 10;
719 print $fh "type:debug Error during friends list update. Aborted.\n";
723 my ( $added, $removed ) = ( 0, 0 );
724 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
725 foreach ( keys %new_friends ) {
726 next if exists $friends{$_};
731 print $fh "type:debug Scanning for removed friends...\n"
732 if ( $fh and &debug );
733 foreach ( keys %friends ) {
734 next if exists $new_friends{$_};
739 return ( $added, $removed );
743 print scalar localtime, " - get_updates starting" if &debug;
746 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
749 ->print( "Can't find a window named '"
750 . Irssi::settings_get_str('twitter_window')
751 . "'. Create it or change the value of twitter_window" );
754 return unless &logged_in($twit);
756 my ( $fh, $filename ) = File::Temp::tempfile();
757 binmode( $fh, ":utf8" );
761 Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
762 Irssi::pidwait_add($pid);
763 } elsif ( defined $pid ) { # child
772 foreach ( keys %twits ) {
773 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
776 print $fh "__friends__\n";
778 time - $last_friends_poll >
779 Irssi::settings_get_int('twitter_friends_poll') )
781 print $fh "__updated ", time, "\n";
782 my ( $added, $removed ) = &load_friends($fh);
783 if ( $added + $removed ) {
784 print $fh "type:debug %R***%n Friends list updated: ",
786 sprintf( "%d added", $added ),
787 sprintf( "%d removed", $removed ) ),
792 foreach ( sort keys %friends ) {
793 print $fh "$_ $friends{$_}\n";
797 print $fh "type:debug Update encountered errors. Aborted\n";
798 print $fh "-- $last_poll";
800 print $fh "-- $new_poll";
805 &ccrap("Failed to fork for updating: $!");
807 print scalar localtime, " - get_updates ends" if &debug;
811 my ( $fh, $username, $obj, $cache ) = @_;
813 my $rate_limit = $obj->rate_limit_status();
814 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
815 ¬ice("Rate limit exceeded for $username");
819 print scalar localtime, " - Polling for updates for $username" if &debug;
823 if ( $id_map{__last_id}{$username}{timeline} )
825 $tweets = $obj->friends_timeline( { count => 100 } );
827 $tweets = $obj->friends_timeline();
832 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
833 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
837 unless ( ref $tweets ) {
838 if ( $obj->can("get_error") ) {
839 my $error = "Unknown error";
840 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
841 unless ($@) { $error = $obj->get_error() }
843 "type:debug API Error during friends_timeline call: Aborted\n";
844 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
848 "type:debug API Error during friends_timeline call. Aborted.\n";
853 foreach my $t ( reverse @$tweets ) {
854 my $text = decode_entities( $t->{text} );
855 $text =~ s/[\n\r]/ /g;
857 if ( Irssi::settings_get_bool("show_reply_context")
858 and $t->{in_reply_to_screen_name} ne $username
859 and $t->{in_reply_to_screen_name}
860 and not exists $friends{ $t->{in_reply_to_screen_name} } )
862 $nicks{ $t->{in_reply_to_screen_name} } = time;
864 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
866 $cache->{ $t->{in_reply_to_status_id} } =
867 $obj->show_status( $t->{in_reply_to_status_id} );
871 $context = $cache->{ $t->{in_reply_to_status_id} };
874 my $ctext = decode_entities( $context->{text} );
875 $ctext =~ s/[\n\r]/ /g;
876 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
878 " -- http://twitter.com/$context->{user}{screen_name}"
879 . "/status/$context->{id}";
881 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
882 $context->{id}, $username,
883 $context->{user}{screen_name}, $ctext;
888 if $t->{user}{screen_name} eq $username
889 and not Irssi::settings_get_bool("show_own_tweets");
890 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
891 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
892 . "/status/$t->{id}";
894 printf $fh "id:%u account:%s nick:%s type:%s %s\n",
895 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
896 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
898 printf $fh "id:%u account:%s type:last_id timeline\n",
899 $new_poll_id, $username;
901 print scalar localtime, " - Polling for replies" if &debug;
904 if ( $id_map{__last_id}{$username}{reply} )
906 $tweets = $obj->replies(
907 { since_id => $id_map{__last_id}{$username}{reply} } )
910 $tweets = $obj->replies() || [];
915 print $fh "type:debug Error during replies call. Aborted.\n";
919 foreach my $t ( reverse @$tweets ) {
921 if exists $friends{ $t->{user}{screen_name} };
923 my $text = decode_entities( $t->{text} );
924 $text =~ s/[\n\r]/ /g;
925 if ( $t->{truncated} ) {
926 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
927 . "/status/$t->{id}";
929 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
930 $t->{id}, $username, $t->{user}{screen_name}, $text;
931 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
933 printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
935 print scalar localtime, " - Polling for DMs" if &debug;
938 if ( $id_map{__last_id}{$username}{dm} )
940 $tweets = $obj->direct_messages(
941 { since_id => $id_map{__last_id}{$username}{dm} } )
944 $tweets = $obj->direct_messages() || [];
949 print $fh "type:debug Error during direct_messages call. Aborted.\n";
953 foreach my $t ( reverse @$tweets ) {
954 my $text = decode_entities( $t->{text} );
955 $text =~ s/[\n\r]/ /g;
956 printf $fh "id:%u account:%s nick:%s type:dm %s\n",
957 $t->{id}, $username, $t->{sender_screen_name}, $text;
958 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
960 printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
962 print scalar localtime, " - Polling for subscriptions" if &debug;
963 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
965 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
966 print $fh "type:debug searching for $topic since ",
967 "$id_map{__searches}{$username}{$topic}\n";
969 $search = $obj->search(
972 since_id => $id_map{__searches}{$username}{$topic}
979 "type:debug Error during search($topic) call. Aborted.\n";
983 unless ( $search->{max_id} ) {
984 print $fh "type:debug Invalid search results when searching",
985 " for $topic. Aborted.\n";
989 $id_map{__searches}{$username}{$topic} = $search->{max_id};
990 printf $fh "id:%u account:%s type:searchid topic:%s\n",
991 $search->{max_id}, $username, $topic;
993 foreach my $t ( reverse @{ $search->{results} } ) {
994 my $text = decode_entities( $t->{text} );
995 $text =~ s/[\n\r]/ /g;
996 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
997 $t->{id}, $username, $t->{from_user}, $topic, $text;
998 $new_poll_id = $t->{id}
1000 or $t->{id} < $new_poll_id;
1005 print scalar localtime, " - Done" if &debug;
1012 my $filename = $data->[0];
1013 my $attempt = $data->[1];
1015 print scalar localtime, " - checking child log at $filename ($attempt)"
1017 my ($new_last_poll);
1019 # first time we run we don't want to print out *everything*, so we just
1022 if ( open FILE, $filename ) {
1026 last if /^__friends__/;
1027 unless (/\n$/) { # skip partial lines
1028 # print "Skipping partial line: $_" if &debug;
1035 foreach my $key (qw/id account nick type topic/) {
1036 if (s/^$key:(\S+)\s*//) {
1041 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1042 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1046 $new_cache{ $meta{id} } = time;
1048 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1054 $meta{account} =~ s/\@(\w+)$//;
1055 $meta{service} = $1;
1057 lc $meta{service} eq
1058 lc Irssi::settings_get_str("twirssi_default_service") )
1060 $account = "$meta{account}: "
1061 if lc "$meta{account}\@$meta{service}" ne lc
1062 "$user\@$defservice";
1064 $account = "$meta{account}\@$meta{service}: ";
1068 if ( $meta{type} ne 'dm'
1069 and Irssi::settings_get_bool("twirssi_track_replies")
1073 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1074 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1075 $id_map{__indexes}{ $meta{nick} } = $marker;
1076 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1077 $marker = ":$marker";
1081 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1082 my $nick = "\@$meta{account}";
1083 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1084 and Irssi::settings_get_bool("twirssi_hilights") )
1086 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1087 $hilight = MSGLEVEL_HILIGHT;
1090 if ( $meta{type} =~ /tweet|reply/ ) {
1093 ( MSGLEVEL_PUBLIC | $hilight ),
1094 $meta{type}, $account, $meta{nick}, $marker, $_
1096 } elsif ( $meta{type} eq 'search' ) {
1099 ( MSGLEVEL_PUBLIC | $hilight ),
1100 $meta{type}, $account, $meta{topic},
1101 $meta{nick}, $marker, $_
1104 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1106 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1108 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1111 } elsif ( $meta{type} eq 'dm' ) {
1114 ( MSGLEVEL_MSGS | $hilight ),
1115 $meta{type}, $account, $meta{nick}, $_
1117 } elsif ( $meta{type} eq 'searchid' ) {
1118 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1121 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1123 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1125 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1128 print "Search '$meta{topic}' returned invalid id $meta{id}";
1130 } elsif ( $meta{type} eq 'last_id' ) {
1131 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1133 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1135 } elsif ( $meta{type} eq 'error' ) {
1136 push @lines, [ MSGLEVEL_MSGS, $_ ];
1137 } elsif ( $meta{type} eq 'debug' ) {
1138 print "$_" if &debug,;
1140 print "Unknown line type $meta{type}: $_" if &debug,;
1146 if (/^__updated (\d+)$/) {
1147 $last_friends_poll = $1;
1148 print "Friend list updated" if &debug;
1153 ($new_last_poll) = ($1);
1156 my ( $f, $t ) = split ' ', $_;
1157 $nicks{$f} = $friends{$f} = $t;
1160 if ($new_last_poll) {
1161 print "new last_poll = $new_last_poll" if &debug;
1162 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1164 print "First call, not printing updates" if &debug;
1166 foreach my $line (@lines) {
1167 $window->printformat(
1169 "twirssi_" . $line->[1],
1170 @$line[ 2 .. $#$line-1 ],
1171 &hilight($line->[-1])
1178 or warn "Failed to remove $filename: $!"
1181 # commit the pending cache lines to the actual cache, now that
1182 # we've printed our output
1183 %tweet_cache = ( %tweet_cache, %new_cache );
1185 # keep enough cached tweets, to make sure we don't show duplicates.
1186 foreach ( keys %tweet_cache ) {
1187 next if $tweet_cache{$_} >= $last_poll - 3600;
1188 delete $tweet_cache{$_};
1190 $last_poll = $new_last_poll;
1195 Irssi::settings_get_str("twirssi_replies_store") )
1197 if ( open JSON, ">$file" ) {
1198 print JSON JSON::Any->objToJson( \%id_map );
1201 &ccrap("Failed to write replies to $file: $!");
1212 if ( $attempt < 24 ) {
1213 Irssi::timeout_add_once( 5000, 'monitor_child',
1214 [ $filename, $attempt + 1 ] );
1216 print "Giving up on polling $filename" if &debug;
1217 unlink $filename unless &debug;
1219 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1222 my @time = localtime($last_poll);
1223 if ( time - $last_poll < 24 * 60 * 60 ) {
1224 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1226 $since = scalar localtime($last_poll);
1229 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1234 q{ .--./ / | _.---.| },
1246 if ( time - $last_poll < 600 ) {
1247 &ccrap("Haven't been able to get updated tweets since $since");
1253 return Irssi::settings_get_bool("twirssi_debug");
1257 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1261 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1267 if ( Irssi::settings_get_bool("tweet_to_away")
1269 and $data !~ /^[dD] / )
1272 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1274 $server->send_raw("away :$data");
1277 &ccrap( "Can't find bitlbee server.",
1278 "Update bitlbee_server or disable tweet_to_away" );
1288 my $noalert = shift;
1290 if ( length $data > 140 ) {
1291 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1299 sub valid_username {
1300 my $username = shift;
1302 $username = &normalize_username($username);
1304 unless ( exists $twits{$username} ) {
1305 ¬ice("Unknown username $username");
1315 ¬ice("Not logged in! Use /twitter_login username pass!");
1323 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1326 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1327 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1328 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1330 { # /twitter_reply gets a nick:num
1332 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1333 sort { $nicks{$b} <=> $nicks{$a} }
1335 keys %{ $id_map{__indexes} };
1338 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1339 { # /twitter_unfriend gets a nick
1341 push @$complist, grep /^\Q$word/i,
1342 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1345 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1347 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1348 my $prefix = $word =~ s/^@//;
1349 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1350 push @$complist, grep /^\Q$word/i,
1351 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1352 @$complist = map { "\@$_" } @$complist if $prefix;
1356 sub event_send_text {
1357 my ( $line, $server, $win ) = @_;
1358 my $awin = Irssi::active_win();
1360 # if the window where we got our text was the twitter window, and the user
1361 # wants to be lazy, tweet away!
1362 if ( ( $awin->get_active_name() eq $window->{name} )
1363 and Irssi::settings_get_bool("tweet_window_input") )
1365 &cmd_tweet( $line, $server, $win );
1370 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1371 return $poll if $poll >= 60;
1378 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1379 my $c = Irssi::settings_get_str("twirssi_nick_color");
1380 $c = $irssi_to_mirc_colors{$c};
1381 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1383 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1384 my $c = Irssi::settings_get_str("twirssi_topic_color");
1385 $c = $irssi_to_mirc_colors{$c};
1386 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1388 $text =~ s/[\n\r]/ /g;
1396 my $provider = Irssi::settings_get_str("short_url_provider");
1399 Irssi::settings_get_bool("twirssi_always_shorten")
1400 or &too_long( $data, 1 )
1406 if ( $provider eq 'Bitly' ) {
1407 @args[ 1, 2 ] = split ',',
1408 Irssi::settings_get_str("short_url_args"), 2;
1409 unless ( @args == 3 ) {
1411 "WWW::Shorten::Bitly requires a username and API key.",
1412 "Set short_url_args to username,API_key or change your",
1413 "short_url_provider."
1419 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1422 my $short = makeashorterlink(@args);
1424 $data =~ s/\Q$url/$short/g;
1426 ¬ice("Failed to shorten $url!");
1435 sub normalize_username {
1438 my ( $username, $service ) = split /\@/, $user, 2;
1440 $service = ucfirst lc $service;
1443 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1444 unless ( exists $twits{"$username\@$service"} ) {
1446 foreach my $t ( sort keys %twits ) {
1447 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1453 ¬ice("Can't find a logged in user '$user'");
1458 return "$username\@$service";
1461 Irssi::signal_add( "send text", "event_send_text" );
1463 Irssi::theme_register(
1465 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1466 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1467 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1468 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1469 'twirssi_error', 'ERROR: $0',
1473 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1474 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1475 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1476 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1477 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1478 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1479 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1480 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1481 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1482 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1483 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1484 'RT $n: "$t" ${-- $c$}' );
1485 Irssi::settings_add_str( "twirssi", "twirssi_location",
1486 ".irssi/scripts/twirssi.pl" );
1487 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1488 ".irssi/scripts/twirssi.json" );
1490 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1492 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1493 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1494 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1495 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1496 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1497 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1498 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1499 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1500 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1501 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1502 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1503 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1504 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1506 $last_poll = time - &get_poll_time;
1507 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1510 ->print( "Couldn't find a window named '"
1511 . Irssi::settings_get_str('twitter_window')
1512 . "', trying to create it." );
1514 Irssi::Windowitem::window_create(
1515 Irssi::settings_get_str('twitter_window'), 1 );
1516 $window->set_name( Irssi::settings_get_str('twitter_window') );
1520 Irssi::command_bind( "dm", "cmd_direct" );
1521 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1522 Irssi::command_bind( "tweet", "cmd_tweet" );
1523 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1524 Irssi::command_bind( "retweet", "cmd_retweet" );
1525 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1526 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1527 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1528 Irssi::command_bind( "twitter_login", "cmd_login" );
1529 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1530 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1531 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1532 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1533 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1534 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1535 Irssi::command_bind( "twitter_updates", "get_updates" );
1536 Irssi::command_bind( "bitlbee_away", "update_away" );
1537 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1538 Irssi::command_bind( "reply", "cmd_reply" );
1539 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1541 Irssi::command_bind(
1544 print "twits: ", join ", ",
1545 map { "u: $_->{username}\@" . ref($_) } values %twits;
1546 print "selected: $user\@$defservice";
1547 print "friends: ", join ", ", sort keys %friends;
1548 print "nicks: ", join ", ", sort keys %nicks;
1549 print "searches: ", Dumper \%{ $id_map{__searches} };
1550 print "last poll: $last_poll";
1551 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1552 print DUMP Dumper \%tweet_cache;
1554 print "cache written out to /tmp/twirssi.cache.txt";
1558 Irssi::command_bind(
1561 ¬ice("Twirssi v$VERSION (r$REV); "
1562 . "Net::Twitter v$Net::Twitter::VERSION. "
1564 . JSON::Any::handler()
1565 . ". See details at http://twirssi.com/" );
1568 Irssi::command_bind(
1571 "/twitter_follow <username>",
1573 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1576 Irssi::command_bind(
1579 "/twitter_unfriend <username>",
1581 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1584 Irssi::command_bind(
1585 "twitter_device_updates",
1587 "/twitter_device_updates none|im|sms",
1588 "update_delivery_device",
1589 sub { ¬ice("Device updated to $_[0]"); }
1592 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1594 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1595 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1597 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1599 my $file = Irssi::settings_get_str("twirssi_replies_store");
1600 if ( $file and -r $file ) {
1601 if ( open( JSON, $file ) ) {
1606 my $ref = JSON::Any->jsonToObj($json);
1608 my $num = keys %{ $id_map{__indexes} };
1609 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1610 $num, ( $num == 1 ? "" : "s" ) );
1614 ¬ice("Failed to load old replies from $file: $!");
1618 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1619 ¬ice("Loading WWW::Shorten::$provider...");
1620 eval "use WWW::Shorten::$provider;";
1624 "Failed to load WWW::Shorten::$provider - either clear",
1625 "short_url_provider or install the CPAN module"
1630 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1631 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1639 ->print( "Create a window named "
1640 . Irssi::settings_get_str('twitter_window')
1641 . " or change the value of twitter_window. Then, reload twirssi." );
1644 # vim: set sts=4 expandtab: