9 $Data::Dumper::Indent = 1;
11 use vars qw($VERSION %IRSSI);
13 $VERSION = "2.2.3beta";
14 my ($REV) = '$Rev: 619 $' =~ /(\d+)/;
16 authors => 'Dan Boger',
17 contact => 'zigdon@gmail.com',
19 description => 'Send twitter updates using /tweet. '
20 . 'Can optionally set your bitlbee /away message to same',
21 license => 'GNU GPL v2',
22 url => 'http://twirssi.com',
23 changed => '$Date: 2009-04-25 11:08:58 -0700 (Sat, 25 Apr 2009) $',
33 my $last_friends_poll = 0;
41 my %irssi_to_mirc_colors = (
61 my ( $data, $server, $win ) = @_;
63 return unless &logged_in($twit);
65 my ( $target, $text ) = split ' ', $data, 2;
66 unless ( $target and $text ) {
67 ¬ice("Usage: /dm <nick> <message>");
71 &cmd_direct_as( "$user $data", $server, $win );
75 my ( $data, $server, $win ) = @_;
77 return unless &logged_in($twit);
79 my ( $username, $target, $text ) = split ' ', $data, 3;
80 unless ( $username and $target and $text ) {
81 ¬ice("Usage: /dm_as <username> <nick> <message>");
85 return unless $username = &valid_username($username);
88 if ( $twits{$username}
89 ->new_direct_message( { user => $target, text => $text } ) )
91 ¬ice("DM sent to $target");
92 $nicks{$target} = time;
96 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
97 $error = $error->{error};
100 ¬ice("DM to $target failed");
105 ¬ice("DM caused an error: $@");
111 my ( $data, $server, $win ) = @_;
113 return unless &logged_in($twit);
115 $data =~ s/^\s+|\s+$//;
117 ¬ice("Usage: /retweet <nick[:num]> [comment]");
121 my ( $id, $data ) = split ' ', $data, 2;
123 &cmd_retweet_as( "$user $id $data", $server, $win );
127 my ( $data, $server, $win ) = @_;
129 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
130 ¬ice("twirssi_track_replies is required in order to reteet.");
134 return unless &logged_in($twit);
136 $data =~ s/^\s+|\s+$//;
137 my ( $username, $id, $data ) = split ' ', $data, 3;
140 ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
144 return unless $username = &valid_username($username);
147 $id =~ s/[^\w\d\-:]+//g;
148 ( $nick, $id ) = split /:/, $id;
149 unless ( exists $id_map{ lc $nick } ) {
150 ¬ice("Can't find a tweet from $nick to retweet!");
154 $id = $id_map{__indexes}{$nick} unless $id;
155 unless ( $id_map{ lc $nick }[$id] ) {
156 ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
160 unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
161 ¬ice("The text of this tweet isn't saved, sorry!");
165 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
166 my $text = Irssi::settings_get_str("twirssi_retweet_format");
167 $text =~ s/\$n/\@$nick/g;
169 $text =~ s/\${|\$}//g;
170 $text =~ s/\$c/$data/;
172 $text =~ s/\${.*?\$}//;
174 $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
176 $data = &shorten($text);
178 return if &too_long($data);
183 $twits{$username}->update(
186 in_reply_to_status_id => $id_map{ lc $nick }[$id]
191 ¬ice("Update failed");
195 return unless $success;
198 ¬ice("Update caused an error: $@. Aborted");
202 foreach ( $data =~ /@([-\w]+)/ ) {
206 ¬ice("Retweet sent");
210 my ( $data, $server, $win ) = @_;
212 return unless &logged_in($twit);
214 $data =~ s/^\s+|\s+$//;
216 ¬ice("Usage: /tweet <update>");
220 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
224 my ( $data, $server, $win ) = @_;
226 return unless &logged_in($twit);
228 $data =~ s/^\s+|\s+$//;
229 $data =~ s/\s\s+/ /g;
230 my ( $username, $data ) = split ' ', $data, 2;
232 unless ( $username and $data ) {
233 ¬ice("Usage: /tweet_as <username> <update>");
237 return unless $username = &valid_username($username);
239 $data = &shorten($data);
241 return if &too_long($data);
245 unless ( $twits{$username}->update($data) )
247 ¬ice("Update failed");
251 return unless $success;
254 ¬ice("Update caused an error: $@. Aborted.");
258 foreach ( $data =~ /@([-\w]+)/ ) {
262 my $away = &update_away($data);
264 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
268 my ( $data, $server, $win ) = @_;
270 return unless &logged_in($twit);
272 $data =~ s/^\s+|\s+$//;
274 ¬ice("Usage: /reply <nick[:num]> <update>");
278 my ( $id, $data ) = split ' ', $data, 2;
279 unless ( $id and $data ) {
280 ¬ice("Usage: /reply <nick[:num]> <update>");
284 &cmd_reply_as( "$user $id $data", $server, $win );
288 my ( $data, $server, $win ) = @_;
290 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
291 ¬ice("twirssi_track_replies is required in order to reply to "
292 . "specific tweets. Either enable it, or just use /tweet "
293 . "\@username <text>." );
297 return unless &logged_in($twit);
299 $data =~ s/^\s+|\s+$//;
300 my ( $username, $id, $data ) = split ' ', $data, 3;
302 unless ( $username and $data ) {
303 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
307 return unless $username = &valid_username($username);
310 $id =~ s/[^\w\d\-:]+//g;
311 ( $nick, $id ) = split /:/, $id;
312 unless ( exists $id_map{ lc $nick } ) {
313 ¬ice("Can't find a tweet from $nick to reply to!");
317 $id = $id_map{__indexes}{$nick} unless $id;
318 unless ( $id_map{ lc $nick }[$id] ) {
319 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
323 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
325 # remove any @nick at the beginning of the reply, as we'll add it anyway
326 $data =~ s/^\s*\@?$nick\s*//;
327 $data = "\@$nick " . $data;
330 $data = &shorten($data);
332 return if &too_long($data);
337 $twits{$username}->update(
340 in_reply_to_status_id => $id_map{ lc $nick }[$id]
345 ¬ice("Update failed");
349 return unless $success;
352 ¬ice("Update caused an error: $@. Aborted");
356 foreach ( $data =~ /@([-\w]+)/ ) {
360 my $away = &update_away($data);
362 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
366 my ( $usage_str, $api_name, $post_ref ) = @_;
369 my ( $data, $server, $win ) = @_;
371 return unless &logged_in($twit);
373 $data =~ s/^\s+|\s+$//;
375 ¬ice("Usage: $usage_str");
381 unless ( $twit->$api_name($data) )
383 ¬ice("$api_name failed");
387 return unless $success;
390 ¬ice("$api_name caused an error. Aborted.");
394 &$post_ref($data) if $post_ref;
399 my ( $data, $server, $win ) = @_;
401 $data =~ s/^\s+|\s+$//g;
402 $data = &normalize_username($data);
403 if ( exists $twits{$data} ) {
404 ¬ice("Switching to $data");
405 $twit = $twits{$data};
406 if ( $data =~ /(.*)\@(.*)/ ) {
410 ¬ice("Couldn't figure out what service '$data' is on");
413 ¬ice("Unknown user $data");
418 my ( $data, $server, $win ) = @_;
420 $data =~ s/^\s+|\s+$//g;
421 $data = $user unless $data;
422 return unless $data = &valid_username($data);
424 ¬ice("Logging out $data...");
425 $twits{$data}->end_session();
426 delete $twits{$data};
429 &cmd_switch( ( keys %twits )[0], $server, $win );
431 Irssi::timeout_remove($poll) if $poll;
437 my ( $data, $server, $win ) = @_;
440 ( $user, $pass ) = split ' ', $data, 2;
441 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
442 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
444 my @user = split /\s*,\s*/, $autouser;
445 my @pass = split /\s*,\s*/, $autopass;
447 # if a password ends with a '\', it was meant to escape the comma, and
448 # it should be concatinated with the next one
452 while ( $p =~ /\\$/ and @pass ) {
453 $p .= "," . shift @pass;
458 if ( @user != @unescaped ) {
459 ¬ice("Number of usernames doesn't match "
460 . "the number of passwords - auto-login failed" );
463 while ( @user and @unescaped ) {
465 $p = shift @unescaped;
471 ¬ice("/twitter_login requires either a username and password "
472 . "or twitter_usernames and twitter_passwords to be set." );
476 %friends = %nicks = ();
479 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
480 ( $user, $service ) = ( $1, $2 );
482 $service = Irssi::settings_get_str("twirssi_default_service");
484 $defservice = $service = ucfirst lc $service;
486 eval "use Net::$service";
489 "Failed to load Net::$service when trying to log in as $user: $@");
493 $twit = "Net::$service"->new(
499 unless ( $twit->verify_credentials() ) {
500 ¬ice("Login as $user\@$service failed");
503 &cmd_switch( ( keys %twits )[0], $server, $win );
509 my $rate_limit = $twit->rate_limit_status();
510 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
512 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
518 $twits{"$user\@$service"} = $twit;
519 Irssi::timeout_remove($poll) if $poll;
520 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
521 ¬ice("Logged in as $user\@$service, loading friends list...");
523 ¬ice( "loaded friends: ", scalar keys %friends );
524 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
525 Irssi::settings_set_bool( "twirssi_first_run", 0 );
526 unless ( exists $friends{twirssi} ) {
527 ¬ice("Welcome to twirssi!"
528 . " Perhaps you should add \@twirssi to your friends list,"
529 . " so you can be notified when a new version is release?"
530 . " Just type /twitter_friend twirssi." );
537 ¬ice("Login failed");
542 my ( $data, $server, $win ) = @_;
544 unless ( $twit and $twit->can('search') ) {
545 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
546 . "doesn't support searches." );
550 $data =~ s/^\s+|\s+$//;
554 ¬ice("Usage: /twitter_subscribe <topic>");
558 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
559 ¬ice("Already had a subscription for '$data'");
563 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
564 ¬ice("Added subscription for '$data'");
568 my ( $data, $server, $win ) = @_;
570 unless ( $twit and $twit->can('search') ) {
571 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
572 . "doesn't support searches." );
575 $data =~ s/^\s+|\s+$//;
579 ¬ice("Usage: /twitter_unsubscribe <topic>");
583 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
584 ¬ice("No subscription found for '$data'");
588 delete $id_map{__searches}{"$user\@$defservice"}{$data};
589 ¬ice("Removed subscription for '$data'");
592 sub cmd_list_search {
593 my ( $data, $server, $win ) = @_;
596 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
598 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
599 $topics = $topics ? "$topics, $topic" : $topic;
603 ¬ice("Search subscriptions for \@$suser: $topics");
608 ¬ice("No search subscriptions set up");
613 my ( $data, $server, $win ) = @_;
615 my $loc = Irssi::settings_get_str("twirssi_location");
618 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
624 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
625 eval { use Digest::MD5; };
629 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
634 $md5 = get("http://twirssi.com/md5sum");
638 ¬ice("Failed to download md5sum from peeron! Aborting.");
642 unless ( open( CUR, $loc ) ) {
644 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
649 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
652 if ( $cur_md5 eq $md5 ) {
653 ¬ice("Current twirssi seems to be up to date.");
659 Irssi::settings_get_bool("twirssi_upgrade_beta")
660 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
661 : "http://twirssi.com/twirssi.pl";
662 ¬ice("Downloading twirssi from $URL");
663 LWP::Simple::getstore( $URL, "$loc.upgrade" );
665 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
666 unless ( open( NEW, "$loc.upgrade" ) ) {
668 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
673 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
676 if ( $new_md5 ne $md5 ) {
677 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
682 rename $loc, "$loc.backup"
683 or ¬ice("Failed to back up $loc: $!. Aborting")
685 rename "$loc.upgrade", $loc
686 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
689 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
690 if ( -e "$dir/autorun/$file" ) {
691 ¬ice("Updating $dir/autorun/$file");
692 unlink "$dir/autorun/$file"
693 or ¬ice("Failed to remove old $file from autorun: $!");
694 symlink "../$file", "$dir/autorun/$file"
695 or ¬ice("Failed to create symlink in autorun directory: $!");
698 ¬ice("Download complete. Reload twirssi with /script load $file");
708 print $fh "type:debug Loading friends page $page...\n"
709 if ( $fh and &debug );
710 my $friends = $twit->friends( { page => $page } );
711 last unless $friends;
712 $new_friends{ $_->{screen_name} } = time foreach @$friends;
714 last if @$friends == 0 or $page == 10;
719 print $fh "type:debug Error during friends list update. Aborted.\n";
723 my ( $added, $removed ) = ( 0, 0 );
724 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
725 foreach ( keys %new_friends ) {
726 next if exists $friends{$_};
731 print $fh "type:debug Scanning for removed friends...\n"
732 if ( $fh and &debug );
733 foreach ( keys %friends ) {
734 next if exists $new_friends{$_};
739 return ( $added, $removed );
743 print scalar localtime, " - get_updates starting" if &debug;
746 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
749 ->print( "Can't find a window named '"
750 . Irssi::settings_get_str('twitter_window')
751 . "'. Create it or change the value of twitter_window" );
754 return unless &logged_in($twit);
756 my ( $fh, $filename ) = File::Temp::tempfile();
757 binmode( $fh, ":utf8" );
761 Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
762 Irssi::pidwait_add($pid);
763 } elsif ( defined $pid ) { # child
772 foreach ( keys %twits ) {
773 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
776 print $fh "__friends__\n";
778 time - $last_friends_poll >
779 Irssi::settings_get_int('twitter_friends_poll') )
781 print $fh "__updated ", time, "\n";
782 my ( $added, $removed ) = &load_friends($fh);
783 if ( $added + $removed ) {
784 print $fh "type:debug %R***%n Friends list updated: ",
786 sprintf( "%d added", $added ),
787 sprintf( "%d removed", $removed ) ),
792 foreach ( sort keys %friends ) {
793 print $fh "$_ $friends{$_}\n";
797 print $fh "type:debug Update encountered errors. Aborted\n";
798 print $fh "-- $last_poll";
800 print $fh "-- $new_poll";
805 print scalar localtime, " - get_updates ends" if &debug;
809 my ( $fh, $username, $obj, $cache ) = @_;
811 my $rate_limit = $obj->rate_limit_status();
812 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
813 ¬ice("Rate limit exceeded for $username");
817 print scalar localtime, " - Polling for updates for $username" if &debug;
821 if ( $id_map{__last_id}{$username}{timeline} )
823 $tweets = $obj->friends_timeline( { count => 100 } );
825 $tweets = $obj->friends_timeline();
830 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
831 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
835 unless ( ref $tweets ) {
836 if ( $obj->can("get_error") ) {
837 my $error = "Unknown error";
838 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
839 unless ($@) { $error = $obj->get_error() }
841 "type:debug API Error during friends_timeline call: Aborted\n";
842 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
846 "type:debug API Error during friends_timeline call. Aborted.\n";
851 foreach my $t ( reverse @$tweets ) {
852 my $text = decode_entities( $t->{text} );
853 $text = &hilight($text);
855 if ( Irssi::settings_get_bool("show_reply_context")
856 and $t->{in_reply_to_screen_name} ne $username
857 and $t->{in_reply_to_screen_name}
858 and not exists $friends{ $t->{in_reply_to_screen_name} } )
860 $nicks{ $t->{in_reply_to_screen_name} } = time;
862 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
864 $cache->{ $t->{in_reply_to_status_id} } =
865 $obj->show_status( $t->{in_reply_to_status_id} );
869 $context = $cache->{ $t->{in_reply_to_status_id} };
872 my $ctext = decode_entities( $context->{text} );
873 $ctext = &hilight($ctext);
874 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
876 " -- http://twitter.com/$context->{user}{screen_name}"
877 . "/status/$context->{id}";
879 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
880 $context->{id}, $username,
881 $context->{user}{screen_name}, $ctext;
886 if $t->{user}{screen_name} eq $username
887 and not Irssi::settings_get_bool("show_own_tweets");
888 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
889 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
890 . "/status/$t->{id}";
892 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
893 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
894 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
896 printf $fh "id:%d account:%s type:last_id timeline\n",
897 $new_poll_id, $username;
899 print scalar localtime, " - Polling for replies" if &debug;
902 if ( $id_map{__last_id}{$username}{reply} )
904 $tweets = $obj->replies(
905 { since_id => $id_map{__last_id}{$username}{reply} } )
908 $tweets = $obj->replies() || [];
913 print $fh "type:debug Error during replies call. Aborted.\n";
917 foreach my $t ( reverse @$tweets ) {
919 if exists $friends{ $t->{user}{screen_name} };
921 my $text = decode_entities( $t->{text} );
922 $text = &hilight($text);
923 if ( $t->{truncated} ) {
924 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
925 . "/status/$t->{id}";
927 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
928 $t->{id}, $username, $t->{user}{screen_name}, $text;
929 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
931 printf $fh "id:%d account:%s type:last_id reply\n", $new_poll_id, $username;
933 print scalar localtime, " - Polling for DMs" if &debug;
936 if ( $id_map{__last_id}{$username}{dm} )
938 $tweets = $obj->direct_messages(
939 { since_id => $id_map{__last_id}{$username}{dm} } )
942 $tweets = $obj->direct_messages() || [];
947 print $fh "type:debug Error during direct_messages call. Aborted.\n";
951 foreach my $t ( reverse @$tweets ) {
952 my $text = decode_entities( $t->{text} );
953 $text = &hilight($text);
954 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
955 $t->{id}, $username, $t->{sender_screen_name}, $text;
956 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
958 printf $fh "id:%d account:%s type:last_id dm\n", $new_poll_id, $username;
960 print scalar localtime, " - Polling for subscriptions" if &debug;
961 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
963 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
964 print $fh "type:debug searching for $topic since ",
965 "$id_map{__searches}{$username}{$topic}\n";
967 $search = $obj->search(
970 since_id => $id_map{__searches}{$username}{$topic}
977 "type:debug Error during search($topic) call. Aborted.\n";
981 unless ( $search->{max_id} ) {
982 print $fh "type:debug Invalid search results when searching",
983 " for $topic. Aborted.\n";
987 $id_map{__searches}{$username}{$topic} = $search->{max_id};
988 printf $fh "id:%d account:%s type:searchid topic:%s\n",
989 $search->{max_id}, $username, $topic;
991 foreach my $t ( reverse @{ $search->{results} } ) {
992 my $text = decode_entities( $t->{text} );
993 $text = &hilight($text);
994 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
995 $t->{id}, $username, $t->{from_user}, $topic, $text;
996 $new_poll_id = $t->{id}
998 or $t->{id} < $new_poll_id;
1003 print scalar localtime, " - Done" if &debug;
1010 my $filename = $data->[0];
1011 my $attempt = $data->[1];
1013 print scalar localtime, " - checking child log at $filename ($attempt)"
1015 my ($new_last_poll);
1017 # first time we run we don't want to print out *everything*, so we just
1020 if ( open FILE, $filename ) {
1024 last if /^__friends__/;
1025 unless (/\n$/) { # skip partial lines
1026 # print "Skipping partial line: $_" if &debug;
1033 foreach my $key (qw/id account nick type topic/) {
1034 if (s/^$key:(\S+)\s*//) {
1039 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1040 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1044 $new_cache{ $meta{id} } = time;
1046 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1052 $meta{account} =~ s/\@(\w+)$//;
1053 $meta{service} = $1;
1055 lc $meta{service} eq
1056 lc Irssi::settings_get_str("twirssi_default_service") )
1058 $account = "$meta{account}: "
1059 if lc "$meta{account}\@$meta{service}" ne lc
1060 "$user\@$defservice";
1062 $account = "$meta{account}\@$meta{service}: ";
1066 if ( $meta{type} ne 'dm'
1067 and Irssi::settings_get_bool("twirssi_track_replies")
1071 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1072 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1073 $id_map{__indexes}{ $meta{nick} } = $marker;
1074 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1075 $marker = ":$marker";
1079 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1080 my $nick = "\@$meta{account}";
1081 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1082 and Irssi::settings_get_bool("twirssi_hilights") )
1084 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1085 $hilight = MSGLEVEL_HILIGHT;
1088 if ( $meta{type} =~ /tweet|reply/ ) {
1091 ( MSGLEVEL_PUBLIC | $hilight ),
1092 $meta{type}, $account, $meta{nick}, $marker, $_
1094 } elsif ( $meta{type} eq 'search' ) {
1097 ( MSGLEVEL_PUBLIC | $hilight ),
1098 $meta{type}, $account, $meta{topic},
1099 $meta{nick}, $marker, $_
1102 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1104 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1106 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1109 } elsif ( $meta{type} eq 'dm' ) {
1112 ( MSGLEVEL_MSGS | $hilight ),
1113 $meta{type}, $account, $meta{nick}, $_
1115 } elsif ( $meta{type} eq 'searchid' ) {
1116 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1119 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1121 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1123 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1126 print "Search '$meta{topic}' returned invalid id $meta{id}";
1128 } elsif ( $meta{type} eq 'last_id' ) {
1129 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1131 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1133 } elsif ( $meta{type} eq 'error' ) {
1134 push @lines, [ MSGLEVEL_MSGS, $_ ];
1135 } elsif ( $meta{type} eq 'debug' ) {
1136 print "$_" if &debug,;
1138 print "Unknown line type $meta{type}: $_" if &debug,;
1144 if (/^__updated (\d+)$/) {
1145 $last_friends_poll = $1;
1146 print "Friend list updated" if &debug;
1151 ($new_last_poll) = ($1);
1154 my ( $f, $t ) = split ' ', $_;
1155 $nicks{$f} = $friends{$f} = $t;
1158 if ($new_last_poll) {
1159 print "new last_poll = $new_last_poll" if &debug;
1160 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1162 print "First call, not printing updates" if &debug;
1164 foreach my $line (@lines) {
1165 $window->printformat(
1167 "twirssi_" . $line->[1],
1168 @$line[ 2 .. $#$line ]
1175 or warn "Failed to remove $filename: $!"
1178 # commit the pending cache lines to the actual cache, now that
1179 # we've printed our output
1180 %tweet_cache = ( %tweet_cache, %new_cache );
1182 # keep enough cached tweets, to make sure we don't show duplicates.
1183 foreach ( keys %tweet_cache ) {
1184 next if $tweet_cache{$_} >= $last_poll - 3600;
1185 delete $tweet_cache{$_};
1187 $last_poll = $new_last_poll;
1192 Irssi::settings_get_str("twirssi_replies_store") )
1194 if ( open JSON, ">$file" ) {
1195 print JSON JSON::Any->objToJson( \%id_map );
1198 &ccrap("Failed to write replies to $file: $!");
1209 if ( $attempt < 24 ) {
1210 Irssi::timeout_add_once( 5000, 'monitor_child',
1211 [ $filename, $attempt + 1 ] );
1213 print "Giving up on polling $filename" if &debug;
1214 unlink $filename unless &debug;
1216 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1219 my @time = localtime($last_poll);
1220 if ( time - $last_poll < 24 * 60 * 60 ) {
1221 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1223 $since = scalar localtime($last_poll);
1226 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1231 q{ .--./ / | _.---.| },
1242 &ccrap("Haven't been able to get updated tweets since $since");
1247 return Irssi::settings_get_bool("twirssi_debug");
1251 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1255 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1261 if ( Irssi::settings_get_bool("tweet_to_away")
1263 and $data !~ /^[dD] / )
1266 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1268 $server->send_raw("away :$data");
1271 &ccrap( "Can't find bitlbee server.",
1272 "Update bitlbee_server or disable tweet_to_away" );
1282 my $noalert = shift;
1284 if ( length $data > 140 ) {
1285 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1293 sub valid_username {
1294 my $username = shift;
1296 $username = &normalize_username($username);
1298 unless ( exists $twits{$username} ) {
1299 ¬ice("Unknown username $username");
1309 ¬ice("Not logged in! Use /twitter_login username pass!");
1317 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1320 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1321 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1322 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1324 { # /twitter_reply gets a nick:num
1326 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1327 sort { $nicks{$b} <=> $nicks{$a} }
1329 keys %{ $id_map{__indexes} };
1332 if ( $linestart =~ /^\/twitter_unfriend\s*$/ )
1333 { # /twitter_unfriend gets a nick
1335 push @$complist, grep /^\Q$word/i,
1336 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1339 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1341 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1342 my $prefix = $word =~ s/^@//;
1343 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1344 push @$complist, grep /^\Q$word/i,
1345 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1346 @$complist = map { "\@$_" } @$complist if $prefix;
1350 sub event_send_text {
1351 my ( $line, $server, $win ) = @_;
1352 my $awin = Irssi::active_win();
1354 # if the window where we got our text was the twitter window, and the user
1355 # wants to be lazy, tweet away!
1356 if ( ( $awin->get_active_name() eq $window->{name} )
1357 and Irssi::settings_get_bool("tweet_window_input") )
1359 &cmd_tweet( $line, $server, $win );
1364 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1365 return $poll if $poll >= 60;
1372 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1373 my $c = Irssi::settings_get_str("twirssi_nick_color");
1374 $c = $irssi_to_mirc_colors{$c};
1375 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1377 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1378 my $c = Irssi::settings_get_str("twirssi_topic_color");
1379 $c = $irssi_to_mirc_colors{$c};
1380 $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1382 $text =~ s/[\n\r]/ /g;
1390 my $provider = Irssi::settings_get_str("short_url_provider");
1393 Irssi::settings_get_bool("twirssi_always_shorten")
1394 or &too_long( $data, 1 )
1400 if ( $provider eq 'Bitly' ) {
1401 @args[ 1, 2 ] = split ',',
1402 Irssi::settings_get_str("short_url_args"), 2;
1403 unless ( @args == 3 ) {
1405 "WWW::Shorten::Bitly requires a username and API key.",
1406 "Set short_url_args to username,API_key or change your",
1407 "short_url_provider."
1413 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1416 my $short = makeashorterlink(@args);
1418 $data =~ s/\Q$url/$short/g;
1420 ¬ice("Failed to shorten $url!");
1429 sub normalize_username {
1432 my ( $username, $service ) = split /\@/, $user, 2;
1434 $service = ucfirst lc $service;
1437 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1438 unless ( exists $twits{"$username\@$service"} ) {
1440 foreach my $t ( sort keys %twits ) {
1441 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1447 ¬ice("Can't find a logged in user '$user'");
1452 return "$username\@$service";
1455 Irssi::signal_add( "send text", "event_send_text" );
1457 Irssi::theme_register(
1459 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1460 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1461 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1462 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1463 'twirssi_error', 'ERROR: $0',
1467 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1468 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1469 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1470 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1471 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1472 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1473 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1474 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1475 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1476 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1477 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1478 'RT $n: "$t" ${-- $c$}' );
1479 Irssi::settings_add_str( "twirssi", "twirssi_location",
1480 ".irssi/scripts/twirssi.pl" );
1481 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1482 ".irssi/scripts/twirssi.json" );
1484 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1486 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1487 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1488 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1489 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1490 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1491 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1492 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1493 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1494 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1495 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1496 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1497 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1498 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1500 $last_poll = time - &get_poll_time;
1501 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1504 ->print( "Couldn't find a window named '"
1505 . Irssi::settings_get_str('twitter_window')
1506 . "', trying to create it." );
1508 Irssi::Windowitem::window_create(
1509 Irssi::settings_get_str('twitter_window'), 1 );
1510 $window->set_name( Irssi::settings_get_str('twitter_window') );
1514 Irssi::command_bind( "dm", "cmd_direct" );
1515 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1516 Irssi::command_bind( "tweet", "cmd_tweet" );
1517 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1518 Irssi::command_bind( "retweet", "cmd_retweet" );
1519 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1520 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1521 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1522 Irssi::command_bind( "twitter_login", "cmd_login" );
1523 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1524 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1525 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1526 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1527 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1528 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1529 Irssi::command_bind( "twitter_updates", "get_updates" );
1530 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1531 Irssi::command_bind( "reply", "cmd_reply" );
1532 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1534 Irssi::command_bind(
1537 print "twits: ", join ", ",
1538 map { "u: $_->{username}\@" . ref($_) } values %twits;
1539 print "selected: $user\@$defservice";
1540 print "friends: ", join ", ", sort keys %friends;
1541 print "nicks: ", join ", ", sort keys %nicks;
1542 print "searches: ", Dumper \%{ $id_map{__searches} };
1543 print "last poll: $last_poll";
1544 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1545 print DUMP Dumper \%tweet_cache;
1547 print "cache written out to /tmp/twirssi.cache.txt";
1551 Irssi::command_bind(
1554 ¬ice("Twirssi v$VERSION (r$REV); "
1555 . "Net::Twitter v$Net::Twitter::VERSION. "
1557 . JSON::Any::handler()
1558 . ". See details at http://twirssi.com/" );
1561 Irssi::command_bind(
1564 "/twitter_friend <username>",
1566 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1569 Irssi::command_bind(
1572 "/twitter_unfriend <username>",
1574 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1577 Irssi::command_bind(
1578 "twitter_device_updates",
1580 "/twitter_device_updates none|im|sms",
1581 "update_delivery_device",
1582 sub { ¬ice("Device updated to $_[0]"); }
1585 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1587 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1588 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1590 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1592 my $file = Irssi::settings_get_str("twirssi_replies_store");
1593 if ( $file and -r $file ) {
1594 if ( open( JSON, $file ) ) {
1599 my $ref = JSON::Any->jsonToObj($json);
1601 my $num = keys %{ $id_map{__indexes} };
1602 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1603 $num, ( $num == 1 ? "" : "s" ) );
1607 ¬ice("Failed to load old replies from $file: $!");
1611 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1612 ¬ice("Loading WWW::Shorten::$provider...");
1613 eval "use WWW::Shorten::$provider;";
1617 "Failed to load WWW::Shorten::$provider - either clear",
1618 "short_url_provider or install the CPAN module"
1623 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1624 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1632 ->print( "Create a window named "
1633 . Irssi::settings_get_str('twitter_window')
1634 . " or change the value of twitter_window. Then, reload twirssi." );
1637 # vim: set sts=4 expandtab: