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");
557 my ( $data, $server, $win ) = @_;
559 unless ( $twit and $twit->can('search') ) {
560 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
561 . "doesn't support searches." );
565 $data =~ s/^\s+|\s+$//;
569 ¬ice("Usage: /twitter_subscribe <topic>");
573 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
574 ¬ice("Already had a subscription for '$data'");
578 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
579 ¬ice("Added subscription for '$data'");
583 my ( $data, $server, $win ) = @_;
585 unless ( $twit and $twit->can('search') ) {
586 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
587 . "doesn't support searches." );
590 $data =~ s/^\s+|\s+$//;
594 ¬ice("Usage: /twitter_unsubscribe <topic>");
598 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
599 ¬ice("No subscription found for '$data'");
603 delete $id_map{__searches}{"$user\@$defservice"}{$data};
604 ¬ice("Removed subscription for '$data'");
607 sub cmd_list_search {
608 my ( $data, $server, $win ) = @_;
611 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
613 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
614 $topics = $topics ? "$topics, $topic" : $topic;
618 ¬ice("Search subscriptions for \@$suser: $topics");
623 ¬ice("No search subscriptions set up");
628 my ( $data, $server, $win ) = @_;
630 my $loc = Irssi::settings_get_str("twirssi_location");
633 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
639 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
640 eval { use Digest::MD5; };
644 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
649 $md5 = get("http://twirssi.com/md5sum");
653 ¬ice("Failed to download md5sum from peeron! Aborting.");
657 unless ( open( CUR, $loc ) ) {
659 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
664 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
667 if ( $cur_md5 eq $md5 ) {
668 ¬ice("Current twirssi seems to be up to date.");
674 Irssi::settings_get_bool("twirssi_upgrade_beta")
675 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
676 : "http://twirssi.com/twirssi.pl";
677 ¬ice("Downloading twirssi from $URL");
678 LWP::Simple::getstore( $URL, "$loc.upgrade" );
680 unless ( -s "$loc.upgrade" ) {
681 ¬ice("Failed to save $loc.upgrade."
682 . " Check that /set twirssi_location is set to the correct location."
687 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
688 unless ( open( NEW, "$loc.upgrade" ) ) {
689 ¬ice("Failed to read $loc.upgrade."
690 . " Check that /set twirssi_location is set to the correct location."
695 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
698 if ( $new_md5 ne $md5 ) {
699 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
704 rename $loc, "$loc.backup"
705 or ¬ice("Failed to back up $loc: $!. Aborting")
707 rename "$loc.upgrade", $loc
708 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
711 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
712 if ( -e "$dir/autorun/$file" ) {
713 ¬ice("Updating $dir/autorun/$file");
714 unlink "$dir/autorun/$file"
715 or ¬ice("Failed to remove old $file from autorun: $!");
716 symlink "../$file", "$dir/autorun/$file"
717 or ¬ice("Failed to create symlink in autorun directory: $!");
720 ¬ice("Download complete. Reload twirssi with /script load $file");
730 print $fh "type:debug Loading friends page $page...\n"
731 if ( $fh and &debug );
732 my $friends = $twit->friends( { page => $page } );
733 last unless $friends;
734 $new_friends{ $_->{screen_name} } = time foreach @$friends;
736 last if @$friends == 0 or $page == 10;
741 print $fh "type:debug Error during friends list update. Aborted.\n";
745 my ( $added, $removed ) = ( 0, 0 );
746 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
747 foreach ( keys %new_friends ) {
748 next if exists $friends{$_};
753 print $fh "type:debug Scanning for removed friends...\n"
754 if ( $fh and &debug );
755 foreach ( keys %friends ) {
756 next if exists $new_friends{$_};
761 return ( $added, $removed );
765 print scalar localtime, " - get_updates starting" if &debug;
768 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
771 ->print( "Can't find a window named '"
772 . Irssi::settings_get_str('twitter_window')
773 . "'. Create it or change the value of twitter_window" );
776 return unless &logged_in($twit);
778 my ( $fh, $filename ) = File::Temp::tempfile();
779 binmode( $fh, ":utf8" );
782 if ($child_pid) { # parent
783 Irssi::timeout_add_once( 5000, 'monitor_child',
784 [ "$filename.done", 0 ] );
785 Irssi::pidwait_add($child_pid);
786 } elsif ( defined $child_pid ) { # child
795 foreach ( keys %twits ) {
796 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
799 print $fh "__friends__\n";
801 time - $last_friends_poll >
802 Irssi::settings_get_int('twitter_friends_poll') )
804 print $fh "__updated ", time, "\n";
805 my ( $added, $removed ) = &load_friends($fh);
806 if ( $added + $removed ) {
807 print $fh "type:debug %R***%n Friends list updated: ",
809 sprintf( "%d added", $added ),
810 sprintf( "%d removed", $removed ) ),
815 foreach ( sort keys %friends ) {
816 print $fh "$_ $friends{$_}\n";
820 print $fh "type:debug Update encountered errors. Aborted\n";
821 print $fh "-- $last_poll";
823 print $fh "-- $new_poll";
826 rename $filename, "$filename.done";
829 &ccrap("Failed to fork for updating: $!");
831 print scalar localtime, " - get_updates ends" if &debug;
835 my ( $fh, $username, $obj, $cache ) = @_;
837 my $rate_limit = $obj->rate_limit_status();
838 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
839 ¬ice("Rate limit exceeded for $username");
843 print scalar localtime, " - Polling for updates for $username" if &debug;
847 if ( $id_map{__last_id}{$username}{timeline} )
849 $tweets = $obj->friends_timeline( { count => 100 } );
851 $tweets = $obj->friends_timeline();
856 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
857 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
861 unless ( ref $tweets ) {
862 if ( $obj->can("get_error") ) {
863 my $error = "Unknown error";
864 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
865 unless ($@) { $error = $obj->get_error() }
867 "type:debug API Error during friends_timeline call: Aborted\n";
868 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
872 "type:debug API Error during friends_timeline call. Aborted.\n";
877 foreach my $t ( reverse @$tweets ) {
878 my $text = decode_entities( $t->{text} );
879 $text =~ s/[\n\r]/ /g;
881 if ( Irssi::settings_get_bool("show_reply_context")
882 and $t->{in_reply_to_screen_name} ne $username
883 and $t->{in_reply_to_screen_name}
884 and not exists $friends{ $t->{in_reply_to_screen_name} } )
886 $nicks{ $t->{in_reply_to_screen_name} } = time;
888 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
890 $cache->{ $t->{in_reply_to_status_id} } =
891 $obj->show_status( $t->{in_reply_to_status_id} );
895 $context = $cache->{ $t->{in_reply_to_status_id} };
898 my $ctext = decode_entities( $context->{text} );
899 $ctext =~ s/[\n\r]/ /g;
900 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
902 " -- http://twitter.com/$context->{user}{screen_name}"
903 . "/status/$context->{id}";
905 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
906 $context->{id}, $username,
907 $context->{user}{screen_name}, $ctext;
912 if $t->{user}{screen_name} eq $username
913 and not Irssi::settings_get_bool("show_own_tweets");
914 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
915 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
916 . "/status/$t->{id}";
918 printf $fh "id:%u account:%s nick:%s type:%s %s\n",
919 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
920 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
922 printf $fh "id:%u account:%s type:last_id timeline\n",
923 $new_poll_id, $username;
925 print scalar localtime, " - Polling for replies since ",
926 $id_map{__last_id}{$username}{reply}
930 if ( $id_map{__last_id}{$username}{reply} )
932 $tweets = $obj->replies(
933 { since_id => $id_map{__last_id}{$username}{reply} } )
936 $tweets = $obj->replies() || [];
941 print $fh "type:debug Error during replies call. Aborted.\n";
945 foreach my $t ( reverse @$tweets ) {
947 if exists $friends{ $t->{user}{screen_name} };
949 my $text = decode_entities( $t->{text} );
950 $text =~ s/[\n\r]/ /g;
951 if ( $t->{truncated} ) {
952 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
953 . "/status/$t->{id}";
955 printf $fh "id:%u account:%s nick:%s type:tweet %s\n",
956 $t->{id}, $username, $t->{user}{screen_name}, $text;
957 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
959 printf $fh "id:%u account:%s type:last_id reply\n", $new_poll_id, $username;
961 print scalar localtime, " - Polling for DMs" if &debug;
964 if ( $id_map{__last_id}{$username}{dm} )
966 $tweets = $obj->direct_messages(
967 { since_id => $id_map{__last_id}{$username}{dm} } )
970 $tweets = $obj->direct_messages() || [];
975 print $fh "type:debug Error during direct_messages call. Aborted.\n";
979 foreach my $t ( reverse @$tweets ) {
980 my $text = decode_entities( $t->{text} );
981 $text =~ s/[\n\r]/ /g;
982 printf $fh "id:%u account:%s nick:%s type:dm %s\n",
983 $t->{id}, $username, $t->{sender_screen_name}, $text;
984 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
986 printf $fh "id:%u account:%s type:last_id dm\n", $new_poll_id, $username;
988 print scalar localtime, " - Polling for subscriptions" if &debug;
989 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
991 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
992 print $fh "type:debug searching for $topic since ",
993 "$id_map{__searches}{$username}{$topic}\n";
995 $search = $obj->search(
998 since_id => $id_map{__searches}{$username}{$topic}
1005 "type:debug Error during search($topic) call. Aborted.\n";
1009 unless ( $search->{max_id} ) {
1010 print $fh "type:debug Invalid search results when searching",
1011 " for $topic. Aborted.\n";
1015 $id_map{__searches}{$username}{$topic} = $search->{max_id};
1016 printf $fh "id:%u account:%s type:searchid topic:%s\n",
1017 $search->{max_id}, $username, $topic;
1019 foreach my $t ( reverse @{ $search->{results} } ) {
1020 my $text = decode_entities( $t->{text} );
1021 $text =~ s/[\n\r]/ /g;
1022 printf $fh "id:%u account:%s nick:%s type:search topic:%s %s\n",
1023 $t->{id}, $username, $t->{from_user}, $topic, $text;
1024 $new_poll_id = $t->{id}
1026 or $t->{id} < $new_poll_id;
1031 print scalar localtime, " - Done" if &debug;
1038 my $filename = $data->[0];
1039 my $attempt = $data->[1];
1041 print scalar localtime, " - checking child log at $filename ($attempt)"
1043 my ($new_last_poll);
1045 # first time we run we don't want to print out *everything*, so we just
1048 if ( open FILE, $filename ) {
1049 binmode FILE, ":utf8";
1053 last if /^__friends__/;
1054 unless (/\n$/) { # skip partial lines
1055 # print "Skipping partial line: $_" if &debug;
1062 foreach my $key (qw/id account nick type topic/) {
1063 if (s/^$key:(\S+)\s*//) {
1068 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1069 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1073 $new_cache{ $meta{id} } = time;
1075 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1081 $meta{account} =~ s/\@(\w+)$//;
1082 $meta{service} = $1;
1084 lc $meta{service} eq
1085 lc Irssi::settings_get_str("twirssi_default_service") )
1087 $account = "$meta{account}: "
1088 if lc "$meta{account}\@$meta{service}" ne lc
1089 "$user\@$defservice";
1091 $account = "$meta{account}\@$meta{service}: ";
1095 if ( $meta{type} ne 'dm'
1096 and Irssi::settings_get_bool("twirssi_track_replies")
1100 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1101 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1102 $id_map{__indexes}{ $meta{nick} } = $marker;
1103 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1104 $marker = ":$marker";
1108 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1109 my $nick = "\@$meta{account}";
1110 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1111 and Irssi::settings_get_bool("twirssi_hilights") )
1113 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1114 $hilight = MSGLEVEL_HILIGHT;
1117 if ( $meta{type} =~ /tweet|reply/ ) {
1120 ( MSGLEVEL_PUBLIC | $hilight ),
1121 $meta{type}, $account, $meta{nick}, $marker, $_
1123 } elsif ( $meta{type} eq 'search' ) {
1126 ( MSGLEVEL_PUBLIC | $hilight ),
1127 $meta{type}, $account, $meta{topic},
1128 $meta{nick}, $marker, $_
1131 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1133 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1135 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1138 } elsif ( $meta{type} eq 'dm' ) {
1141 ( MSGLEVEL_MSGS | $hilight ),
1142 $meta{type}, $account, $meta{nick}, $_
1144 } elsif ( $meta{type} eq 'searchid' ) {
1145 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1148 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1150 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1152 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1155 print "Search '$meta{topic}' returned invalid id $meta{id}";
1157 } elsif ( $meta{type} eq 'last_id' ) {
1158 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1160 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1162 } elsif ( $meta{type} eq 'error' ) {
1163 push @lines, [ MSGLEVEL_MSGS, $_ ];
1164 } elsif ( $meta{type} eq 'debug' ) {
1165 print "$_" if &debug,;
1167 print "Unknown line type $meta{type}: $_" if &debug,;
1173 if (/^__updated (\d+)$/) {
1174 $last_friends_poll = $1;
1175 print "Friend list updated" if &debug;
1180 $new_last_poll = $1;
1181 if ( $new_last_poll >= $last_poll ) {
1184 print "Impossible! ",
1185 "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1187 undef $new_last_poll;
1191 my ( $f, $t ) = split ' ', $_;
1192 $nicks{$f} = $friends{$f} = $t;
1195 if ($new_last_poll) {
1196 print "new last_poll = $new_last_poll" if &debug;
1197 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1199 print "First call, not printing updates" if &debug;
1201 foreach my $line (@lines) {
1202 $window->printformat(
1204 "twirssi_" . $line->[1],
1205 @$line[ 2 .. $#$line - 1 ],
1206 &hilight( $line->[-1] )
1213 or warn "Failed to remove $filename: $!"
1216 # commit the pending cache lines to the actual cache, now that
1217 # we've printed our output
1218 %tweet_cache = ( %tweet_cache, %new_cache );
1220 # keep enough cached tweets, to make sure we don't show duplicates.
1221 foreach ( keys %tweet_cache ) {
1222 next if $tweet_cache{$_} >= $last_poll - 3600;
1223 delete $tweet_cache{$_};
1225 $last_poll = $new_last_poll;
1227 # make sure the pid is removed from the waitpid list
1228 Irssi::pidwait_remove($child_pid);
1233 Irssi::settings_get_str("twirssi_replies_store") )
1235 if ( open JSON, ">$file" ) {
1236 print JSON JSON::Any->objToJson( \%id_map );
1239 &ccrap("Failed to write replies to $file: $!");
1250 if ( $attempt < 24 ) {
1251 Irssi::timeout_add_once( 5000, 'monitor_child',
1252 [ $filename, $attempt + 1 ] );
1254 print "Giving up on polling $filename" if &debug;
1255 unlink $filename unless &debug;
1257 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1260 my @time = localtime($last_poll);
1261 if ( time - $last_poll < 24 * 60 * 60 ) {
1262 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1264 $since = scalar localtime($last_poll);
1267 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1272 q{ .--./ / | _.---.| },
1284 if ( time - $last_poll < 600 ) {
1285 &ccrap("Haven't been able to get updated tweets since $since");
1291 return Irssi::settings_get_bool("twirssi_debug");
1295 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1299 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1305 if ( Irssi::settings_get_bool("tweet_to_away")
1307 and $data !~ /^[dD] / )
1310 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1312 $server->send_raw("away :$data");
1315 &ccrap( "Can't find bitlbee server.",
1316 "Update bitlbee_server or disable tweet_to_away" );
1326 my $noalert = shift;
1328 if ( length $data > 140 ) {
1329 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1337 sub valid_username {
1338 my $username = shift;
1340 $username = &normalize_username($username);
1342 unless ( exists $twits{$username} ) {
1343 ¬ice("Unknown username $username");
1353 ¬ice("Not logged in! Use /twitter_login username pass!");
1361 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1364 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1365 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1366 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1368 { # /twitter_reply gets a nick:num
1370 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1371 sort { $nicks{$b} <=> $nicks{$a} }
1373 keys %{ $id_map{__indexes} };
1376 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1377 { # /twitter_unfriend gets a nick
1379 push @$complist, grep /^\Q$word/i,
1380 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1383 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1385 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1386 my $prefix = $word =~ s/^@//;
1387 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1388 push @$complist, grep /^\Q$word/i,
1389 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1390 @$complist = map { "\@$_" } @$complist if $prefix;
1394 sub event_send_text {
1395 my ( $line, $server, $win ) = @_;
1396 my $awin = Irssi::active_win();
1398 # if the window where we got our text was the twitter window, and the user
1399 # wants to be lazy, tweet away!
1400 if ( ( $awin->get_active_name() eq $window->{name} )
1401 and Irssi::settings_get_bool("tweet_window_input") )
1403 &cmd_tweet( $line, $server, $win );
1408 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1409 return $poll if $poll >= 60;
1416 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1417 my $c = Irssi::settings_get_str("twirssi_nick_color");
1418 $c = $irssi_to_mirc_colors{$c};
1419 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1421 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1422 my $c = Irssi::settings_get_str("twirssi_topic_color");
1423 $c = $irssi_to_mirc_colors{$c};
1424 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1426 $text =~ s/[\n\r]/ /g;
1434 my $provider = Irssi::settings_get_str("short_url_provider");
1437 Irssi::settings_get_bool("twirssi_always_shorten")
1438 or &too_long( $data, 1 )
1444 if ( $provider eq 'Bitly' ) {
1445 @args[ 1, 2 ] = split ',',
1446 Irssi::settings_get_str("short_url_args"), 2;
1447 unless ( @args == 3 ) {
1449 "WWW::Shorten::Bitly requires a username and API key.",
1450 "Set short_url_args to username,API_key or change your",
1451 "short_url_provider."
1457 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1460 my $short = makeashorterlink(@args);
1462 $data =~ s/\Q$url/$short/g;
1464 ¬ice("Failed to shorten $url!");
1470 return decode "utf8", $data;
1473 sub normalize_username {
1476 my ( $username, $service ) = split /\@/, $user, 2;
1478 $service = ucfirst lc $service;
1481 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1482 unless ( exists $twits{"$username\@$service"} ) {
1484 foreach my $t ( sort keys %twits ) {
1485 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1491 ¬ice("Can't find a logged in user '$user'");
1496 return "$username\@$service";
1499 Irssi::signal_add( "send text", "event_send_text" );
1501 Irssi::theme_register(
1503 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1504 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1505 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1506 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1507 'twirssi_error', 'ERROR: $0',
1511 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1512 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1513 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1514 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1515 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1516 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1517 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1518 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1519 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1520 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1521 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1522 'RT $n: "$t" ${-- $c$}' );
1523 Irssi::settings_add_str( "twirssi", "twirssi_location",
1524 ".irssi/scripts/twirssi.pl" );
1525 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1526 ".irssi/scripts/twirssi.json" );
1528 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1529 Irssi::settings_add_int( "twirssi", "twitter_timeout", 30 );
1531 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1532 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1533 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1534 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1535 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1536 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1537 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1538 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1539 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1540 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1541 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1542 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1543 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1544 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl", 0 );
1546 $last_poll = time - &get_poll_time;
1547 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1550 ->print( "Couldn't find a window named '"
1551 . Irssi::settings_get_str('twitter_window')
1552 . "', trying to create it." );
1554 Irssi::Windowitem::window_create(
1555 Irssi::settings_get_str('twitter_window'), 1 );
1556 $window->set_name( Irssi::settings_get_str('twitter_window') );
1560 Irssi::command_bind( "dm", "cmd_direct" );
1561 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1562 Irssi::command_bind( "tweet", "cmd_tweet" );
1563 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1564 Irssi::command_bind( "retweet", "cmd_retweet" );
1565 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1566 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1567 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1568 Irssi::command_bind( "twitter_login", "cmd_login" );
1569 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1570 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1571 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1572 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1573 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1574 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1575 Irssi::command_bind( "twitter_updates", "get_updates" );
1576 Irssi::command_bind( "bitlbee_away", "update_away" );
1577 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1578 Irssi::command_bind( "reply", "cmd_reply" );
1579 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1581 Irssi::command_bind(
1584 print "twits: ", join ", ",
1585 map { "u: $_->{username}\@" . ref($_) } values %twits;
1586 print "selected: $user\@$defservice";
1587 print "friends: ", join ", ", sort keys %friends;
1588 print "nicks: ", join ", ", sort keys %nicks;
1589 print "searches: ", Dumper \%{ $id_map{__searches} };
1590 print "last poll: $last_poll";
1591 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1592 print DUMP Dumper \%tweet_cache;
1594 print "cache written out to /tmp/twirssi.cache.txt";
1598 Irssi::command_bind(
1602 "Twirssi v$VERSION (r$REV); "
1604 $Net::Twitter::VERSION
1605 ? "Net::Twitter v$Net::Twitter::VERSION. "
1609 $Net::Identica::VERSION
1610 ? "Net::Identica v$Net::Identica::VERSION. "
1614 . JSON::Any::handler()
1615 . ". See details at http://twirssi.com/"
1619 Irssi::command_bind(
1622 "/twitter_follow <username>",
1624 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1627 Irssi::command_bind(
1630 "/twitter_unfriend <username>",
1632 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1635 Irssi::command_bind(
1636 "twitter_device_updates",
1638 "/twitter_device_updates none|im|sms",
1639 "update_delivery_device",
1640 sub { ¬ice("Device updated to $_[0]"); }
1643 Irssi::command_bind(
1646 "/twitter_block <username>",
1648 sub { ¬ice("Blocked $_[0]"); }
1651 Irssi::command_bind(
1654 "/twitter_unblock <username>",
1656 sub { ¬ice("Unblock $_[0]"); }
1659 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1661 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1662 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1664 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1666 my $file = Irssi::settings_get_str("twirssi_replies_store");
1667 if ( $file and -r $file ) {
1668 if ( open( JSON, $file ) ) {
1673 my $ref = JSON::Any->jsonToObj($json);
1675 my $num = keys %{ $id_map{__indexes} };
1676 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1677 $num, ( $num == 1 ? "" : "s" ) );
1681 ¬ice("Failed to load old replies from $file: $!");
1685 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1686 ¬ice("Loading WWW::Shorten::$provider...");
1687 eval "use WWW::Shorten::$provider;";
1691 "Failed to load WWW::Shorten::$provider - either clear",
1692 "short_url_provider or install the CPAN module"
1697 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1698 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1706 ->print( "Create a window named "
1707 . Irssi::settings_get_str('twitter_window')
1708 . " or change the value of twitter_window. Then, reload twirssi." );
1711 # vim: set sts=4 expandtab: