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 binmode 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;
1167 if ( $new_last_poll >= $last_poll ) {
1170 print "Impossible! ",
1171 "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1173 undef $new_last_poll;
1177 my ( $f, $t ) = split ' ', $_;
1178 $nicks{$f} = $friends{$f} = $t;
1181 if ($new_last_poll) {
1182 print "new last_poll = $new_last_poll" if &debug;
1183 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1185 print "First call, not printing updates" if &debug;
1187 foreach my $line (@lines) {
1188 $window->printformat(
1190 "twirssi_" . $line->[1],
1191 @$line[ 2 .. $#$line - 1 ],
1192 &hilight( $line->[-1] )
1199 or warn "Failed to remove $filename: $!"
1202 # commit the pending cache lines to the actual cache, now that
1203 # we've printed our output
1204 %tweet_cache = ( %tweet_cache, %new_cache );
1206 # keep enough cached tweets, to make sure we don't show duplicates.
1207 foreach ( keys %tweet_cache ) {
1208 next if $tweet_cache{$_} >= $last_poll - 3600;
1209 delete $tweet_cache{$_};
1211 $last_poll = $new_last_poll;
1216 Irssi::settings_get_str("twirssi_replies_store") )
1218 if ( open JSON, ">$file" ) {
1219 print JSON JSON::Any->objToJson( \%id_map );
1222 &ccrap("Failed to write replies to $file: $!");
1233 if ( $attempt < 24 ) {
1234 Irssi::timeout_add_once( 5000, 'monitor_child',
1235 [ $filename, $attempt + 1 ] );
1237 print "Giving up on polling $filename" if &debug;
1238 unlink $filename unless &debug;
1240 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1243 my @time = localtime($last_poll);
1244 if ( time - $last_poll < 24 * 60 * 60 ) {
1245 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1247 $since = scalar localtime($last_poll);
1250 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1255 q{ .--./ / | _.---.| },
1267 if ( time - $last_poll < 600 ) {
1268 &ccrap("Haven't been able to get updated tweets since $since");
1274 return Irssi::settings_get_bool("twirssi_debug");
1278 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1282 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1288 if ( Irssi::settings_get_bool("tweet_to_away")
1290 and $data !~ /^[dD] / )
1293 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1295 $server->send_raw("away :$data");
1298 &ccrap( "Can't find bitlbee server.",
1299 "Update bitlbee_server or disable tweet_to_away" );
1309 my $noalert = shift;
1311 if ( length $data > 140 ) {
1312 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1320 sub valid_username {
1321 my $username = shift;
1323 $username = &normalize_username($username);
1325 unless ( exists $twits{$username} ) {
1326 ¬ice("Unknown username $username");
1336 ¬ice("Not logged in! Use /twitter_login username pass!");
1344 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1347 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1348 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1349 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1351 { # /twitter_reply gets a nick:num
1353 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1354 sort { $nicks{$b} <=> $nicks{$a} }
1356 keys %{ $id_map{__indexes} };
1359 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1360 { # /twitter_unfriend gets a nick
1362 push @$complist, grep /^\Q$word/i,
1363 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1366 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1368 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1369 my $prefix = $word =~ s/^@//;
1370 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1371 push @$complist, grep /^\Q$word/i,
1372 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1373 @$complist = map { "\@$_" } @$complist if $prefix;
1377 sub event_send_text {
1378 my ( $line, $server, $win ) = @_;
1379 my $awin = Irssi::active_win();
1381 # if the window where we got our text was the twitter window, and the user
1382 # wants to be lazy, tweet away!
1383 if ( ( $awin->get_active_name() eq $window->{name} )
1384 and Irssi::settings_get_bool("tweet_window_input") )
1386 &cmd_tweet( $line, $server, $win );
1391 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1392 return $poll if $poll >= 60;
1399 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1400 my $c = Irssi::settings_get_str("twirssi_nick_color");
1401 $c = $irssi_to_mirc_colors{$c};
1402 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1404 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1405 my $c = Irssi::settings_get_str("twirssi_topic_color");
1406 $c = $irssi_to_mirc_colors{$c};
1407 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1409 $text =~ s/[\n\r]/ /g;
1417 my $provider = Irssi::settings_get_str("short_url_provider");
1420 Irssi::settings_get_bool("twirssi_always_shorten")
1421 or &too_long( $data, 1 )
1427 if ( $provider eq 'Bitly' ) {
1428 @args[ 1, 2 ] = split ',',
1429 Irssi::settings_get_str("short_url_args"), 2;
1430 unless ( @args == 3 ) {
1432 "WWW::Shorten::Bitly requires a username and API key.",
1433 "Set short_url_args to username,API_key or change your",
1434 "short_url_provider."
1440 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1443 my $short = makeashorterlink(@args);
1445 $data =~ s/\Q$url/$short/g;
1447 ¬ice("Failed to shorten $url!");
1453 return decode "utf8", $data;
1456 sub normalize_username {
1459 my ( $username, $service ) = split /\@/, $user, 2;
1461 $service = ucfirst lc $service;
1464 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1465 unless ( exists $twits{"$username\@$service"} ) {
1467 foreach my $t ( sort keys %twits ) {
1468 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1474 ¬ice("Can't find a logged in user '$user'");
1479 return "$username\@$service";
1482 Irssi::signal_add( "send text", "event_send_text" );
1484 Irssi::theme_register(
1486 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1487 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1488 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1489 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1490 'twirssi_error', 'ERROR: $0',
1494 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1495 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1496 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1497 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1498 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1499 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1500 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1501 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1502 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1503 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1504 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1505 'RT $n: "$t" ${-- $c$}' );
1506 Irssi::settings_add_str( "twirssi", "twirssi_location",
1507 ".irssi/scripts/twirssi.pl" );
1508 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1509 ".irssi/scripts/twirssi.json" );
1511 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1513 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1514 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1515 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1516 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1517 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1518 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1519 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1520 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1521 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1522 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1523 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1524 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1525 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1526 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl", 0 );
1528 $last_poll = time - &get_poll_time;
1529 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1532 ->print( "Couldn't find a window named '"
1533 . Irssi::settings_get_str('twitter_window')
1534 . "', trying to create it." );
1536 Irssi::Windowitem::window_create(
1537 Irssi::settings_get_str('twitter_window'), 1 );
1538 $window->set_name( Irssi::settings_get_str('twitter_window') );
1542 Irssi::command_bind( "dm", "cmd_direct" );
1543 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1544 Irssi::command_bind( "tweet", "cmd_tweet" );
1545 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1546 Irssi::command_bind( "retweet", "cmd_retweet" );
1547 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1548 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1549 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1550 Irssi::command_bind( "twitter_login", "cmd_login" );
1551 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1552 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1553 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1554 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1555 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1556 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1557 Irssi::command_bind( "twitter_updates", "get_updates" );
1558 Irssi::command_bind( "bitlbee_away", "update_away" );
1559 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1560 Irssi::command_bind( "reply", "cmd_reply" );
1561 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1563 Irssi::command_bind(
1566 print "twits: ", join ", ",
1567 map { "u: $_->{username}\@" . ref($_) } values %twits;
1568 print "selected: $user\@$defservice";
1569 print "friends: ", join ", ", sort keys %friends;
1570 print "nicks: ", join ", ", sort keys %nicks;
1571 print "searches: ", Dumper \%{ $id_map{__searches} };
1572 print "last poll: $last_poll";
1573 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1574 print DUMP Dumper \%tweet_cache;
1576 print "cache written out to /tmp/twirssi.cache.txt";
1580 Irssi::command_bind(
1583 ¬ice("Twirssi v$VERSION (r$REV); "
1584 . "Net::Twitter v$Net::Twitter::VERSION. "
1586 . JSON::Any::handler()
1587 . ". See details at http://twirssi.com/" );
1590 Irssi::command_bind(
1593 "/twitter_follow <username>",
1595 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1598 Irssi::command_bind(
1601 "/twitter_unfriend <username>",
1603 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1606 Irssi::command_bind(
1607 "twitter_device_updates",
1609 "/twitter_device_updates none|im|sms",
1610 "update_delivery_device",
1611 sub { ¬ice("Device updated to $_[0]"); }
1614 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1616 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1617 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1619 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1621 my $file = Irssi::settings_get_str("twirssi_replies_store");
1622 if ( $file and -r $file ) {
1623 if ( open( JSON, $file ) ) {
1628 my $ref = JSON::Any->jsonToObj($json);
1630 my $num = keys %{ $id_map{__indexes} };
1631 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1632 $num, ( $num == 1 ? "" : "s" ) );
1636 ¬ice("Failed to load old replies from $file: $!");
1640 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1641 ¬ice("Loading WWW::Shorten::$provider...");
1642 eval "use WWW::Shorten::$provider;";
1646 "Failed to load WWW::Shorten::$provider - either clear",
1647 "short_url_provider or install the CPAN module"
1652 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1653 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1661 ->print( "Create a window named "
1662 . Irssi::settings_get_str('twitter_window')
1663 . " or change the value of twitter_window. Then, reload twirssi." );
1666 # vim: set sts=4 expandtab: