10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
14 $VERSION = "2.2.5beta";
15 my ($REV) = '$Rev: 677 $' =~ /(\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-07-22 13:58:05 -0700 (Wed, 22 Jul 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 ) {
1038 last if /^__friends__/;
1039 unless (/\n$/) { # skip partial lines
1040 # print "Skipping partial line: $_" if &debug;
1047 foreach my $key (qw/id account nick type topic/) {
1048 if (s/^$key:(\S+)\s*//) {
1053 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1054 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1058 $new_cache{ $meta{id} } = time;
1060 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1066 $meta{account} =~ s/\@(\w+)$//;
1067 $meta{service} = $1;
1069 lc $meta{service} eq
1070 lc Irssi::settings_get_str("twirssi_default_service") )
1072 $account = "$meta{account}: "
1073 if lc "$meta{account}\@$meta{service}" ne lc
1074 "$user\@$defservice";
1076 $account = "$meta{account}\@$meta{service}: ";
1080 if ( $meta{type} ne 'dm'
1081 and Irssi::settings_get_bool("twirssi_track_replies")
1085 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1086 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1087 $id_map{__indexes}{ $meta{nick} } = $marker;
1088 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1089 $marker = ":$marker";
1093 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1094 my $nick = "\@$meta{account}";
1095 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1096 and Irssi::settings_get_bool("twirssi_hilights") )
1098 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1099 $hilight = MSGLEVEL_HILIGHT;
1102 if ( $meta{type} =~ /tweet|reply/ ) {
1105 ( MSGLEVEL_PUBLIC | $hilight ),
1106 $meta{type}, $account, $meta{nick}, $marker, $_
1108 } elsif ( $meta{type} eq 'search' ) {
1111 ( MSGLEVEL_PUBLIC | $hilight ),
1112 $meta{type}, $account, $meta{topic},
1113 $meta{nick}, $marker, $_
1116 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1118 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1120 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1123 } elsif ( $meta{type} eq 'dm' ) {
1126 ( MSGLEVEL_MSGS | $hilight ),
1127 $meta{type}, $account, $meta{nick}, $_
1129 } elsif ( $meta{type} eq 'searchid' ) {
1130 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1133 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1135 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1137 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1140 print "Search '$meta{topic}' returned invalid id $meta{id}";
1142 } elsif ( $meta{type} eq 'last_id' ) {
1143 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1145 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1147 } elsif ( $meta{type} eq 'error' ) {
1148 push @lines, [ MSGLEVEL_MSGS, $_ ];
1149 } elsif ( $meta{type} eq 'debug' ) {
1150 print "$_" if &debug,;
1152 print "Unknown line type $meta{type}: $_" if &debug,;
1158 if (/^__updated (\d+)$/) {
1159 $last_friends_poll = $1;
1160 print "Friend list updated" if &debug;
1165 ($new_last_poll) = ($1);
1168 my ( $f, $t ) = split ' ', $_;
1169 $nicks{$f} = $friends{$f} = $t;
1172 if ($new_last_poll) {
1173 print "new last_poll = $new_last_poll" if &debug;
1174 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1176 print "First call, not printing updates" if &debug;
1178 foreach my $line (@lines) {
1179 $window->printformat(
1181 "twirssi_" . $line->[1],
1182 @$line[ 2 .. $#$line - 1 ],
1183 &hilight( $line->[-1] )
1190 or warn "Failed to remove $filename: $!"
1193 # commit the pending cache lines to the actual cache, now that
1194 # we've printed our output
1195 %tweet_cache = ( %tweet_cache, %new_cache );
1197 # keep enough cached tweets, to make sure we don't show duplicates.
1198 foreach ( keys %tweet_cache ) {
1199 next if $tweet_cache{$_} >= $last_poll - 3600;
1200 delete $tweet_cache{$_};
1202 $last_poll = $new_last_poll;
1207 Irssi::settings_get_str("twirssi_replies_store") )
1209 if ( open JSON, ">$file" ) {
1210 print JSON JSON::Any->objToJson( \%id_map );
1213 &ccrap("Failed to write replies to $file: $!");
1224 if ( $attempt < 24 ) {
1225 Irssi::timeout_add_once( 5000, 'monitor_child',
1226 [ $filename, $attempt + 1 ] );
1228 print "Giving up on polling $filename" if &debug;
1229 unlink $filename unless &debug;
1231 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1234 my @time = localtime($last_poll);
1235 if ( time - $last_poll < 24 * 60 * 60 ) {
1236 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1238 $since = scalar localtime($last_poll);
1241 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1246 q{ .--./ / | _.---.| },
1258 if ( time - $last_poll < 600 ) {
1259 &ccrap("Haven't been able to get updated tweets since $since");
1265 return Irssi::settings_get_bool("twirssi_debug");
1269 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1273 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1279 if ( Irssi::settings_get_bool("tweet_to_away")
1281 and $data !~ /^[dD] / )
1284 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1286 $server->send_raw("away :$data");
1289 &ccrap( "Can't find bitlbee server.",
1290 "Update bitlbee_server or disable tweet_to_away" );
1300 my $noalert = shift;
1302 if ( length $data > 140 ) {
1303 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1311 sub valid_username {
1312 my $username = shift;
1314 $username = &normalize_username($username);
1316 unless ( exists $twits{$username} ) {
1317 ¬ice("Unknown username $username");
1327 ¬ice("Not logged in! Use /twitter_login username pass!");
1335 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1338 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1339 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1340 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1342 { # /twitter_reply gets a nick:num
1344 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1345 sort { $nicks{$b} <=> $nicks{$a} }
1347 keys %{ $id_map{__indexes} };
1350 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1351 { # /twitter_unfriend gets a nick
1353 push @$complist, grep /^\Q$word/i,
1354 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1357 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1359 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1360 my $prefix = $word =~ s/^@//;
1361 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1362 push @$complist, grep /^\Q$word/i,
1363 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1364 @$complist = map { "\@$_" } @$complist if $prefix;
1368 sub event_send_text {
1369 my ( $line, $server, $win ) = @_;
1370 my $awin = Irssi::active_win();
1372 # if the window where we got our text was the twitter window, and the user
1373 # wants to be lazy, tweet away!
1374 if ( ( $awin->get_active_name() eq $window->{name} )
1375 and Irssi::settings_get_bool("tweet_window_input") )
1377 &cmd_tweet( $line, $server, $win );
1382 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1383 return $poll if $poll >= 60;
1390 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1391 my $c = Irssi::settings_get_str("twirssi_nick_color");
1392 $c = $irssi_to_mirc_colors{$c};
1393 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1395 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1396 my $c = Irssi::settings_get_str("twirssi_topic_color");
1397 $c = $irssi_to_mirc_colors{$c};
1398 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1400 $text =~ s/[\n\r]/ /g;
1408 my $provider = Irssi::settings_get_str("short_url_provider");
1411 Irssi::settings_get_bool("twirssi_always_shorten")
1412 or &too_long( $data, 1 )
1418 if ( $provider eq 'Bitly' ) {
1419 @args[ 1, 2 ] = split ',',
1420 Irssi::settings_get_str("short_url_args"), 2;
1421 unless ( @args == 3 ) {
1423 "WWW::Shorten::Bitly requires a username and API key.",
1424 "Set short_url_args to username,API_key or change your",
1425 "short_url_provider."
1431 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1434 my $short = makeashorterlink(@args);
1436 $data =~ s/\Q$url/$short/g;
1438 ¬ice("Failed to shorten $url!");
1444 return decode "utf8", $data;
1447 sub normalize_username {
1450 my ( $username, $service ) = split /\@/, $user, 2;
1452 $service = ucfirst lc $service;
1455 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1456 unless ( exists $twits{"$username\@$service"} ) {
1458 foreach my $t ( sort keys %twits ) {
1459 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1465 ¬ice("Can't find a logged in user '$user'");
1470 return "$username\@$service";
1473 Irssi::signal_add( "send text", "event_send_text" );
1475 Irssi::theme_register(
1477 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1478 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1479 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1480 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1481 'twirssi_error', 'ERROR: $0',
1485 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1486 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1487 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1488 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1489 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1490 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1491 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1492 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1493 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1494 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1495 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1496 'RT $n: "$t" ${-- $c$}' );
1497 Irssi::settings_add_str( "twirssi", "twirssi_location",
1498 ".irssi/scripts/twirssi.pl" );
1499 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1500 ".irssi/scripts/twirssi.json" );
1502 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1504 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1505 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1506 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1507 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1508 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1509 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1510 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1511 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1512 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1513 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1514 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1515 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1516 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1517 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl", 0 );
1519 $last_poll = time - &get_poll_time;
1520 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1523 ->print( "Couldn't find a window named '"
1524 . Irssi::settings_get_str('twitter_window')
1525 . "', trying to create it." );
1527 Irssi::Windowitem::window_create(
1528 Irssi::settings_get_str('twitter_window'), 1 );
1529 $window->set_name( Irssi::settings_get_str('twitter_window') );
1533 Irssi::command_bind( "dm", "cmd_direct" );
1534 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1535 Irssi::command_bind( "tweet", "cmd_tweet" );
1536 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1537 Irssi::command_bind( "retweet", "cmd_retweet" );
1538 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1539 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1540 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1541 Irssi::command_bind( "twitter_login", "cmd_login" );
1542 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1543 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1544 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1545 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1546 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1547 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1548 Irssi::command_bind( "twitter_updates", "get_updates" );
1549 Irssi::command_bind( "bitlbee_away", "update_away" );
1550 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1551 Irssi::command_bind( "reply", "cmd_reply" );
1552 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1554 Irssi::command_bind(
1557 print "twits: ", join ", ",
1558 map { "u: $_->{username}\@" . ref($_) } values %twits;
1559 print "selected: $user\@$defservice";
1560 print "friends: ", join ", ", sort keys %friends;
1561 print "nicks: ", join ", ", sort keys %nicks;
1562 print "searches: ", Dumper \%{ $id_map{__searches} };
1563 print "last poll: $last_poll";
1564 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1565 print DUMP Dumper \%tweet_cache;
1567 print "cache written out to /tmp/twirssi.cache.txt";
1571 Irssi::command_bind(
1574 ¬ice("Twirssi v$VERSION (r$REV); "
1575 . "Net::Twitter v$Net::Twitter::VERSION. "
1577 . JSON::Any::handler()
1578 . ". See details at http://twirssi.com/" );
1581 Irssi::command_bind(
1584 "/twitter_follow <username>",
1586 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1589 Irssi::command_bind(
1592 "/twitter_unfriend <username>",
1594 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1597 Irssi::command_bind(
1598 "twitter_device_updates",
1600 "/twitter_device_updates none|im|sms",
1601 "update_delivery_device",
1602 sub { ¬ice("Device updated to $_[0]"); }
1605 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1607 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1608 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1610 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1612 my $file = Irssi::settings_get_str("twirssi_replies_store");
1613 if ( $file and -r $file ) {
1614 if ( open( JSON, $file ) ) {
1619 my $ref = JSON::Any->jsonToObj($json);
1621 my $num = keys %{ $id_map{__indexes} };
1622 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1623 $num, ( $num == 1 ? "" : "s" ) );
1627 ¬ice("Failed to load old replies from $file: $!");
1631 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1632 ¬ice("Loading WWW::Shorten::$provider...");
1633 eval "use WWW::Shorten::$provider;";
1637 "Failed to load WWW::Shorten::$provider - either clear",
1638 "short_url_provider or install the CPAN module"
1643 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1644 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1652 ->print( "Create a window named "
1653 . Irssi::settings_get_str('twitter_window')
1654 . " or change the value of twitter_window. Then, reload twirssi." );
1657 # vim: set sts=4 expandtab: