10 $Data::Dumper::Indent = 1;
12 use vars qw($VERSION %IRSSI);
14 $VERSION = "2.3.4beta";
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-08-07 01:24:53 -0700 (Fri, 07 Aug 2009) $',
33 my $last_friends_poll = 0;
41 my %fix_replies_index;
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: $text");
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 my $modified = $data;
179 $data = &shorten($text);
181 return if $modified and &too_long($data);
187 $success = $twits{$username}->update(
191 # in_reply_to_status_id => $id_map{ lc $nick }[$id]
196 $twits{$username}->retweet( { id => $id_map{ lc $nick }[$id] } );
197 $success = $success->{id} if ref $success;
199 ¬ice("Update failed") unless $success;
201 return unless $success;
204 ¬ice("Update caused an error: $@. Aborted");
208 foreach ( $data =~ /@([-\w]+)/ ) {
212 ¬ice("Retweet sent");
216 my ( $data, $server, $win ) = @_;
218 return unless &logged_in($twit);
220 $data =~ s/^\s+|\s+$//;
222 ¬ice("Usage: /tweet <update>");
226 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
230 my ( $data, $server, $win ) = @_;
232 return unless &logged_in($twit);
234 $data =~ s/^\s+|\s+$//;
235 $data =~ s/\s\s+/ /g;
236 my ( $username, $data ) = split ' ', $data, 2;
238 unless ( $username and $data ) {
239 ¬ice("Usage: /tweet_as <username> <update>");
243 return unless $username = &valid_username($username);
245 $data = &shorten($data);
247 return if &too_long($data);
251 unless ( $twits{$username}->update($data) )
253 ¬ice("Update failed");
257 return unless $success;
260 ¬ice("Update caused an error: $@. Aborted.");
264 foreach ( $data =~ /@([-\w]+)/ ) {
268 my $away = &update_away($data);
270 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
274 my ( $data, $server, $win ) = @_;
276 return unless &logged_in($twit);
278 $data =~ s/^\s+|\s+$//;
280 ¬ice("Usage: /reply <nick[:num]> <update>");
284 my ( $id, $data ) = split ' ', $data, 2;
285 unless ( $id and $data ) {
286 ¬ice("Usage: /reply <nick[:num]> <update>");
290 &cmd_reply_as( "$user $id $data", $server, $win );
294 my ( $data, $server, $win ) = @_;
296 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
297 ¬ice("twirssi_track_replies is required in order to reply to "
298 . "specific tweets. Either enable it, or just use /tweet "
299 . "\@username <text>." );
303 return unless &logged_in($twit);
305 $data =~ s/^\s+|\s+$//;
306 my ( $username, $id, $data ) = split ' ', $data, 3;
308 unless ( $username and $data ) {
309 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
313 return unless $username = &valid_username($username);
316 $id =~ s/[^\w\d\-:]+//g;
317 ( $nick, $id ) = split /:/, $id;
318 unless ( exists $id_map{ lc $nick } ) {
319 ¬ice("Can't find a tweet from $nick to reply to!");
323 $id = $id_map{__indexes}{$nick} unless $id;
324 unless ( $id_map{ lc $nick }[$id] ) {
325 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
329 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
331 # remove any @nick at the beginning of the reply, as we'll add it anyway
332 $data =~ s/^\s*\@?$nick\s*//;
333 $data = "\@$nick " . $data;
336 $data = &shorten($data);
338 return if &too_long($data);
343 $twits{$username}->update(
346 in_reply_to_status_id => $id_map{ lc $nick }[$id]
351 ¬ice("Update failed");
355 return unless $success;
358 ¬ice("Update caused an error: $@. Aborted");
362 foreach ( $data =~ /@([-\w]+)/ ) {
366 my $away = &update_away($data);
368 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
372 my ( $usage_str, $api_name, $post_ref ) = @_;
375 my ( $data, $server, $win ) = @_;
377 return unless &logged_in($twit);
379 $data =~ s/^\s+|\s+$//;
381 ¬ice("Usage: $usage_str");
387 unless ( $twit->$api_name($data) )
389 ¬ice("$api_name failed");
393 return unless $success;
396 ¬ice("$api_name caused an error. Aborted.");
400 &$post_ref($data) if $post_ref;
405 my ( $data, $server, $win ) = @_;
407 $data =~ s/^\s+|\s+$//g;
408 $data = &normalize_username($data);
409 if ( exists $twits{$data} ) {
410 ¬ice("Switching to $data");
411 $twit = $twits{$data};
412 if ( $data =~ /(.*)\@(.*)/ ) {
416 ¬ice("Couldn't figure out what service '$data' is on");
419 ¬ice("Unknown user $data");
424 my ( $data, $server, $win ) = @_;
426 $data =~ s/^\s+|\s+$//g;
427 $data = $user unless $data;
428 return unless $data = &valid_username($data);
430 ¬ice("Logging out $data...");
431 $twits{$data}->end_session();
432 delete $twits{$data};
435 &cmd_switch( ( keys %twits )[0], $server, $win );
437 Irssi::timeout_remove($poll) if $poll;
443 my ( $data, $server, $win ) = @_;
446 ( $user, $pass ) = split ' ', $data, 2;
448 ¬ice("usage: /twitter_login <username>[\@<service>] <password>");
451 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
452 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
454 my @user = split /\s*,\s*/, $autouser;
455 my @pass = split /\s*,\s*/, $autopass;
457 # if a password ends with a '\', it was meant to escape the comma, and
458 # it should be concatinated with the next one
462 while ( $p =~ /\\$/ and @pass ) {
463 $p .= "," . shift @pass;
468 if ( @user != @unescaped ) {
469 ¬ice("Number of usernames doesn't match "
470 . "the number of passwords - auto-login failed" );
473 while ( @user and @unescaped ) {
475 $p = shift @unescaped;
481 ¬ice("/twitter_login requires either a username and password "
482 . "or twitter_usernames and twitter_passwords to be set." );
486 %friends = %nicks = ();
489 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
490 ( $user, $service ) = ( $1, $2 );
492 $service = Irssi::settings_get_str("twirssi_default_service");
494 $defservice = $service = ucfirst lc $service;
496 eval "use Net::$service 3.05";
499 "Failed to load Net::$service when trying to log in as $user: $@");
503 $twit = "Net::$service"->new(
507 ssl => Irssi::settings_get_bool("twirssi_avoid_ssl") ? 0 : 1,
511 ¬ice("Failed to create Net::$service object! Aborting.");
515 if ( my $timeout = Irssi::settings_get_int("twitter_timeout")
516 and $twit->can('ua') )
518 $twit->ua->timeout($timeout);
519 ¬ice("Twitter timeout set to $timeout");
522 unless ( $twit->verify_credentials() ) {
523 ¬ice("Login as $user\@$service failed");
525 if ( not Irssi::settings_get_bool("twirssi_avoid_ssl") ) {
527 "It's possible you're missing one of the modules required for "
528 . "SSL logins. Try setting twirssi_avoid_ssl to on. See "
529 . "http://cpansearch.perl.org/src/GAAS/libwww-perl-5.831/README.SSL "
530 . "for the detailed requirements." );
535 &cmd_switch( ( keys %twits )[0], $server, $win );
541 my $rate_limit = $twit->rate_limit_status();
542 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
544 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
550 $twits{"$user\@$service"} = $twit;
551 Irssi::timeout_remove($poll) if $poll;
552 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
553 ¬ice("Logged in as $user\@$service, loading friends list...");
555 ¬ice( "loaded friends: ", scalar keys %friends );
556 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
557 Irssi::settings_set_bool( "twirssi_first_run", 0 );
563 ¬ice("Login failed");
568 my ( $data, $server, $win ) = @_;
571 ¬ice("Usage: /twitter_add_follow_extra <username>");
575 $data =~ s/^\s+|\s+$//;
579 if ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
580 ¬ice("Already following all replies by \@$data");
584 $id_map{__fixreplies}{"$user\@$defservice"}{$data} = 1;
585 ¬ice("Will now follow all replies by \@$data");
589 my ( $data, $server, $win ) = @_;
592 ¬ice("Usage: /twitter_del_follow_extra <username>");
596 $data =~ s/^\s+|\s+$//;
600 unless ( exists $id_map{__fixreplies}{"$user\@$defservice"}{$data} ) {
601 ¬ice("Wasn't following all replies by \@$data");
605 delete $id_map{__fixreplies}{"$user\@$defservice"}{$data};
606 ¬ice("Will no longer follow all replies by \@$data");
609 sub cmd_list_follow {
610 my ( $data, $server, $win ) = @_;
613 foreach my $suser ( sort keys %{ $id_map{__fixreplies} } ) {
615 foreach my $fruser ( sort keys %{ $id_map{__fixreplies}{$suser} } ) {
616 $frusers = $frusers ? "$frusers, $fruser" : $fruser;
620 ¬ice("Following all replies as \@$suser: $frusers");
625 ¬ice("Not following all replies by anyone");
630 my ( $data, $server, $win ) = @_;
632 unless ( $twit and $twit->can('search') ) {
633 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
634 . "doesn't support searches." );
638 $data =~ s/^\s+|\s+$//;
642 ¬ice("Usage: /twitter_subscribe <topic>");
646 if ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
647 ¬ice("Already had a subscription for '$data'");
651 $id_map{__searches}{"$user\@$defservice"}{$data} = 1;
652 ¬ice("Added subscription for '$data'");
656 my ( $data, $server, $win ) = @_;
658 unless ( $twit and $twit->can('search') ) {
659 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
660 . "doesn't support searches." );
663 $data =~ s/^\s+|\s+$//;
667 ¬ice("Usage: /twitter_unsubscribe <topic>");
671 unless ( exists $id_map{__searches}{"$user\@$defservice"}{$data} ) {
672 ¬ice("No subscription found for '$data'");
676 delete $id_map{__searches}{"$user\@$defservice"}{$data};
677 ¬ice("Removed subscription for '$data'");
680 sub cmd_list_search {
681 my ( $data, $server, $win ) = @_;
684 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
686 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
687 $topics = $topics ? "$topics, $topic" : $topic;
691 ¬ice("Search subscriptions for \@$suser: $topics");
696 ¬ice("No search subscriptions set up");
701 my ( $data, $server, $win ) = @_;
703 my $loc = Irssi::settings_get_str("twirssi_location");
705 ¬ice("$loc isn't writable, can't upgrade."
706 . " Perhaps you need to /set twirssi_location?" );
711 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
712 eval { use Digest::MD5; };
715 ¬ice("Failed to load Digest::MD5."
716 . " Try '/twirssi_upgrade nomd5' to skip MD5 verification" );
720 $md5 = get("http://twirssi.com/md5sum");
724 ¬ice("Failed to download md5sum from peeron! Aborting.");
728 unless ( open( CUR, $loc ) ) {
729 ¬ice("Failed to read $loc."
730 . " Check that /set twirssi_location is set to the correct location."
735 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
738 if ( $cur_md5 eq $md5 ) {
739 ¬ice("Current twirssi seems to be up to date.");
745 Irssi::settings_get_bool("twirssi_upgrade_beta")
746 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
747 : "http://twirssi.com/twirssi.pl";
748 ¬ice("Downloading twirssi from $URL");
749 LWP::Simple::getstore( $URL, "$loc.upgrade" );
751 unless ( -s "$loc.upgrade" ) {
752 ¬ice("Failed to save $loc.upgrade."
753 . " Check that /set twirssi_location is set to the correct location."
758 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
759 unless ( open( NEW, "$loc.upgrade" ) ) {
760 ¬ice("Failed to read $loc.upgrade."
761 . " Check that /set twirssi_location is set to the correct location."
766 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
769 if ( $new_md5 ne $md5 ) {
770 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
775 rename $loc, "$loc.backup"
776 or ¬ice("Failed to back up $loc: $!. Aborting")
778 rename "$loc.upgrade", $loc
779 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
782 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
783 if ( -e "$dir/autorun/$file" ) {
784 ¬ice("Updating $dir/autorun/$file");
785 unlink "$dir/autorun/$file"
786 or ¬ice("Failed to remove old $file from autorun: $!");
787 symlink "../$file", "$dir/autorun/$file"
788 or ¬ice("Failed to create symlink in autorun directory: $!");
791 ¬ice("Download complete. Reload twirssi with /script load $file");
800 while ( $page < 11 and $cursor ne "0" )
802 print $fh "type:debug Loading friends page $page...\n"
803 if ( $fh and &debug );
805 if ( ref $twit =~ /^Net::Twitter/ ) {
806 $friends = $twit->friends( { cursor => $cursor } );
807 last unless $friends;
808 $cursor = $friends->{next_cursor};
809 $friends = $friends->{users};
811 $friends = $twit->friends( { page => $page } );
812 last unless $friends;
814 $new_friends{ $_->{screen_name} } = time foreach @$friends;
820 print $fh "type:debug Error during friends list update. Aborted.\n";
824 my ( $added, $removed ) = ( 0, 0 );
825 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
826 foreach ( keys %new_friends ) {
827 next if exists $friends{$_};
832 print $fh "type:debug Scanning for removed friends...\n"
833 if ( $fh and &debug );
834 foreach ( keys %friends ) {
835 next if exists $new_friends{$_};
840 return ( $added, $removed );
844 print scalar localtime, " - get_updates starting" if &debug;
847 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
850 ->print( "Can't find a window named '"
851 . Irssi::settings_get_str('twitter_window')
852 . "'. Create it or change the value of twitter_window" );
855 return unless &logged_in($twit);
857 my ( $fh, $filename ) = File::Temp::tempfile();
858 binmode( $fh, ":utf8" );
861 if ($child_pid) { # parent
862 Irssi::timeout_add_once( 5000, 'monitor_child',
863 [ "$filename.done", 0 ] );
864 Irssi::pidwait_add($child_pid);
865 } elsif ( defined $child_pid ) { # child
874 foreach ( keys %twits ) {
875 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
877 if ( $id_map{__fixreplies}{$_} ) {
878 my @frusers = sort keys %{ $id_map{__fixreplies}{$_} };
881 unless &get_timeline( $fh, $frusers[ $fix_replies_index{$_} ],
882 $_, $twits{$_}, \%context_cache );
884 $fix_replies_index{$_}++;
885 $fix_replies_index{$_} = 0
886 if $fix_replies_index{$_} >= @frusers;
887 print $fh "id:$fix_replies_index{$_} ",
888 "account:$_ type:fix_replies_index\n";
892 print $fh "__friends__\n";
894 time - $last_friends_poll >
895 Irssi::settings_get_int('twitter_friends_poll') )
897 print $fh "__updated ", time, "\n";
898 my ( $added, $removed ) = &load_friends($fh);
899 if ( $added + $removed ) {
900 print $fh "type:debug %R***%n Friends list updated: ",
902 sprintf( "%d added", $added ),
903 sprintf( "%d removed", $removed ) ),
908 foreach ( sort keys %friends ) {
909 print $fh "$_ $friends{$_}\n";
913 print $fh "type:debug Update encountered errors. Aborted\n";
914 print $fh "-- $last_poll";
916 print $fh "-- $new_poll";
919 rename $filename, "$filename.done";
922 &ccrap("Failed to fork for updating: $!");
924 print scalar localtime, " - get_updates ends" if &debug;
928 my ( $fh, $username, $obj, $cache ) = @_;
930 my $rate_limit = $obj->rate_limit_status();
931 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
932 ¬ice("Rate limit exceeded for $username");
936 print scalar localtime, " - Polling for updates for $username" if &debug;
940 if ( $id_map{__last_id}{$username}{timeline} )
942 $tweets = $obj->home_timeline( { count => 100 } );
944 $tweets = $obj->home_timeline();
949 print $fh "type:debug Error during home_timeline call: Aborted.\n";
950 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
954 unless ( ref $tweets ) {
955 if ( $obj->can("get_error") ) {
956 my $error = "Unknown error";
957 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
958 unless ($@) { $error = $obj->get_error() }
960 "type:debug API Error during home_timeline call: Aborted\n";
961 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
965 "type:debug API Error during home_timeline call. Aborted.\n";
970 foreach my $t ( reverse @$tweets ) {
971 my $text = &get_text( $t, $obj );
973 if ( Irssi::settings_get_bool("show_reply_context")
974 and $t->{in_reply_to_screen_name} ne $username
975 and $t->{in_reply_to_screen_name}
976 and not exists $friends{ $t->{in_reply_to_screen_name} } )
978 $nicks{ $t->{in_reply_to_screen_name} } = time;
980 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
982 $cache->{ $t->{in_reply_to_status_id} } =
983 $obj->show_status( $t->{in_reply_to_status_id} );
987 $context = $cache->{ $t->{in_reply_to_status_id} };
990 my $ctext = &get_text( $context, $obj );
991 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
992 $context->{id}, $username,
993 $context->{user}{screen_name}, $ctext;
998 if $t->{user}{screen_name} eq $username
999 and not Irssi::settings_get_bool("show_own_tweets");
1000 printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1001 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1002 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1004 printf $fh "id:%s account:%s type:last_id timeline\n",
1005 $new_poll_id, $username;
1007 print scalar localtime, " - Polling for replies since ",
1008 $id_map{__last_id}{$username}{reply}
1012 if ( $id_map{__last_id}{$username}{reply} )
1014 $tweets = $obj->replies(
1015 { since_id => $id_map{__last_id}{$username}{reply} } )
1018 $tweets = $obj->replies() || [];
1023 print $fh "type:debug Error during replies call. Aborted.\n";
1027 foreach my $t ( reverse @$tweets ) {
1029 if exists $friends{ $t->{user}{screen_name} };
1031 my $text = &get_text( $t, $obj );
1032 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1033 $t->{id}, $username, $t->{user}{screen_name}, $text;
1034 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1036 printf $fh "id:%s account:%s type:last_id reply\n", $new_poll_id, $username;
1038 print scalar localtime, " - Polling for DMs" if &debug;
1041 if ( $id_map{__last_id}{$username}{dm} )
1043 $tweets = $obj->direct_messages(
1044 { since_id => $id_map{__last_id}{$username}{dm} } )
1047 $tweets = $obj->direct_messages() || [];
1052 print $fh "type:debug Error during direct_messages call. Aborted.\n";
1056 foreach my $t ( reverse @$tweets ) {
1057 my $text = decode_entities( $t->{text} );
1058 $text =~ s/[\n\r]/ /g;
1059 printf $fh "id:%s account:%s nick:%s type:dm %s\n",
1060 $t->{id}, $username, $t->{sender_screen_name}, $text;
1061 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
1063 printf $fh "id:%s account:%s type:last_id dm\n", $new_poll_id, $username;
1065 print scalar localtime, " - Polling for subscriptions" if &debug;
1066 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
1068 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
1069 print $fh "type:debug searching for $topic since ",
1070 "$id_map{__searches}{$username}{$topic}\n";
1072 $search = $obj->search(
1075 since_id => $id_map{__searches}{$username}{$topic}
1082 "type:debug Error during search($topic) call. Aborted.\n";
1086 unless ( $search->{max_id} ) {
1087 print $fh "type:debug Invalid search results when searching",
1088 " for $topic. Aborted.\n";
1092 $id_map{__searches}{$username}{$topic} = $search->{max_id};
1093 printf $fh "id:%s account:%s type:searchid topic:%s\n",
1094 $search->{max_id}, $username, $topic;
1096 foreach my $t ( reverse @{ $search->{results} } ) {
1097 my $text = &get_text( $t, $obj );
1098 printf $fh "id:%s account:%s nick:%s type:search topic:%s %s\n",
1099 $t->{id}, $username, $t->{from_user}, $topic, $text;
1100 $new_poll_id = $t->{id}
1102 or $t->{id} < $new_poll_id;
1107 print scalar localtime, " - Done" if &debug;
1113 my ( $fh, $target, $username, $obj, $cache ) = @_;
1115 my $last_id = $id_map{__last_id}{$username}{$target};
1117 print $fh "type:debug get_timeline("
1118 . "$fix_replies_index{$username}=$target > $last_id) started."
1119 . " username = $username\n";
1121 $tweets = $obj->user_timeline(
1124 ( $last_id ? ( since_id => $last_id ) : () ),
1131 "type:debug Error during user_timeline($target) call: Aborted.\n";
1132 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
1138 "type:debug user_timeline($target) call returned undef! Aborted\n";
1142 foreach my $t ( reverse @$tweets ) {
1143 my $text = &get_text( $t, $obj );
1144 my $reply = "tweet";
1145 if ( Irssi::settings_get_bool("show_reply_context")
1146 and $t->{in_reply_to_screen_name} ne $username
1147 and $t->{in_reply_to_screen_name}
1148 and not exists $friends{ $t->{in_reply_to_screen_name} } )
1150 $nicks{ $t->{in_reply_to_screen_name} } = time;
1152 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
1154 $cache->{ $t->{in_reply_to_status_id} } =
1155 $obj->show_status( $t->{in_reply_to_status_id} );
1159 $context = $cache->{ $t->{in_reply_to_status_id} };
1162 my $ctext = &get_text( $context, $obj );
1163 printf $fh "id:%s account:%s nick:%s type:tweet %s\n",
1164 $context->{id}, $username,
1165 $context->{user}{screen_name}, $ctext;
1169 printf $fh "id:%s account:%s nick:%s type:%s %s\n",
1170 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
1171 $last_id = $t->{id} if $last_id < $t->{id};
1173 printf $fh "id:%s account:%s type:last_id_fixreplies %s\n",
1174 $last_id, $username, $target;
1181 my $filename = $data->[0];
1182 my $attempt = $data->[1];
1184 print scalar localtime, " - checking child log at $filename ($attempt)"
1186 my ($new_last_poll);
1188 # first time we run we don't want to print out *everything*, so we just
1191 if ( open FILE, $filename ) {
1192 binmode FILE, ":utf8";
1196 last if /^__friends__/;
1197 unless (/\n$/) { # skip partial lines
1198 # print "Skipping partial line: $_" if &debug;
1205 foreach my $key (qw/id account nick type topic/) {
1206 if (s/^$key:(\S+)\s*//) {
1211 if ( $meta{type} and $meta{type} eq 'fix_replies_index' ) {
1212 $fix_replies_index{ $meta{account} } = $meta{id};
1213 print "fix_replies_index for $meta{account} set to $meta{id}"
1218 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1219 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1223 $new_cache{ $meta{id} } = time;
1225 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1231 $meta{account} =~ s/\@(\w+)$//;
1232 $meta{service} = $1;
1234 lc $meta{service} eq
1235 lc Irssi::settings_get_str("twirssi_default_service") )
1237 $account = "$meta{account}: "
1238 if lc "$meta{account}\@$meta{service}" ne lc
1239 "$user\@$defservice";
1241 $account = "$meta{account}\@$meta{service}: ";
1245 if ( $meta{type} ne 'dm'
1246 and Irssi::settings_get_bool("twirssi_track_replies")
1250 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1251 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1252 $id_map{__indexes}{ $meta{nick} } = $marker;
1253 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1254 $marker = ":$marker";
1258 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1259 my $nick = "\@$meta{account}";
1260 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1261 and Irssi::settings_get_bool("twirssi_hilights") )
1263 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1264 $hilight = MSGLEVEL_HILIGHT;
1267 if ( $meta{type} =~ /tweet|reply/ ) {
1270 ( MSGLEVEL_PUBLIC | $hilight ),
1271 $meta{type}, $account, $meta{nick}, $marker, $_
1273 } elsif ( $meta{type} eq 'search' ) {
1276 ( MSGLEVEL_PUBLIC | $hilight ),
1277 $meta{type}, $account, $meta{topic},
1278 $meta{nick}, $marker, $_
1281 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1283 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1285 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1288 } elsif ( $meta{type} eq 'dm' ) {
1291 ( MSGLEVEL_MSGS | $hilight ),
1292 $meta{type}, $account, $meta{nick}, $_
1294 } elsif ( $meta{type} eq 'searchid' ) {
1295 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1298 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1300 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1302 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1305 print "Search '$meta{topic}' returned invalid id $meta{id}";
1307 } elsif ( $meta{type} eq 'last_id' ) {
1308 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1310 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1312 } elsif ( $meta{type} eq 'last_id_fixreplies' ) {
1313 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1315 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1317 } elsif ( $meta{type} eq 'error' ) {
1318 push @lines, [ MSGLEVEL_MSGS, $_ ];
1319 } elsif ( $meta{type} eq 'debug' ) {
1320 print "$_" if &debug,;
1322 print "Unknown line type $meta{type}: $_" if &debug,;
1328 if (/^__updated (\d+)$/) {
1329 $last_friends_poll = $1;
1330 print "Friend list updated" if &debug;
1335 $new_last_poll = $1;
1336 if ( $new_last_poll >= $last_poll ) {
1339 print "Impossible! ",
1340 "new_last_poll=$new_last_poll < last_poll=$last_poll!"
1342 undef $new_last_poll;
1346 my ( $f, $t ) = split ' ', $_;
1347 $nicks{$f} = $friends{$f} = $t;
1350 if ($new_last_poll) {
1351 print "new last_poll = $new_last_poll" if &debug;
1352 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1354 print "First call, not printing updates" if &debug;
1356 foreach my $line (@lines) {
1357 $window->printformat(
1359 "twirssi_" . $line->[1],
1360 @$line[ 2 .. $#$line - 1 ],
1361 &hilight( $line->[-1] )
1368 or warn "Failed to remove $filename: $!"
1371 # commit the pending cache lines to the actual cache, now that
1372 # we've printed our output
1373 %tweet_cache = ( %tweet_cache, %new_cache );
1375 # keep enough cached tweets, to make sure we don't show duplicates.
1376 foreach ( keys %tweet_cache ) {
1377 next if $tweet_cache{$_} >= $last_poll - 3600;
1378 delete $tweet_cache{$_};
1380 $last_poll = $new_last_poll;
1382 # make sure the pid is removed from the waitpid list
1383 Irssi::pidwait_remove($child_pid);
1385 # and that we don't leave any zombies behind, somehow
1391 Irssi::settings_get_str("twirssi_replies_store") )
1393 if ( open JSON, ">$file" ) {
1394 print JSON JSON::Any->objToJson( \%id_map );
1397 &ccrap("Failed to write replies to $file: $!");
1408 if ( $attempt < 24 ) {
1409 Irssi::timeout_add_once( 5000, 'monitor_child',
1410 [ $filename, $attempt + 1 ] );
1412 print "Giving up on polling $filename" if &debug;
1413 Irssi::pidwait_remove($child_pid);
1415 unlink $filename unless &debug;
1417 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1420 my @time = localtime($last_poll);
1421 if ( time - $last_poll < 24 * 60 * 60 ) {
1422 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1424 $since = scalar localtime($last_poll);
1427 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1432 q{ .--./ / | _.---.| },
1444 if ( time - $last_poll < 600 ) {
1445 &ccrap("Haven't been able to get updated tweets since $since");
1451 return Irssi::settings_get_bool("twirssi_debug");
1455 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1459 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1465 if ( Irssi::settings_get_bool("tweet_to_away")
1467 and $data !~ /^[dD] / )
1470 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1472 $server->send_raw("away :$data");
1475 &ccrap( "Can't find bitlbee server.",
1476 "Update bitlbee_server or disable tweet_to_away" );
1486 my $noalert = shift;
1488 if ( length $data > 140 ) {
1489 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1497 sub valid_username {
1498 my $username = shift;
1500 $username = &normalize_username($username);
1502 unless ( exists $twits{$username} ) {
1503 ¬ice("Unknown username $username");
1513 ¬ice("Not logged in! Use /twitter_login username pass!");
1521 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1524 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1525 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1526 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1528 { # /twitter_reply gets a nick:num
1530 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1531 sort { $nicks{$b} <=> $nicks{$a} }
1533 keys %{ $id_map{__indexes} };
1537 /^\/(twitter_unfriend|twitter_add_follow_extra|twitter_del_follow_extra)\s*$/
1539 { # /twitter_unfriend gets a nick
1541 push @$complist, grep /^\Q$word/i,
1542 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1545 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1547 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1548 my $prefix = $word =~ s/^@//;
1549 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1550 push @$complist, grep /^\Q$word/i,
1551 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1552 @$complist = map { "\@$_" } @$complist if $prefix;
1556 sub event_send_text {
1557 my ( $line, $server, $win ) = @_;
1558 my $awin = Irssi::active_win();
1560 # if the window where we got our text was the twitter window, and the user
1561 # wants to be lazy, tweet away!
1562 if ( ( $awin->get_active_name() eq $window->{name} )
1563 and Irssi::settings_get_bool("tweet_window_input") )
1565 &cmd_tweet( $line, $server, $win );
1570 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1571 return $poll if $poll >= 60;
1578 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1579 my $c = Irssi::settings_get_str("twirssi_nick_color");
1580 $c = $irssi_to_mirc_colors{$c};
1581 $text =~ s/(^|\W)\@(\w+)/$1\cC$c\@$2\cO/g if $c;
1583 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1584 my $c = Irssi::settings_get_str("twirssi_topic_color");
1585 $c = $irssi_to_mirc_colors{$c};
1586 $text =~ s/(^|\W)(\#|\!)([-\w]+)/$1\cC$c$2$3\cO/g if $c;
1588 $text =~ s/[\n\r]/ /g;
1596 my $provider = Irssi::settings_get_str("short_url_provider");
1599 Irssi::settings_get_bool("twirssi_always_shorten")
1600 or &too_long( $data, 1 )
1606 if ( $provider eq 'Bitly' ) {
1607 @args[ 1, 2 ] = split ',',
1608 Irssi::settings_get_str("short_url_args"), 2;
1609 unless ( @args == 3 ) {
1611 "WWW::Shorten::Bitly requires a username and API key.",
1612 "Set short_url_args to username,API_key or change your",
1613 "short_url_provider."
1615 return decode "utf8", $data;
1619 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1622 my $short = makeashorterlink(@args);
1624 $data =~ s/\Q$url/$short/g;
1626 ¬ice("Failed to shorten $url!");
1632 return decode "utf8", $data;
1635 sub normalize_username {
1638 my ( $username, $service ) = split /\@/, $user, 2;
1640 $service = ucfirst lc $service;
1643 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1644 unless ( exists $twits{"$username\@$service"} ) {
1646 foreach my $t ( sort keys %twits ) {
1647 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1653 ¬ice("Can't find a logged in user '$user'");
1658 return "$username\@$service";
1664 my $text = decode_entities( $tweet->{text} );
1665 if ( $tweet->{truncated} ) {
1666 if ( exists $tweet->{retweeted_status} ) {
1667 $text = "RT $tweet->{retweeted_status}{user}{screen_name}: "
1668 . "$tweet->{retweeted_status}{text}";
1669 } elsif ( $object->isa('Net::Twitter') ) {
1670 $text .= " -- http://twitter.com/$tweet->{user}{screen_name}"
1671 . "/status/$tweet->{id}";
1675 $text =~ s/[\n\r]/ /g;
1680 Irssi::signal_add( "send text", "event_send_text" );
1682 Irssi::theme_register(
1684 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1685 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1686 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1687 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1688 'twirssi_error', 'ERROR: $0',
1692 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1693 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1694 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1695 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1696 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1697 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1698 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1699 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1700 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1701 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1702 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1703 'RT $n: "$t" ${-- $c$}' );
1704 Irssi::settings_add_str( "twirssi", "twirssi_location",
1705 ".irssi/scripts/twirssi.pl" );
1706 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1707 ".irssi/scripts/twirssi.json" );
1709 Irssi::settings_add_int( "twirssi", "twitter_friends_poll", 600 );
1710 Irssi::settings_add_int( "twirssi", "twitter_timeout", 30 );
1712 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1713 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1714 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1715 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1716 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1717 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1718 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1719 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1720 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1721 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1722 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1723 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1724 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1725 Irssi::settings_add_bool( "twirssi", "twirssi_avoid_ssl", 0 );
1727 $last_poll = time - &get_poll_time;
1728 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1731 ->print( "Couldn't find a window named '"
1732 . Irssi::settings_get_str('twitter_window')
1733 . "', trying to create it." );
1735 Irssi::Windowitem::window_create(
1736 Irssi::settings_get_str('twitter_window'), 1 );
1737 $window->set_name( Irssi::settings_get_str('twitter_window') );
1741 Irssi::command_bind( "dm", "cmd_direct" );
1742 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1743 Irssi::command_bind( "tweet", "cmd_tweet" );
1744 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1745 Irssi::command_bind( "retweet", "cmd_retweet" );
1746 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1747 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1748 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1749 Irssi::command_bind( "twitter_login", "cmd_login" );
1750 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1751 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1752 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1753 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1754 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1755 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1756 Irssi::command_bind( "twitter_updates", "get_updates" );
1757 Irssi::command_bind( "twitter_add_follow_extra", "cmd_add_follow" );
1758 Irssi::command_bind( "twitter_del_follow_extra", "cmd_del_follow" );
1759 Irssi::command_bind( "twitter_list_follow_extra", "cmd_list_follow" );
1760 Irssi::command_bind( "bitlbee_away", "update_away" );
1761 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1762 Irssi::command_bind( "reply", "cmd_reply" );
1763 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1765 Irssi::command_bind(
1768 print "twits: ", join ", ",
1769 map { "u: $_->{username}\@" . ref($_) } values %twits;
1770 print "selected: $user\@$defservice";
1771 print "friends: ", join ", ", sort keys %friends;
1772 print "nicks: ", join ", ", sort keys %nicks;
1773 print "searches: ", Dumper \%{ $id_map{__searches} };
1774 print "last poll: $last_poll";
1775 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1776 print DUMP Dumper \%tweet_cache;
1778 print "cache written out to /tmp/twirssi.cache.txt";
1782 Irssi::command_bind(
1786 "Twirssi v$VERSION; "
1788 $Net::Twitter::VERSION
1789 ? "Net::Twitter v$Net::Twitter::VERSION. "
1793 $Net::Identica::VERSION
1794 ? "Net::Identica v$Net::Identica::VERSION. "
1798 . JSON::Any::handler()
1799 . ". See details at http://twirssi.com/"
1803 Irssi::command_bind(
1806 "/twitter_follow <username>",
1808 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1811 Irssi::command_bind(
1814 "/twitter_unfriend <username>",
1816 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1819 Irssi::command_bind(
1820 "twitter_device_updates",
1822 "/twitter_device_updates none|im|sms",
1823 "update_delivery_device",
1824 sub { ¬ice("Device updated to $_[0]"); }
1827 Irssi::command_bind(
1830 "/twitter_block <username>",
1832 sub { ¬ice("Blocked $_[0]"); }
1835 Irssi::command_bind(
1838 "/twitter_unblock <username>",
1840 sub { ¬ice("Unblock $_[0]"); }
1843 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1845 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N");
1846 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1848 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1850 my $file = Irssi::settings_get_str("twirssi_replies_store");
1851 if ( $file and -r $file ) {
1852 if ( open( JSON, $file ) ) {
1857 my $ref = JSON::Any->jsonToObj($json);
1859 my $num = keys %{ $id_map{__indexes} };
1860 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1861 $num, ( $num == 1 ? "" : "s" ) );
1866 ¬ice("Failed to load old replies from $file: $!");
1870 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1871 ¬ice("Loading WWW::Shorten::$provider...");
1872 eval "use WWW::Shorten::$provider;";
1876 "Failed to load WWW::Shorten::$provider - either clear",
1877 "short_url_provider or install the CPAN module"
1882 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1883 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1891 ->print( "Create a window named "
1892 . Irssi::settings_get_str('twitter_window')
1893 . " or change the value of twitter_window. Then, reload twirssi." );
1896 # vim: set sts=4 expandtab: