10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
14 $VERSION = "2.2.5beta";
15 my ($REV) = '$Rev: 687 $' =~ /(\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-08-07 01:24:53 -0700 (Fri, 07 Aug 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(
188 # in_reply_to_status_id => $id_map{ lc $nick }[$id]
193 ¬ice("Update failed");
197 return unless $success;
200 ¬ice("Update caused an error: $@. Aborted");
204 foreach ( $data =~ /@([-\w]+)/ ) {
208 ¬ice("Retweet sent");
212 my ( $data, $server, $win ) = @_;
214 return unless &logged_in($twit);
216 $data =~ s/^\s+|\s+$//;
218 ¬ice("Usage: /tweet <update>");
222 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
226 my ( $data, $server, $win ) = @_;
228 return unless &logged_in($twit);
230 $data =~ s/^\s+|\s+$//;
231 $data =~ s/\s\s+/ /g;
232 my ( $username, $data ) = split ' ', $data, 2;
234 unless ( $username and $data ) {
235 ¬ice("Usage: /tweet_as <username> <update>");
239 return unless $username = &valid_username($username);
241 $data = &shorten($data);
243 return if &too_long($data);
247 unless ( $twits{$username}->update($data) )
249 ¬ice("Update failed");
253 return unless $success;
256 ¬ice("Update caused an error: $@. Aborted.");
260 foreach ( $data =~ /@([-\w]+)/ ) {
264 my $away = &update_away($data);
266 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
270 my ( $data, $server, $win ) = @_;
272 return unless &logged_in($twit);
274 $data =~ s/^\s+|\s+$//;
276 ¬ice("Usage: /reply <nick[:num]> <update>");
280 my ( $id, $data ) = split ' ', $data, 2;
281 unless ( $id and $data ) {
282 ¬ice("Usage: /reply <nick[:num]> <update>");
286 &cmd_reply_as( "$user $id $data", $server, $win );
290 my ( $data, $server, $win ) = @_;
292 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
293 ¬ice("twirssi_track_replies is required in order to reply to "
294 . "specific tweets. Either enable it, or just use /tweet "
295 . "\@username <text>." );
299 return unless &logged_in($twit);
301 $data =~ s/^\s+|\s+$//;
302 my ( $username, $id, $data ) = split ' ', $data, 3;
304 unless ( $username and $data ) {
305 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
309 return unless $username = &valid_username($username);
312 $id =~ s/[^\w\d\-:]+//g;
313 ( $nick, $id ) = split /:/, $id;
314 unless ( exists $id_map{ lc $nick } ) {
315 ¬ice("Can't find a tweet from $nick to reply to!");
319 $id = $id_map{__indexes}{$nick} unless $id;
320 unless ( $id_map{ lc $nick }[$id] ) {
321 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
325 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
327 # remove any @nick at the beginning of the reply, as we'll add it anyway
328 $data =~ s/^\s*\@?$nick\s*//;
329 $data = "\@$nick " . $data;
332 $data = &shorten($data);
334 return if &too_long($data);
339 $twits{$username}->update(
342 in_reply_to_status_id => $id_map{ lc $nick }[$id]
347 ¬ice("Update failed");
351 return unless $success;
354 ¬ice("Update caused an error: $@. Aborted");
358 foreach ( $data =~ /@([-\w]+)/ ) {
362 my $away = &update_away($data);
364 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
368 my ( $usage_str, $api_name, $post_ref ) = @_;
371 my ( $data, $server, $win ) = @_;
373 return unless &logged_in($twit);
375 $data =~ s/^\s+|\s+$//;
377 ¬ice("Usage: $usage_str");
383 unless ( $twit->$api_name($data) )
385 ¬ice("$api_name failed");
389 return unless $success;
392 ¬ice("$api_name caused an error. Aborted.");
396 &$post_ref($data) if $post_ref;
401 my ( $data, $server, $win ) = @_;
403 $data =~ s/^\s+|\s+$//g;
404 $data = &normalize_username($data);
405 if ( exists $twits{$data} ) {
406 ¬ice("Switching to $data");
407 $twit = $twits{$data};
408 if ( $data =~ /(.*)\@(.*)/ ) {
412 ¬ice("Couldn't figure out what service '$data' is on");
415 ¬ice("Unknown user $data");
420 my ( $data, $server, $win ) = @_;
422 $data =~ s/^\s+|\s+$//g;
423 $data = $user unless $data;
424 return unless $data = &valid_username($data);
426 ¬ice("Logging out $data...");
427 $twits{$data}->end_session();
428 delete $twits{$data};
431 &cmd_switch( ( keys %twits )[0], $server, $win );
433 Irssi::timeout_remove($poll) if $poll;
439 my ( $data, $server, $win ) = @_;
442 ( $user, $pass ) = split ' ', $data, 2;
443 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
444 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
446 my @user = split /\s*,\s*/, $autouser;
447 my @pass = split /\s*,\s*/, $autopass;
449 # if a password ends with a '\', it was meant to escape the comma, and
450 # it should be concatinated with the next one
454 while ( $p =~ /\\$/ and @pass ) {
455 $p .= "," . shift @pass;
460 if ( @user != @unescaped ) {
461 ¬ice("Number of usernames doesn't match "
462 . "the number of passwords - auto-login failed" );
465 while ( @user and @unescaped ) {
467 $p = shift @unescaped;
473 ¬ice("/twitter_login requires either a username and password "
474 . "or twitter_usernames and twitter_passwords to be set." );
478 %friends = %nicks = ();
481 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
482 ( $user, $service ) = ( $1, $2 );
484 $service = Irssi::settings_get_str("twirssi_default_service");
486 $defservice = $service = ucfirst lc $service;
488 eval "use Net::$service";
491 "Failed to load Net::$service when trying to log in as $user: $@");
495 $twit = "Net::$service"->new(
499 ssl => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
502 unless ( $twit->verify_credentials() ) {
503 ¬ice("Login as $user\@$service failed");
506 &cmd_switch( ( keys %twits )[0], $server, $win );
512 my $rate_limit = $twit->rate_limit_status();
513 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
515 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
521 $twits{"$user\@$service"} = $twit;
522 Irssi::timeout_remove($poll) if $poll;
523 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
524 ¬ice("Logged in as $user\@$service, loading friends list...");
526 ¬ice( "loaded friends: ", scalar keys %friends );
527 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
528 Irssi::settings_set_bool( "twirssi_first_run", 0 );
529 unless ( exists $friends{twirssi} ) {
530 ¬ice("Welcome to twirssi!"
531 . " Perhaps you should add \@twirssi to your friends list,"
532 . " so you can be notified when a new version is release?"
533 . " Just type /twitter_follow twirssi." );
540 ¬ice("Login failed");
545 my ( $data, $server, $win ) = @_;
547 unless ( $twit and $twit->can('search') ) {
548 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
549 . "doesn't support searches." );
553 $data =~ s/^\s+|\s+$//;
557 ¬ice("Usage: /twitter_subscribe <topic>");
561 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
562 ¬ice("Already had a subscription for '$data'");
566 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
567 ¬ice("Added subscription for '$data'");
571 my ( $data, $server, $win ) = @_;
573 unless ( $twit and $twit->can('search') ) {
574 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
575 . "doesn't support searches." );
578 $data =~ s/^\s+|\s+$//;
582 ¬ice("Usage: /twitter_unsubscribe <topic>");
586 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
587 ¬ice("No subscription found for '$data'");
591 delete $id_map{__searches}{"$user\@$defservice"}{$data};
592 ¬ice("Removed subscription for '$data'");
595 sub cmd_list_search {
596 my ( $data, $server, $win ) = @_;
599 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
601 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
602 $topics = $topics ? "$topics, $topic" : $topic;
606 ¬ice("Search subscriptions for \@$suser: $topics");
611 ¬ice("No search subscriptions set up");
616 my ( $data, $server, $win ) = @_;
618 my $loc = Irssi::settings_get_str("twirssi_location");
621 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
627 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
628 eval { use Digest::MD5; };
632 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
637 $md5 = get("http://twirssi.com/md5sum");
641 ¬ice("Failed to download md5sum from peeron! Aborting.");
645 unless ( open( CUR, $loc ) ) {
647 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
652 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
655 if ( $cur_md5 eq $md5 ) {
656 ¬ice("Current twirssi seems to be up to date.");
662 Irssi::settings_get_bool("twirssi_upgrade_beta")
663 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
664 : "http://twirssi.com/twirssi.pl";
665 ¬ice("Downloading twirssi from $URL");
666 LWP::Simple::getstore( $URL, "$loc.upgrade" );
668 unless ( -s "$loc.upgrade" ) {
669 ¬ice("Failed to save $loc.upgrade."
670 . " Check that /set twirssi_location is set to the correct location."
675 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
676 unless ( open( NEW, "$loc.upgrade" ) ) {
677 ¬ice("Failed to read $loc.upgrade."
678 . " Check that /set twirssi_location is set to the correct location."
683 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
686 if ( $new_md5 ne $md5 ) {
687 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
692 rename $loc, "$loc.backup"
693 or ¬ice("Failed to back up $loc: $!. Aborting")
695 rename "$loc.upgrade", $loc
696 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
699 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
700 if ( -e "$dir/autorun/$file" ) {
701 ¬ice("Updating $dir/autorun/$file");
702 unlink "$dir/autorun/$file"
703 or ¬ice("Failed to remove old $file from autorun: $!");
704 symlink "../$file", "$dir/autorun/$file"
705 or ¬ice("Failed to create symlink in autorun directory: $!");
708 ¬ice("Download complete. Reload twirssi with /script load $file");
718 print $fh "type:debug Loading friends page $page...\n"
719 if ( $fh and &debug );
720 my $friends = $twit->friends( { page => $page } );
721 last unless $friends;
722 $new_friends{ $_->{screen_name} } = time foreach @$friends;
724 last if @$friends == 0 or $page == 10;
729 print $fh "type:debug Error during friends list update. Aborted.\n";
733 my ( $added, $removed ) = ( 0, 0 );
734 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
735 foreach ( keys %new_friends ) {
736 next if exists $friends{$_};
741 print $fh "type:debug Scanning for removed friends...\n"
742 if ( $fh and &debug );
743 foreach ( keys %friends ) {
744 next if exists $new_friends{$_};
749 return ( $added, $removed );
753 print scalar localtime, " - get_updates starting" if &debug;
756 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
759 ->print( "Can't find a window named '"
760 . Irssi::settings_get_str('twitter_window')
761 . "'. Create it or change the value of twitter_window" );
764 return unless &logged_in($twit);
766 my ( $fh, $filename ) = File::Temp::tempfile();
767 binmode( $fh, ":utf8" );
771 Irssi::timeout_add_once( 5000, 'monitor_child',
772 [ "$filename.done", 0 ] );
773 Irssi::pidwait_add($pid);
774 } elsif ( defined $pid ) { # child
783 foreach ( keys %twits ) {
784 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
787 print $fh "__friends__\n";
789 time - $last_friends_poll >
790 Irssi::settings_get_int('twitter_friends_poll') )
792 print $fh "__updated ", time, "\n";
793 my ( $added, $removed ) = &load_friends($fh);
794 if ( $added + $removed ) {
795 print $fh "type:debug %R***%n Friends list updated: ",
797 sprintf( "%d added", $added ),
798 sprintf( "%d removed", $removed ) ),
803 foreach ( sort keys %friends ) {
804 print $fh "$_ $friends{$_}\n";
808 print $fh "type:debug Update encountered errors. Aborted\n";
809 print $fh "-- $last_poll";
811 print $fh "-- $new_poll";
814 rename $filename, "$filename.done";
817 &ccrap("Failed to fork for updating: $!");
819 print scalar localtime, " - get_updates ends" if &debug;
823 my ( $fh, $username, $obj, $cache ) = @_;
825 my $rate_limit = $obj->rate_limit_status();
826 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
827 ¬ice("Rate limit exceeded for $username");
831 print scalar localtime, " - Polling for updates for $username" if &debug;
835 if ( $id_map{__last_id}{$username}{timeline} )
837 $tweets = $obj->friends_timeline( { count => 100 } );
839 $tweets = $obj->friends_timeline();
844 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
845 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
849 unless ( ref $tweets ) {
850 if ( $obj->can("get_error") ) {
851 my $error = "Unknown error";
852 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
853 unless ($@) { $error = $obj->get_error() }
855 "type:debug API Error during friends_timeline call: Aborted\n";
856 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
860 "type:debug API Error during friends_timeline call. Aborted.\n";
865 foreach my $t ( reverse @$tweets ) {
866 my $text = decode_entities( $t->{text} );
867 $text =~ s/[\n\r]/ /g;
869 if ( Irssi::settings_get_bool("show_reply_context")
870 and $t->{in_reply_to_screen_name} ne $username
871 and $t->{in_reply_to_screen_name}
872 and not exists $friends{ $t->{in_reply_to_screen_name} } )
874 $nicks{ $t->{in_reply_to_screen_name} } = time;
876 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
878 $cache->{ $t->{in_reply_to_status_id} } =
879 $obj->show_status( $t->{in_reply_to_status_id} );
883 $context = $cache->{ $t->{in_reply_to_status_id} };
886 my $ctext = decode_entities( $context->{text} );
887 $ctext =~ s/[\n\r]/ /g;
888 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
890 " -- http://twitter.com/$context->{user}{screen_name}"
891 . "/status/$context->{id}";
893 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
894 $context->{id}, $username,
895 $context->{user}{screen_name}, $ctext;
900 if $t->{user}{screen_name} eq $username
901 and not Irssi::settings_get_bool("show_own_tweets");
902 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
903 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
904 . "/status/$t->{id}";
906 printf $fh "id:%u account:%s nick:%s type:%s %s\n",
907 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
908 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
910 printf $fh "id:%u account:%s type:last_id timeline\n",
911 $new_poll_id, $username;
913 print scalar localtime, " - Polling for replies" if &debug;
916 if ( $id_map{__last_id}{$username}{reply} )
918 $tweets = $obj->replies(
919 { since_id => $id_map{__last_id}{$username}{reply} } )
922 $tweets = $obj->replies() || [];
927 print $fh "type:debug Error during replies call. Aborted.\n";
931 foreach my $t ( reverse @$tweets ) {
933 if exists $friends{ $t->{user}{screen_name} };
935 my $text = decode_entities( $t->{text} );
936 $text =~ s/[\n\r]/ /g;
937 if ( $t->{truncated} ) {
938 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
939 . "/status/$t->{id}";
941 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
942 $t->{id}, $username, $t->{user}{screen_name}, $text;
943 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
945 printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
947 print scalar localtime, " - Polling for DMs" if &debug;
950 if ( $id_map{__last_id}{$username}{dm} )
952 $tweets = $obj->direct_messages(
953 { since_id => $id_map{__last_id}{$username}{dm} } )
956 $tweets = $obj->direct_messages() || [];
961 print $fh "type:debug Error during direct_messages call. Aborted.\n";
965 foreach my $t ( reverse @$tweets ) {
966 my $text = decode_entities( $t->{text} );
967 $text =~ s/[\n\r]/ /g;
968 printf $fh "id:%u account:%s nick:%s type:dm %s\n",
969 $t->{id}, $username, $t->{sender_screen_name}, $text;
970 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
972 printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
974 print scalar localtime, " - Polling for subscriptions" if &debug;
975 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
977 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
978 print $fh "type:debug searching for $topic since ",
979 "$id_map{__searches}{$username}{$topic}\n";
981 $search = $obj->search(
984 since_id => $id_map{__searches}{$username}{$topic}
991 "type:debug Error during search($topic) call. Aborted.\n";
995 unless ( $search->{max_id} ) {
996 print $fh "type:debug Invalid search results when searching",
997 " for $topic. Aborted.\n";
1001 $id_map{__searches}{$username}{$topic} = $search->{max_id};
1002 printf $fh "id:%u account:%s type:searchid topic:%s\n",
1003 $search->{max_id}, $username, $topic;
1005 foreach my $t ( reverse @{ $search->{results} } ) {
1006 my $text = decode_entities( $t->{text} );
1007 $text =~ s/[\n\r]/ /g;
1008 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
1009 $t->{id}, $username, $t->{from_user}, $topic, $text;
1010 $new_poll_id = $t->{id}
1012 or $t->{id} < $new_poll_id;
1017 print scalar localtime, " - Done" if &debug;
1024 my $filename = $data->[0];
1025 my $attempt = $data->[1];
1027 print scalar localtime, " - checking child log at $filename ($attempt)"
1029 my ($new_last_poll);
1031 # first time we run we don't want to print out *everything*, so we just
1034 if ( open FILE, $filename ) {
1035 bindmode FILE, ":utf8";
1039 last if /^__friends__/;
1040 unless (/\n$/) { # skip partial lines
1041 # print "Skipping partial line: $_" if &debug;
1048 foreach my $key (qw/id account nick type topic/) {
1049 if (s/^$key:(\S+)\s*//) {
1054 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1055 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1059 $new_cache{ $meta{id} } = time;
1061 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1067 $meta{account} =~ s/\@(\w+)$//;
1068 $meta{service} = $1;
1070 lc $meta{service} eq
1071 lc Irssi::settings_get_str("twirssi_default_service") )
1073 $account = "$meta{account}: "
1074 if lc "$meta{account}\@$meta{service}" ne lc
1075 "$user\@$defservice";
1077 $account = "$meta{account}\@$meta{service}: ";
1081 if ( $meta{type} ne 'dm'
1082 and Irssi::settings_get_bool("twirssi_track_replies")
1086 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1087 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1088 $id_map{__indexes}{ $meta{nick} } = $marker;
1089 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1090 $marker = ":$marker";
1094 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1095 my $nick = "\@$meta{account}";
1096 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1097 and Irssi::settings_get_bool("twirssi_hilights") )
1099 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1100 $hilight = MSGLEVEL_HILIGHT;
1103 if ( $meta{type} =~ /tweet|reply/ ) {
1106 ( MSGLEVEL_PUBLIC | $hilight ),
1107 $meta{type}, $account, $meta{nick}, $marker, $_
1109 } elsif ( $meta{type} eq 'search' ) {
1112 ( MSGLEVEL_PUBLIC | $hilight ),
1113 $meta{type}, $account, $meta{topic},
1114 $meta{nick}, $marker, $_
1117 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1119 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1121 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1124 } elsif ( $meta{type} eq 'dm' ) {
1127 ( MSGLEVEL_MSGS | $hilight ),
1128 $meta{type}, $account, $meta{nick}, $_
1130 } elsif ( $meta{type} eq 'searchid' ) {
1131 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1134 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1136 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1138 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1141 print "Search '$meta{topic}' returned invalid id $meta{id}";
1143 } elsif ( $meta{type} eq 'last_id' ) {
1144 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1146 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1148 } elsif ( $meta{type} eq 'error' ) {
1149 push @lines, [ MSGLEVEL_MSGS, $_ ];
1150 } elsif ( $meta{type} eq 'debug' ) {
1151 print "$_" if &debug,;
1153 print "Unknown line type $meta{type}: $_" if &debug,;
1159 if (/^__updated (\d+)$/) {
1160 $last_friends_poll = $1;
1161 print "Friend list updated" if &debug;
1166 ($new_last_poll) = ($1);
1169 my ( $f, $t ) = split ' ', $_;
1170 $nicks{$f} = $friends{$f} = $t;
1173 if ($new_last_poll) {
1174 print "new last_poll = $new_last_poll" if &debug;
1175 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1177 print "First call, not printing updates" if &debug;
1179 foreach my $line (@lines) {
1180 $window->printformat(
1182 "twirssi_" . $line->[1],
1183 @$line[ 2 .. $#$line - 1 ],
1184 &hilight( $line->[-1] )
1191 or warn "Failed to remove $filename: $!"
1194 # commit the pending cache lines to the actual cache, now that
1195 # we've printed our output
1196 %tweet_cache = ( %tweet_cache, %new_cache );
1198 # keep enough cached tweets, to make sure we don't show duplicates.
1199 foreach ( keys %tweet_cache ) {
1200 next if $tweet_cache{$_} >= $last_poll - 3600;
1201 delete $tweet_cache{$_};
1203 $last_poll = $new_last_poll;
1208 Irssi::settings_get_str("twirssi_replies_store") )
1210 if ( open JSON, ">$file" ) {
1211 print JSON JSON::Any->objToJson( \%id_map );
1214 &ccrap("Failed to write replies to $file: $!");
1225 if ( $attempt < 24 ) {
1226 Irssi::timeout_add_once( 5000, 'monitor_child',
1227 [ $filename, $attempt + 1 ] );
1229 print "Giving up on polling $filename" if &debug;
1230 unlink $filename unless &debug;
1232 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1235 my @time = localtime($last_poll);
1236 if ( time - $last_poll < 24 * 60 * 60 ) {
1237 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1239 $since = scalar localtime($last_poll);
1242 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1247 q{ .--./ / | _.---.| },
1259 if ( time - $last_poll < 600 ) {
1260 &ccrap("Haven't been able to get updated tweets since $since");
1266 return Irssi::settings_get_bool("twirssi_debug");
1270 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1274 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1280 if ( Irssi::settings_get_bool("tweet_to_away")
1282 and $data !~ /^[dD] / )
1285 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1287 $server->send_raw("away :$data");
1290 &ccrap( "Can't find bitlbee server.",
1291 "Update bitlbee_server or disable tweet_to_away" );
1301 my $noalert = shift;
1303 if ( length $data > 140 ) {
1304 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1312 sub valid_username {
1313 my $username = shift;
1315 $username = &normalize_username($username);
1317 unless ( exists $twits{$username} ) {
1318 ¬ice("Unknown username $username");
1328 ¬ice("Not logged in! Use /twitter_login username pass!");
1336 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1339 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1340 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1341 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1343 { # /twitter_reply gets a nick:num
1345 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1346 sort { $nicks{$b} <=> $nicks{$a} }
1348 keys %{ $id_map{__indexes} };
1351 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1352 { # /twitter_unfriend gets a nick
1354 push @$complist, grep /^\Q$word/i,
1355 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1358 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1360 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1361 my $prefix = $word =~ s/^@//;
1362 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1363 push @$complist, grep /^\Q$word/i,
1364 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1365 @$complist = map { "\@$_" } @$complist if $prefix;
1369 sub event_send_text {
1370 my ( $line, $server, $win ) = @_;
1371 my $awin = Irssi::active_win();
1373 # if the window where we got our text was the twitter window, and the user
1374 # wants to be lazy, tweet away!
1375 if ( ( $awin->get_active_name() eq $window->{name} )
1376 and Irssi::settings_get_bool("tweet_window_input") )
1378 &cmd_tweet( $line, $server, $win );
1383 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1384 return $poll if $poll >= 60;
1391 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1392 my $c = Irssi::settings_get_str("twirssi_nick_color");
1393 $c = $irssi_to_mirc_colors{$c};
1394 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1396 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1397 my $c = Irssi::settings_get_str("twirssi_topic_color");
1398 $c = $irssi_to_mirc_colors{$c};
1399 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1401 $text =~ s/[\n\r]/ /g;
1409 my $provider = Irssi::settings_get_str("short_url_provider");
1412 Irssi::settings_get_bool("twirssi_always_shorten")
1413 or &too_long( $data, 1 )
1419 if ( $provider eq 'Bitly' ) {
1420 @args[ 1, 2 ] = split ',',
1421 Irssi::settings_get_str("short_url_args"), 2;
1422 unless ( @args == 3 ) {
1424 "WWW::Shorten::Bitly requires a username and API key.",
1425 "Set short_url_args to username,API_key or change your",
1426 "short_url_provider."
1432 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1435 my $short = makeashorterlink(@args);
1437 $data =~ s/\Q$url/$short/g;
1439 ¬ice("Failed to shorten $url!");
1445 return decode "utf8", $data;
1448 sub normalize_username {
1451 my ( $username, $service ) = split /\@/, $user, 2;
1453 $service = ucfirst lc $service;
1456 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1457 unless ( exists $twits{"$username\@$service"} ) {
1459 foreach my $t ( sort keys %twits ) {
1460 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1466 ¬ice("Can't find a logged in user '$user'");
1471 return "$username\@$service";
1474 Irssi::signal_add( "send text", "event_send_text" );
1476 Irssi::theme_register(
1478 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1479 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1480 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1481 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1482 'twirssi_error', 'ERROR: $0',
1486 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1487 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1488 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1489 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1490 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1491 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1492 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1493 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1494 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1495 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1496 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1497 'RT $n: "$t" ${-- $c$}' );
1498 Irssi::settings_add_str( "twirssi", "twirssi_location",
1499 ".irssi/scripts/twirssi.pl" );
1500 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1501 ".irssi/scripts/twirssi.json" );
1503 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1505 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1506 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1507 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1508 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1509 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1510 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1511 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1512 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1513 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1514 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1515 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1516 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1517 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1518 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl", 0 );
1520 $last_poll = time - &get_poll_time;
1521 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1524 ->print( "Couldn't find a window named '"
1525 . Irssi::settings_get_str('twitter_window')
1526 . "', trying to create it." );
1528 Irssi::Windowitem::window_create(
1529 Irssi::settings_get_str('twitter_window'), 1 );
1530 $window->set_name( Irssi::settings_get_str('twitter_window') );
1534 Irssi::command_bind( "dm", "cmd_direct" );
1535 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1536 Irssi::command_bind( "tweet", "cmd_tweet" );
1537 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1538 Irssi::command_bind( "retweet", "cmd_retweet" );
1539 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1540 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1541 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1542 Irssi::command_bind( "twitter_login", "cmd_login" );
1543 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1544 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1545 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1546 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1547 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1548 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1549 Irssi::command_bind( "twitter_updates", "get_updates" );
1550 Irssi::command_bind( "bitlbee_away", "update_away" );
1551 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1552 Irssi::command_bind( "reply", "cmd_reply" );
1553 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1555 Irssi::command_bind(
1558 print "twits: ", join ", ",
1559 map { "u: $_->{username}\@" . ref($_) } values %twits;
1560 print "selected: $user\@$defservice";
1561 print "friends: ", join ", ", sort keys %friends;
1562 print "nicks: ", join ", ", sort keys %nicks;
1563 print "searches: ", Dumper \%{ $id_map{__searches} };
1564 print "last poll: $last_poll";
1565 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1566 print DUMP Dumper \%tweet_cache;
1568 print "cache written out to /tmp/twirssi.cache.txt";
1572 Irssi::command_bind(
1575 ¬ice("Twirssi v$VERSION (r$REV); "
1576 . "Net::Twitter v$Net::Twitter::VERSION. "
1578 . JSON::Any::handler()
1579 . ". See details at http://twirssi.com/" );
1582 Irssi::command_bind(
1585 "/twitter_follow <username>",
1587 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1590 Irssi::command_bind(
1593 "/twitter_unfriend <username>",
1595 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1598 Irssi::command_bind(
1599 "twitter_device_updates",
1601 "/twitter_device_updates none|im|sms",
1602 "update_delivery_device",
1603 sub { ¬ice("Device updated to $_[0]"); }
1606 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1608 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1609 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1611 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1613 my $file = Irssi::settings_get_str("twirssi_replies_store");
1614 if ( $file and -r $file ) {
1615 if ( open( JSON, $file ) ) {
1620 my $ref = JSON::Any->jsonToObj($json);
1622 my $num = keys %{ $id_map{__indexes} };
1623 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1624 $num, ( $num == 1 ? "" : "s" ) );
1628 ¬ice("Failed to load old replies from $file: $!");
1632 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1633 ¬ice("Loading WWW::Shorten::$provider...");
1634 eval "use WWW::Shorten::$provider;";
1638 "Failed to load WWW::Shorten::$provider - either clear",
1639 "short_url_provider or install the CPAN module"
1644 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1645 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1653 ->print( "Create a window named "
1654 . Irssi::settings_get_str('twitter_window')
1655 . " or change the value of twitter_window. Then, reload twirssi." );
1658 # vim: set sts=4 expandtab: