10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
14 $VERSION = "2.2.6beta";
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;
43 my %irssi_to_mirc_colors = (
63 my ( $data, $server, $win ) = @_;
65 return unless &logged_in($twit);
67 my ( $target, $text ) = split ' ', $data, 2;
68 unless ( $target and $text ) {
69 ¬ice("Usage: /dm <nick> <message>");
73 &cmd_direct_as( "$user $data", $server, $win );
77 my ( $data, $server, $win ) = @_;
79 return unless &logged_in($twit);
81 my ( $username, $target, $text ) = split ' ', $data, 3;
82 unless ( $username and $target and $text ) {
83 ¬ice("Usage: /dm_as <username> <nick> <message>");
87 return unless $username = &valid_username($username);
90 if ( $twits{$username}
91 ->new_direct_message( { user => $target, text => $text } ) )
93 ¬ice("DM sent to $target");
94 $nicks{$target} = time;
98 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
99 $error = $error->{error};
101 die $error if $error;
102 ¬ice("DM to $target failed");
107 ¬ice("DM caused an error: $@");
113 my ( $data, $server, $win ) = @_;
115 return unless &logged_in($twit);
117 $data =~ s/^\s+|\s+$//;
119 ¬ice("Usage: /retweet <nick[:num]> [comment]");
123 my ( $id, $data ) = split ' ', $data, 2;
125 &cmd_retweet_as( "$user $id $data", $server, $win );
129 my ( $data, $server, $win ) = @_;
131 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
132 ¬ice("twirssi_track_replies is required in order to reteet.");
136 return unless &logged_in($twit);
138 $data =~ s/^\s+|\s+$//;
139 my ( $username, $id, $data ) = split ' ', $data, 3;
142 ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
146 return unless $username = &valid_username($username);
149 $id =~ s/[^\w\d\-:]+//g;
150 ( $nick, $id ) = split /:/, $id;
151 unless ( exists $id_map{ lc $nick } ) {
152 ¬ice("Can't find a tweet from $nick to retweet!");
156 $id = $id_map{__indexes}{$nick} unless $id;
157 unless ( $id_map{ lc $nick }[$id] ) {
158 ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
162 unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
163 ¬ice("The text of this tweet isn't saved, sorry!");
167 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
168 my $text = Irssi::settings_get_str("twirssi_retweet_format");
169 $text =~ s/\$n/\@$nick/g;
171 $text =~ s/\${|\$}//g;
172 $text =~ s/\$c/$data/;
174 $text =~ s/\${.*?\$}//;
176 $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
178 $data = &shorten($text);
180 return if &too_long($data);
185 $twits{$username}->update(
189 # in_reply_to_status_id => $id_map{ lc $nick }[$id]
194 ¬ice("Update failed");
198 return unless $success;
201 ¬ice("Update caused an error: $@. Aborted");
205 foreach ( $data =~ /@([-\w]+)/ ) {
209 ¬ice("Retweet sent");
213 my ( $data, $server, $win ) = @_;
215 return unless &logged_in($twit);
217 $data =~ s/^\s+|\s+$//;
219 ¬ice("Usage: /tweet <update>");
223 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
227 my ( $data, $server, $win ) = @_;
229 return unless &logged_in($twit);
231 $data =~ s/^\s+|\s+$//;
232 $data =~ s/\s\s+/ /g;
233 my ( $username, $data ) = split ' ', $data, 2;
235 unless ( $username and $data ) {
236 ¬ice("Usage: /tweet_as <username> <update>");
240 return unless $username = &valid_username($username);
242 $data = &shorten($data);
244 return if &too_long($data);
248 unless ( $twits{$username}->update($data) )
250 ¬ice("Update failed");
254 return unless $success;
257 ¬ice("Update caused an error: $@. Aborted.");
261 foreach ( $data =~ /@([-\w]+)/ ) {
265 my $away = &update_away($data);
267 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
271 my ( $data, $server, $win ) = @_;
273 return unless &logged_in($twit);
275 $data =~ s/^\s+|\s+$//;
277 ¬ice("Usage: /reply <nick[:num]> <update>");
281 my ( $id, $data ) = split ' ', $data, 2;
282 unless ( $id and $data ) {
283 ¬ice("Usage: /reply <nick[:num]> <update>");
287 &cmd_reply_as( "$user $id $data", $server, $win );
291 my ( $data, $server, $win ) = @_;
293 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
294 ¬ice("twirssi_track_replies is required in order to reply to "
295 . "specific tweets. Either enable it, or just use /tweet "
296 . "\@username <text>." );
300 return unless &logged_in($twit);
302 $data =~ s/^\s+|\s+$//;
303 my ( $username, $id, $data ) = split ' ', $data, 3;
305 unless ( $username and $data ) {
306 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
310 return unless $username = &valid_username($username);
313 $id =~ s/[^\w\d\-:]+//g;
314 ( $nick, $id ) = split /:/, $id;
315 unless ( exists $id_map{ lc $nick } ) {
316 ¬ice("Can't find a tweet from $nick to reply to!");
320 $id = $id_map{__indexes}{$nick} unless $id;
321 unless ( $id_map{ lc $nick }[$id] ) {
322 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
326 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
328 # remove any @nick at the beginning of the reply, as we'll add it anyway
329 $data =~ s/^\s*\@?$nick\s*//;
330 $data = "\@$nick " . $data;
333 $data = &shorten($data);
335 return if &too_long($data);
340 $twits{$username}->update(
343 in_reply_to_status_id => $id_map{ lc $nick }[$id]
348 ¬ice("Update failed");
352 return unless $success;
355 ¬ice("Update caused an error: $@. Aborted");
359 foreach ( $data =~ /@([-\w]+)/ ) {
363 my $away = &update_away($data);
365 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
369 my ( $usage_str, $api_name, $post_ref ) = @_;
372 my ( $data, $server, $win ) = @_;
374 return unless &logged_in($twit);
376 $data =~ s/^\s+|\s+$//;
378 ¬ice("Usage: $usage_str");
384 unless ( $twit->$api_name($data) )
386 ¬ice("$api_name failed");
390 return unless $success;
393 ¬ice("$api_name caused an error. Aborted.");
397 &$post_ref($data) if $post_ref;
402 my ( $data, $server, $win ) = @_;
404 $data =~ s/^\s+|\s+$//g;
405 $data = &normalize_username($data);
406 if ( exists $twits{$data} ) {
407 ¬ice("Switching to $data");
408 $twit = $twits{$data};
409 if ( $data =~ /(.*)\@(.*)/ ) {
413 ¬ice("Couldn't figure out what service '$data' is on");
416 ¬ice("Unknown user $data");
421 my ( $data, $server, $win ) = @_;
423 $data =~ s/^\s+|\s+$//g;
424 $data = $user unless $data;
425 return unless $data = &valid_username($data);
427 ¬ice("Logging out $data...");
428 $twits{$data}->end_session();
429 delete $twits{$data};
432 &cmd_switch( ( keys %twits )[0], $server, $win );
434 Irssi::timeout_remove($poll) if $poll;
440 my ( $data, $server, $win ) = @_;
443 ( $user, $pass ) = split ' ', $data, 2;
444 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
445 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
447 my @user = split /\s*,\s*/, $autouser;
448 my @pass = split /\s*,\s*/, $autopass;
450 # if a password ends with a '\', it was meant to escape the comma, and
451 # it should be concatinated with the next one
455 while ( $p =~ /\\$/ and @pass ) {
456 $p .= "," . shift @pass;
461 if ( @user != @unescaped ) {
462 ¬ice("Number of usernames doesn't match "
463 . "the number of passwords - auto-login failed" );
466 while ( @user and @unescaped ) {
468 $p = shift @unescaped;
474 ¬ice("/twitter_login requires either a username and password "
475 . "or twitter_usernames and twitter_passwords to be set." );
479 %friends = %nicks = ();
482 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
483 ( $user, $service ) = ( $1, $2 );
485 $service = Irssi::settings_get_str("twirssi_default_service");
487 $defservice = $service = ucfirst lc $service;
489 eval "use Net::$service";
492 "Failed to load Net::$service when trying to log in as $user: $@");
496 $twit = "Net::$service"->new(
500 ssl => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
504 ¬ice("Failed to create Net::$service object! Aborting.");
508 if ( my $timeout = Irssi::settings_get_int("twitter_timeout")
509 and $twit->can('ua') )
511 $twit->ua->timeout($timeout);
514 unless ( $twit->verify_credentials() ) {
515 ¬ice("Login as $user\@$service failed");
518 &cmd_switch( ( keys %twits )[0], $server, $win );
524 my $rate_limit = $twit->rate_limit_status();
525 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
527 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
533 $twits{"$user\@$service"} = $twit;
534 Irssi::timeout_remove($poll) if $poll;
535 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
536 ¬ice("Logged in as $user\@$service, loading friends list...");
538 ¬ice( "loaded friends: ", scalar keys %friends );
539 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
540 Irssi::settings_set_bool( "twirssi_first_run", 0 );
541 unless ( exists $friends{twirssi} ) {
542 ¬ice("Welcome to twirssi!"
543 . " Perhaps you should add \@twirssi to your friends list,"
544 . " so you can be notified when a new version is release?"
545 . " Just type /twitter_follow twirssi." );
552 ¬ice("Login failed");
553 if ( not Irssi::settings_get_bool("twirssi_avoid_ssl") ) {
555 "It's possible you're missing one of the modules required for "
556 . "SSL logins. Try setting twirssi_avoid_ssl to on. See "
557 . "http://cpansearch.perl.org/src/GAAS/libwww-perl-5.831/README.SSL "
558 . "for the detailed requirements." );
564 my ( $data, $server, $win ) = @_;
566 unless ( $twit and $twit->can('search') ) {
567 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
568 . "doesn't support searches." );
572 $data =~ s/^\s+|\s+$//;
576 ¬ice("Usage: /twitter_subscribe <topic>");
580 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
581 ¬ice("Already had a subscription for '$data'");
585 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
586 ¬ice("Added subscription for '$data'");
590 my ( $data, $server, $win ) = @_;
592 unless ( $twit and $twit->can('search') ) {
593 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
594 . "doesn't support searches." );
597 $data =~ s/^\s+|\s+$//;
601 ¬ice("Usage: /twitter_unsubscribe <topic>");
605 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
606 ¬ice("No subscription found for '$data'");
610 delete $id_map{__searches}{"$user\@$defservice"}{$data};
611 ¬ice("Removed subscription for '$data'");
614 sub cmd_list_search {
615 my ( $data, $server, $win ) = @_;
618 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
620 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
621 $topics = $topics ? "$topics, $topic" : $topic;
625 ¬ice("Search subscriptions for \@$suser: $topics");
630 ¬ice("No search subscriptions set up");
635 my ( $data, $server, $win ) = @_;
637 my $loc = Irssi::settings_get_str("twirssi_location");
640 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
646 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
647 eval { use Digest::MD5; };
651 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
656 $md5 = get("http://twirssi.com/md5sum");
660 ¬ice("Failed to download md5sum from peeron! Aborting.");
664 unless ( open( CUR, $loc ) ) {
666 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
671 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
674 if ( $cur_md5 eq $md5 ) {
675 ¬ice("Current twirssi seems to be up to date.");
681 Irssi::settings_get_bool("twirssi_upgrade_beta")
682 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
683 : "http://twirssi.com/twirssi.pl";
684 ¬ice("Downloading twirssi from $URL");
685 LWP::Simple::getstore( $URL, "$loc.upgrade" );
687 unless ( -s "$loc.upgrade" ) {
688 ¬ice("Failed to save $loc.upgrade."
689 . " Check that /set twirssi_location is set to the correct location."
694 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
695 unless ( open( NEW, "$loc.upgrade" ) ) {
696 ¬ice("Failed to read $loc.upgrade."
697 . " Check that /set twirssi_location is set to the correct location."
702 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
705 if ( $new_md5 ne $md5 ) {
706 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
711 rename $loc, "$loc.backup"
712 or ¬ice("Failed to back up $loc: $!. Aborting")
714 rename "$loc.upgrade", $loc
715 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
718 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
719 if ( -e "$dir/autorun/$file" ) {
720 ¬ice("Updating $dir/autorun/$file");
721 unlink "$dir/autorun/$file"
722 or ¬ice("Failed to remove old $file from autorun: $!");
723 symlink "../$file", "$dir/autorun/$file"
724 or ¬ice("Failed to create symlink in autorun directory: $!");
727 ¬ice("Download complete. Reload twirssi with /script load $file");
737 print $fh "type:debug Loading friends page $page...\n"
738 if ( $fh and &debug );
739 my $friends = $twit->friends( { page => $page } );
740 last unless $friends;
741 $new_friends{ $_->{screen_name} } = time foreach @$friends;
743 last if @$friends == 0 or $page == 10;
748 print $fh "type:debug Error during friends list update. Aborted.\n";
752 my ( $added, $removed ) = ( 0, 0 );
753 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
754 foreach ( keys %new_friends ) {
755 next if exists $friends{$_};
760 print $fh "type:debug Scanning for removed friends...\n"
761 if ( $fh and &debug );
762 foreach ( keys %friends ) {
763 next if exists $new_friends{$_};
768 return ( $added, $removed );
772 print scalar localtime, " - get_updates starting" if &debug;
775 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
778 ->print( "Can't find a window named '"
779 . Irssi::settings_get_str('twitter_window')
780 . "'. Create it or change the value of twitter_window" );
783 return unless &logged_in($twit);
785 my ( $fh, $filename ) = File::Temp::tempfile();
786 binmode( $fh, ":utf8" );
789 if ($child_pid) { # parent
790 Irssi::timeout_add_once( 5000, 'monitor_child',
791 [ "$filename.done", 0 ] );
792 Irssi::pidwait_add($child_pid);
793 } elsif ( defined $child_pid ) { # child
802 foreach ( keys %twits ) {
803 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
806 print $fh "__friends__\n";
808 time - $last_friends_poll >
809 Irssi::settings_get_int('twitter_friends_poll') )
811 print $fh "__updated ", time, "\n";
812 my ( $added, $removed ) = &load_friends($fh);
813 if ( $added + $removed ) {
814 print $fh "type:debug %R***%n Friends list updated: ",
816 sprintf( "%d added", $added ),
817 sprintf( "%d removed", $removed ) ),
822 foreach ( sort keys %friends ) {
823 print $fh "$_ $friends{$_}\n";
827 print $fh "type:debug Update encountered errors. Aborted\n";
828 print $fh "-- $last_poll";
830 print $fh "-- $new_poll";
833 rename $filename, "$filename.done";
836 &ccrap("Failed to fork for updating: $!");
838 print scalar localtime, " - get_updates ends" if &debug;
842 my ( $fh, $username, $obj, $cache ) = @_;
844 my $rate_limit = $obj->rate_limit_status();
845 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
846 ¬ice("Rate limit exceeded for $username");
850 print scalar localtime, " - Polling for updates for $username" if &debug;
854 if ( $id_map{__last_id}{$username}{timeline} )
856 $tweets = $obj->friends_timeline( { count => 100 } );
858 $tweets = $obj->friends_timeline();
863 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
864 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
868 unless ( ref $tweets ) {
869 if ( $obj->can("get_error") ) {
870 my $error = "Unknown error";
871 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
872 unless ($@) { $error = $obj->get_error() }
874 "type:debug API Error during friends_timeline call: Aborted\n";
875 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
879 "type:debug API Error during friends_timeline call. Aborted.\n";
884 foreach my $t ( reverse @$tweets ) {
885 my $text = decode_entities( $t->{text} );
886 $text =~ s/[\n\r]/ /g;
888 if ( Irssi::settings_get_bool("show_reply_context")
889 and $t->{in_reply_to_screen_name} ne $username
890 and $t->{in_reply_to_screen_name}
891 and not exists $friends{ $t->{in_reply_to_screen_name} } )
893 $nicks{ $t->{in_reply_to_screen_name} } = time;
895 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
897 $cache->{ $t->{in_reply_to_status_id} } =
898 $obj->show_status( $t->{in_reply_to_status_id} );
902 $context = $cache->{ $t->{in_reply_to_status_id} };
905 my $ctext = decode_entities( $context->{text} );
906 $ctext =~ s/[\n\r]/ /g;
907 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
909 " -- http://twitter.com/$context->{user}{screen_name}"
910 . "/status/$context->{id}";
912 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
913 $context->{id}, $username,
914 $context->{user}{screen_name}, $ctext;
919 if $t->{user}{screen_name} eq $username
920 and not Irssi::settings_get_bool("show_own_tweets");
921 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
922 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
923 . "/status/$t->{id}";
925 printf $fh "id:%u account:%s nick:%s type:%s %s\n",
926 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
927 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
929 printf $fh "id:%u account:%s type:last_id timeline\n",
930 $new_poll_id, $username;
932 print scalar localtime, " - Polling for replies since ",
933 $id_map{__last_id}{$username}{reply}
937 if ( $id_map{__last_id}{$username}{reply} )
939 $tweets = $obj->replies(
940 { since_id => $id_map{__last_id}{$username}{reply} } )
943 $tweets = $obj->replies() || [];
948 print $fh "type:debug Error during replies call. Aborted.\n";
952 foreach my $t ( reverse @$tweets ) {
954 if exists $friends{ $t->{user}{screen_name} };
956 my $text = decode_entities( $t->{text} );
957 $text =~ s/[\n\r]/ /g;
958 if ( $t->{truncated} ) {
959 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
960 . "/status/$t->{id}";
962 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
963 $t->{id}, $username, $t->{user}{screen_name}, $text;
964 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
966 printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
968 print scalar localtime, " - Polling for DMs" if &debug;
971 if ( $id_map{__last_id}{$username}{dm} )
973 $tweets = $obj->direct_messages(
974 { since_id => $id_map{__last_id}{$username}{dm} } )
977 $tweets = $obj->direct_messages() || [];
982 print $fh "type:debug Error during direct_messages call. Aborted.\n";
986 foreach my $t ( reverse @$tweets ) {
987 my $text = decode_entities( $t->{text} );
988 $text =~ s/[\n\r]/ /g;
989 printf $fh "id:%u account:%s nick:%s type:dm %s\n",
990 $t->{id}, $username, $t->{sender_screen_name}, $text;
991 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
993 printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
995 print scalar localtime, " - Polling for subscriptions" if &debug;
996 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
998 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
999 print $fh "type:debug searching for $topic since ",
1000 "$id_map{__searches}{$username}{$topic}\n";
1002 $search = $obj->search(
1005 since_id => $id_map{__searches}{$username}{$topic}
1012 "type:debug Error during search($topic) call. Aborted.\n";
1016 unless ( $search->{max_id} ) {
1017 print $fh "type:debug Invalid search results when searching",
1018 " for $topic. Aborted.\n";
1022 $id_map{__searches}{$username}{$topic} = $search->{max_id};
1023 printf $fh "id:%u account:%s type:searchid topic:%s\n",
1024 $search->{max_id}, $username, $topic;
1026 foreach my $t ( reverse @{ $search->{results} } ) {
1027 my $text = decode_entities( $t->{text} );
1028 $text =~ s/[\n\r]/ /g;
1029 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
1030 $t->{id}, $username, $t->{from_user}, $topic, $text;
1031 $new_poll_id = $t->{id}
1033 or $t->{id} < $new_poll_id;
1038 print scalar localtime, " - Done" if &debug;
1045 my $filename = $data->[0];
1046 my $attempt = $data->[1];
1048 print scalar localtime, " - checking child log at $filename ($attempt)"
1050 my ($new_last_poll);
1052 # first time we run we don't want to print out *everything*, so we just
1055 if ( open FILE, $filename ) {
1056 binmode FILE, ":utf8";
1060 last if /^__friends__/;
1061 unless (/\n$/) { # skip partial lines
1062 # print "Skipping partial line: $_" if &debug;
1069 foreach my $key (qw/id account nick type topic/) {
1070 if (s/^$key:(\S+)\s*//) {
1075 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1076 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1080 $new_cache{ $meta{id} } = time;
1082 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1088 $meta{account} =~ s/\@(\w+)$//;
1089 $meta{service} = $1;
1091 lc $meta{service} eq
1092 lc Irssi::settings_get_str("twirssi_default_service") )
1094 $account = "$meta{account}: "
1095 if lc "$meta{account}\@$meta{service}" ne lc
1096 "$user\@$defservice";
1098 $account = "$meta{account}\@$meta{service}: ";
1102 if ( $meta{type} ne 'dm'
1103 and Irssi::settings_get_bool("twirssi_track_replies")
1107 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1108 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1109 $id_map{__indexes}{ $meta{nick} } = $marker;
1110 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1111 $marker = ":$marker";
1115 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1116 my $nick = "\@$meta{account}";
1117 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1118 and Irssi::settings_get_bool("twirssi_hilights") )
1120 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1121 $hilight = MSGLEVEL_HILIGHT;
1124 if ( $meta{type} =~ /tweet|reply/ ) {
1127 ( MSGLEVEL_PUBLIC | $hilight ),
1128 $meta{type}, $account, $meta{nick}, $marker, $_
1130 } elsif ( $meta{type} eq 'search' ) {
1133 ( MSGLEVEL_PUBLIC | $hilight ),
1134 $meta{type}, $account, $meta{topic},
1135 $meta{nick}, $marker, $_
1138 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1140 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1142 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1145 } elsif ( $meta{type} eq 'dm' ) {
1148 ( MSGLEVEL_MSGS | $hilight ),
1149 $meta{type}, $account, $meta{nick}, $_
1151 } elsif ( $meta{type} eq 'searchid' ) {
1152 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1155 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1157 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1159 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1162 print "Search '$meta{topic}' returned invalid id $meta{id}";
1164 } elsif ( $meta{type} eq 'last_id' ) {
1165 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1167 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1169 } elsif ( $meta{type} eq 'error' ) {
1170 push @lines, [ MSGLEVEL_MSGS, $_ ];
1171 } elsif ( $meta{type} eq 'debug' ) {
1172 print "$_" if &debug,;
1174 print "Unknown line type $meta{type}: $_" if &debug,;
1180 if (/^__updated (\d+)$/) {
1181 $last_friends_poll = $1;
1182 print "Friend list updated" if &debug;
1187 $new_last_poll = $1;
1188 if ( $new_last_poll >= $last_poll ) {
1191 print "Impossible! ",
1192 "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1194 undef $new_last_poll;
1198 my ( $f, $t ) = split ' ', $_;
1199 $nicks{$f} = $friends{$f} = $t;
1202 if ($new_last_poll) {
1203 print "new last_poll = $new_last_poll" if &debug;
1204 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1206 print "First call, not printing updates" if &debug;
1208 foreach my $line (@lines) {
1209 $window->printformat(
1211 "twirssi_" . $line->[1],
1212 @$line[ 2 .. $#$line - 1 ],
1213 &hilight( $line->[-1] )
1220 or warn "Failed to remove $filename: $!"
1223 # commit the pending cache lines to the actual cache, now that
1224 # we've printed our output
1225 %tweet_cache = ( %tweet_cache, %new_cache );
1227 # keep enough cached tweets, to make sure we don't show duplicates.
1228 foreach ( keys %tweet_cache ) {
1229 next if $tweet_cache{$_} >= $last_poll - 3600;
1230 delete $tweet_cache{$_};
1232 $last_poll = $new_last_poll;
1234 # make sure the pid is removed from the waitpid list
1235 Irssi::pidwait_remove($child_pid);
1240 Irssi::settings_get_str("twirssi_replies_store") )
1242 if ( open JSON, ">$file" ) {
1243 print JSON JSON::Any->objToJson( \%id_map );
1246 &ccrap("Failed to write replies to $file: $!");
1257 if ( $attempt < 24 ) {
1258 Irssi::timeout_add_once( 5000, 'monitor_child',
1259 [ $filename, $attempt + 1 ] );
1261 print "Giving up on polling $filename" if &debug;
1262 unlink $filename unless &debug;
1264 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1267 my @time = localtime($last_poll);
1268 if ( time - $last_poll < 24 * 60 * 60 ) {
1269 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1271 $since = scalar localtime($last_poll);
1274 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1279 q{ .--./ / | _.---.| },
1291 if ( time - $last_poll < 600 ) {
1292 &ccrap("Haven't been able to get updated tweets since $since");
1298 return Irssi::settings_get_bool("twirssi_debug");
1302 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1306 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1312 if ( Irssi::settings_get_bool("tweet_to_away")
1314 and $data !~ /^[dD] / )
1317 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1319 $server->send_raw("away :$data");
1322 &ccrap( "Can't find bitlbee server.",
1323 "Update bitlbee_server or disable tweet_to_away" );
1333 my $noalert = shift;
1335 if ( length $data > 140 ) {
1336 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1344 sub valid_username {
1345 my $username = shift;
1347 $username = &normalize_username($username);
1349 unless ( exists $twits{$username} ) {
1350 ¬ice("Unknown username $username");
1360 ¬ice("Not logged in! Use /twitter_login username pass!");
1368 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1371 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1372 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1373 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1375 { # /twitter_reply gets a nick:num
1377 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1378 sort { $nicks{$b} <=> $nicks{$a} }
1380 keys %{ $id_map{__indexes} };
1383 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1384 { # /twitter_unfriend gets a nick
1386 push @$complist, grep /^\Q$word/i,
1387 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1390 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1392 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1393 my $prefix = $word =~ s/^@//;
1394 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1395 push @$complist, grep /^\Q$word/i,
1396 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1397 @$complist = map { "\@$_" } @$complist if $prefix;
1401 sub event_send_text {
1402 my ( $line, $server, $win ) = @_;
1403 my $awin = Irssi::active_win();
1405 # if the window where we got our text was the twitter window, and the user
1406 # wants to be lazy, tweet away!
1407 if ( ( $awin->get_active_name() eq $window->{name} )
1408 and Irssi::settings_get_bool("tweet_window_input") )
1410 &cmd_tweet( $line, $server, $win );
1415 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1416 return $poll if $poll >= 60;
1423 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1424 my $c = Irssi::settings_get_str("twirssi_nick_color");
1425 $c = $irssi_to_mirc_colors{$c};
1426 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1428 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1429 my $c = Irssi::settings_get_str("twirssi_topic_color");
1430 $c = $irssi_to_mirc_colors{$c};
1431 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1433 $text =~ s/[\n\r]/ /g;
1441 my $provider = Irssi::settings_get_str("short_url_provider");
1444 Irssi::settings_get_bool("twirssi_always_shorten")
1445 or &too_long( $data, 1 )
1451 if ( $provider eq 'Bitly' ) {
1452 @args[ 1, 2 ] = split ',',
1453 Irssi::settings_get_str("short_url_args"), 2;
1454 unless ( @args == 3 ) {
1456 "WWW::Shorten::Bitly requires a username and API key.",
1457 "Set short_url_args to username,API_key or change your",
1458 "short_url_provider."
1464 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1467 my $short = makeashorterlink(@args);
1469 $data =~ s/\Q$url/$short/g;
1471 ¬ice("Failed to shorten $url!");
1477 return decode "utf8", $data;
1480 sub normalize_username {
1483 my ( $username, $service ) = split /\@/, $user, 2;
1485 $service = ucfirst lc $service;
1488 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1489 unless ( exists $twits{"$username\@$service"} ) {
1491 foreach my $t ( sort keys %twits ) {
1492 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1498 ¬ice("Can't find a logged in user '$user'");
1503 return "$username\@$service";
1506 Irssi::signal_add( "send text", "event_send_text" );
1508 Irssi::theme_register(
1510 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1511 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1512 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1513 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1514 'twirssi_error', 'ERROR: $0',
1518 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1519 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1520 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1521 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1522 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1523 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1524 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1525 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1526 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1527 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1528 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1529 'RT $n: "$t" ${-- $c$}' );
1530 Irssi::settings_add_str( "twirssi", "twirssi_location",
1531 ".irssi/scripts/twirssi.pl" );
1532 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1533 ".irssi/scripts/twirssi.json" );
1535 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1536 Irssi::settings_add_int( "twirssi", "twitter_timeout", 30 );
1538 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1539 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1540 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1541 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1542 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1543 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1544 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1545 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1546 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1547 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1548 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1549 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1550 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1551 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl", 0 );
1553 $last_poll = time - &get_poll_time;
1554 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1557 ->print( "Couldn't find a window named '"
1558 . Irssi::settings_get_str('twitter_window')
1559 . "', trying to create it." );
1561 Irssi::Windowitem::window_create(
1562 Irssi::settings_get_str('twitter_window'), 1 );
1563 $window->set_name( Irssi::settings_get_str('twitter_window') );
1567 Irssi::command_bind( "dm", "cmd_direct" );
1568 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1569 Irssi::command_bind( "tweet", "cmd_tweet" );
1570 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1571 Irssi::command_bind( "retweet", "cmd_retweet" );
1572 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1573 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1574 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1575 Irssi::command_bind( "twitter_login", "cmd_login" );
1576 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1577 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1578 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1579 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1580 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1581 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1582 Irssi::command_bind( "twitter_updates", "get_updates" );
1583 Irssi::command_bind( "bitlbee_away", "update_away" );
1584 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1585 Irssi::command_bind( "reply", "cmd_reply" );
1586 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1588 Irssi::command_bind(
1591 print "twits: ", join ", ",
1592 map { "u: $_->{username}\@" . ref($_) } values %twits;
1593 print "selected: $user\@$defservice";
1594 print "friends: ", join ", ", sort keys %friends;
1595 print "nicks: ", join ", ", sort keys %nicks;
1596 print "searches: ", Dumper \%{ $id_map{__searches} };
1597 print "last poll: $last_poll";
1598 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1599 print DUMP Dumper \%tweet_cache;
1601 print "cache written out to /tmp/twirssi.cache.txt";
1605 Irssi::command_bind(
1609 "Twirssi v$VERSION (r$REV); "
1611 $Net::Twitter::VERSION
1612 ? "Net::Twitter v$Net::Twitter::VERSION. "
1616 $Net::Identica::VERSION
1617 ? "Net::Identica v$Net::Identica::VERSION. "
1621 . JSON::Any::handler()
1622 . ". See details at http://twirssi.com/"
1626 Irssi::command_bind(
1629 "/twitter_follow <username>",
1631 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1634 Irssi::command_bind(
1637 "/twitter_unfriend <username>",
1639 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1642 Irssi::command_bind(
1643 "twitter_device_updates",
1645 "/twitter_device_updates none|im|sms",
1646 "update_delivery_device",
1647 sub { ¬ice("Device updated to $_[0]"); }
1650 Irssi::command_bind(
1653 "/twitter_block <username>",
1655 sub { ¬ice("Blocked $_[0]"); }
1658 Irssi::command_bind(
1661 "/twitter_unblock <username>",
1663 sub { ¬ice("Unblock $_[0]"); }
1666 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1668 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1669 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1671 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1673 my $file = Irssi::settings_get_str("twirssi_replies_store");
1674 if ( $file and -r $file ) {
1675 if ( open( JSON, $file ) ) {
1680 my $ref = JSON::Any->jsonToObj($json);
1682 my $num = keys %{ $id_map{__indexes} };
1683 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1684 $num, ( $num == 1 ? "" : "s" ) );
1688 ¬ice("Failed to load old replies from $file: $!");
1692 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1693 ¬ice("Loading WWW::Shorten::$provider...");
1694 eval "use WWW::Shorten::$provider;";
1698 "Failed to load WWW::Shorten::$provider - either clear",
1699 "short_url_provider or install the CPAN module"
1704 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1705 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1713 ->print( "Create a window named "
1714 . Irssi::settings_get_str('twitter_window')
1715 . " or change the value of twitter_window. Then, reload twirssi." );
1718 # vim: set sts=4 expandtab: