9 $Data::Dumper::Indent = 1;
11 use vars qw($VERSION %IRSSI);
13 $VERSION = "2.2.1beta";
14 my ($REV) = '$Rev: 610 $' =~ /(\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-10 23:30:55 -0700 (Fri, 10 Apr 2009) $',
38 my %irssi_to_mirc_colors = (
58 my ( $data, $server, $win ) = @_;
60 return unless &logged_in($twit);
62 my ( $target, $text ) = split ' ', $data, 2;
63 unless ( $target and $text ) {
64 ¬ice("Usage: /dm <nick> <message>");
68 &cmd_direct_as( "$user $data", $server, $win );
72 my ( $data, $server, $win ) = @_;
74 return unless &logged_in($twit);
76 my ( $username, $target, $text ) = split ' ', $data, 3;
77 unless ( $username and $target and $text ) {
78 ¬ice("Usage: /dm_as <username> <nick> <message>");
82 return unless $username = &valid_username($username);
85 if ( $twits{$username}
86 ->new_direct_message( { user => $target, text => $text } ) )
88 ¬ice("DM sent to $target");
89 $nicks{$target} = time;
93 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
94 $error = $error->{error};
97 ¬ice("DM to $target failed");
102 ¬ice("DM caused an error: $@");
108 my ( $data, $server, $win ) = @_;
110 return unless &logged_in($twit);
112 $data =~ s/^\s+|\s+$//;
114 ¬ice("Usage: /retweet <nick[:num]> [comment]");
118 my ( $id, $data ) = split ' ', $data, 2;
120 &cmd_retweet_as( "$user $id $data", $server, $win );
124 my ( $data, $server, $win ) = @_;
126 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
127 ¬ice("twirssi_track_replies is required in order to reteet.");
131 return unless &logged_in($twit);
133 $data =~ s/^\s+|\s+$//;
134 my ( $username, $id, $data ) = split ' ', $data, 3;
137 ¬ice("Usage: /retweet_as <username> <nick[:num]> [comment]");
141 return unless $username = &valid_username($username);
144 $id =~ s/[^\w\d\-:]+//g;
145 ( $nick, $id ) = split /:/, $id;
146 unless ( exists $id_map{ lc $nick } ) {
147 ¬ice("Can't find a tweet from $nick to retweet!");
151 $id = $id_map{__indexes}{$nick} unless $id;
152 unless ( $id_map{ lc $nick }[$id] ) {
153 ¬ice("Can't find a tweet numbered $id from $nick to retweet!");
157 unless ( $id_map{__tweets}{ lc $nick }[$id] ) {
158 ¬ice("The text of this tweet isn't saved, sorry!");
162 # Irssi::settings_add_str( "twirssi", "twirssi_retweet_format", 'RT $n: $t ${-- $c$}' );
163 my $text = Irssi::settings_get_str("twirssi_retweet_format");
164 $text =~ s/\$n/\@$nick/g;
166 $text =~ s/\${|\$}//g;
167 $text =~ s/\$c/$data/;
169 $text =~ s/\${.*?\$}//;
171 $text =~ s/\$t/$id_map{__tweets}{ lc $nick }[$id]/;
173 $data = &shorten($text);
175 return if &too_long($data);
180 $twits{$username}->update(
183 in_reply_to_status_id => $id_map{ lc $nick }[$id]
188 ¬ice("Update failed");
192 return unless $success;
195 ¬ice("Update caused an error: $@. Aborted");
199 foreach ( $data =~ /@([-\w]+)/ ) {
203 ¬ice("Retweet sent");
207 my ( $data, $server, $win ) = @_;
209 return unless &logged_in($twit);
211 $data =~ s/^\s+|\s+$//;
213 ¬ice("Usage: /tweet <update>");
217 &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
221 my ( $data, $server, $win ) = @_;
223 return unless &logged_in($twit);
225 $data =~ s/^\s+|\s+$//;
226 $data =~ s/\s\s+/ /g;
227 my ( $username, $data ) = split ' ', $data, 2;
229 unless ( $username and $data ) {
230 ¬ice("Usage: /tweet_as <username> <update>");
234 return unless $username = &valid_username($username);
236 $data = &shorten($data);
238 return if &too_long($data);
242 unless ( $twits{$username}->update($data) )
244 ¬ice("Update failed");
248 return unless $success;
251 ¬ice("Update caused an error: $@. Aborted.");
255 foreach ( $data =~ /@([-\w]+)/ ) {
259 my $away = &update_away($data);
261 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
265 my ( $data, $server, $win ) = @_;
267 return unless &logged_in($twit);
269 $data =~ s/^\s+|\s+$//;
271 ¬ice("Usage: /reply <nick[:num]> <update>");
275 my ( $id, $data ) = split ' ', $data, 2;
276 unless ( $id and $data ) {
277 ¬ice("Usage: /reply <nick[:num]> <update>");
281 &cmd_reply_as( "$user $id $data", $server, $win );
285 my ( $data, $server, $win ) = @_;
287 unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
288 ¬ice("twirssi_track_replies is required in order to reply to "
289 . "specific tweets. Either enable it, or just use /tweet "
290 . "\@username <text>." );
294 return unless &logged_in($twit);
296 $data =~ s/^\s+|\s+$//;
297 my ( $username, $id, $data ) = split ' ', $data, 3;
299 unless ( $username and $data ) {
300 ¬ice("Usage: /reply_as <username> <nick[:num]> <update>");
304 return unless $username = &valid_username($username);
307 $id =~ s/[^\w\d\-:]+//g;
308 ( $nick, $id ) = split /:/, $id;
309 unless ( exists $id_map{ lc $nick } ) {
310 ¬ice("Can't find a tweet from $nick to reply to!");
314 $id = $id_map{__indexes}{$nick} unless $id;
315 unless ( $id_map{ lc $nick }[$id] ) {
316 ¬ice("Can't find a tweet numbered $id from $nick to reply to!");
320 if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
322 # remove any @nick at the beginning of the reply, as we'll add it anyway
323 $data =~ s/^\s*\@?$nick\s*//;
324 $data = "\@$nick " . $data;
327 $data = &shorten($data);
329 return if &too_long($data);
334 $twits{$username}->update(
337 in_reply_to_status_id => $id_map{ lc $nick }[$id]
342 ¬ice("Update failed");
346 return unless $success;
349 ¬ice("Update caused an error: $@. Aborted");
353 foreach ( $data =~ /@([-\w]+)/ ) {
357 my $away = &update_away($data);
359 ¬ice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
363 my ( $usage_str, $api_name, $post_ref ) = @_;
366 my ( $data, $server, $win ) = @_;
368 return unless &logged_in($twit);
370 $data =~ s/^\s+|\s+$//;
372 ¬ice("Usage: $usage_str");
378 unless ( $twit->$api_name($data) )
380 ¬ice("$api_name failed");
384 return unless $success;
387 ¬ice("$api_name caused an error. Aborted.");
391 &$post_ref($data) if $post_ref;
396 my ( $data, $server, $win ) = @_;
398 $data =~ s/^\s+|\s+$//g;
399 $data = &normalize_username($data);
400 if ( exists $twits{$data} ) {
401 ¬ice("Switching to $data");
402 $twit = $twits{$data};
403 if ( $data =~ /(.*)\@(.*)/ ) {
407 ¬ice("Couldn't figure out what service '$data' is on");
410 ¬ice("Unknown user $data");
415 my ( $data, $server, $win ) = @_;
417 $data =~ s/^\s+|\s+$//g;
418 $data = $user unless $data;
419 return unless $data = &valid_username($data);
421 ¬ice("Logging out $data...");
422 $twits{$data}->end_session();
423 delete $twits{$data};
426 &cmd_switch( ( keys %twits )[0], $server, $win );
428 Irssi::timeout_remove($poll) if $poll;
434 my ( $data, $server, $win ) = @_;
437 ( $user, $pass ) = split ' ', $data, 2;
438 } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
439 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
441 my @user = split /\s*,\s*/, $autouser;
442 my @pass = split /\s*,\s*/, $autopass;
444 # if a password ends with a '\', it was meant to escape the comma, and
445 # it should be concatinated with the next one
449 while ( $p =~ /\\$/ and @pass ) {
450 $p .= "," . shift @pass;
455 if ( @user != @unescaped ) {
456 ¬ice("Number of usernames doesn't match "
457 . "the number of passwords - auto-login failed" );
460 while ( @user and @unescaped ) {
462 $p = shift @unescaped;
468 ¬ice("/twitter_login requires either a username and password "
469 . "or twitter_usernames and twitter_passwords to be set." );
473 %friends = %nicks = ();
476 if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
477 ( $user, $service ) = ( $1, $2 );
479 $service = Irssi::settings_get_str("twirssi_default_service");
481 $defservice = $service = ucfirst lc $service;
483 eval "use Net::$service";
486 "Failed to load Net::$service when trying to log in as $user: $@");
490 $twit = "Net::$service"->new(
496 unless ( $twit->verify_credentials() ) {
497 ¬ice("Login as $user\@$service failed");
500 &cmd_switch( ( keys %twits )[0], $server, $win );
506 my $rate_limit = $twit->rate_limit_status();
507 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
509 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
515 $twits{"$user\@$service"} = $twit;
516 Irssi::timeout_remove($poll) if $poll;
517 $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
518 ¬ice("Logged in as $user\@$service, loading friends list...");
520 ¬ice( "loaded friends: ", scalar keys %friends );
521 if ( Irssi::settings_get_bool("twirssi_first_run") ) {
522 Irssi::settings_set_bool( "twirssi_first_run", 0 );
523 unless ( exists $friends{twirssi} ) {
524 ¬ice("Welcome to twirssi!"
525 . " Perhaps you should add \@twirssi to your friends list,"
526 . " so you can be notified when a new version is release?"
527 . " Just type /twitter_friend twirssi." );
534 ¬ice("Login failed");
539 my ( $data, $server, $win ) = @_;
541 unless ( $twit and $twit->can('search') ) {
542 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
543 . "doesn't support searches." );
547 $data =~ s/^\s+|\s+$//;
551 ¬ice("Usage: /twitter_subscribe <topic>");
555 if ( exists $id_map{__searches}{$user}{$data} ) {
556 ¬ice("Already had a subscription for '$data'");
560 $id_map{__searches}{$user}{$data} = 1;
561 ¬ice("Added subscription for '$data'");
565 my ( $data, $server, $win ) = @_;
567 unless ( $twit and $twit->can('search') ) {
568 ¬ice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
569 . "doesn't support searches." );
572 $data =~ s/^\s+|\s+$//;
576 ¬ice("Usage: /twitter_unsubscribe <topic>");
580 unless ( exists $id_map{__searches}{$user}{$data} ) {
581 ¬ice("No subscription found for '$data'");
585 delete $id_map{__searches}{$user}{$data};
586 ¬ice("Removed subscription for '$data'");
589 sub cmd_list_search {
590 my ( $data, $server, $win ) = @_;
593 foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
595 foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
596 $topics = $topics ? "$topics, $topic" : $topic;
600 ¬ice("Search subscriptions for \@$suser: $topics");
605 ¬ice("No search subscriptions set up");
610 my ( $data, $server, $win ) = @_;
612 my $loc = Irssi::settings_get_str("twirssi_location");
615 "$loc isn't writable, can't upgrade. Perhaps you need to /set twirssi_location?"
621 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
622 eval { use Digest::MD5; };
626 "Failed to load Digest::MD5. Try '/twirssi_upgrade nomd5' to skip MD5 verification"
631 $md5 = get("http://twirssi.com/md5sum");
635 ¬ice("Failed to download md5sum from peeron! Aborting.");
639 unless ( open( CUR, $loc ) ) {
641 "Failed to read $loc. Check that /set twirssi_location is set to the correct location."
646 my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
649 if ( $cur_md5 eq $md5 ) {
650 ¬ice("Current twirssi seems to be up to date.");
656 Irssi::settings_get_bool("twirssi_upgrade_beta")
657 ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
658 : "http://twirssi.com/twirssi.pl";
659 ¬ice("Downloading twirssi from $URL");
660 LWP::Simple::getstore( $URL, "$loc.upgrade" );
662 unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
663 unless ( open( NEW, "$loc.upgrade" ) ) {
665 "Failed to read $loc.upgrade. Check that /set twirssi_location is set to the correct location."
670 my $new_md5 = Digest::MD5::md5_hex(<NEW>);
673 if ( $new_md5 ne $md5 ) {
674 ¬ice("MD5 verification failed. expected $md5, got $new_md5");
679 rename $loc, "$loc.backup"
680 or ¬ice("Failed to back up $loc: $!. Aborting")
682 rename "$loc.upgrade", $loc
683 or ¬ice("Failed to rename $loc.upgrade: $!. Aborting")
686 my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
687 if ( -e "$dir/autorun/$file" ) {
688 ¬ice("Updating $dir/autorun/$file");
689 unlink "$dir/autorun/$file"
690 or ¬ice("Failed to remove old $file from autorun: $!");
691 symlink "../$file", "$dir/autorun/$file"
692 or ¬ice("Failed to create symlink in autorun directory: $!");
695 ¬ice("Download complete. Reload twirssi with /script load $file");
705 print $fh "type:debug Loading friends page $page...\n"
706 if ( $fh and &debug );
707 my $friends = $twit->friends( { page => $page } );
708 last unless $friends;
709 $new_friends{ $_->{screen_name} } = time foreach @$friends;
711 last if @$friends == 0 or $page == 10;
716 print $fh "type:debug Error during friends list update. Aborted.\n";
720 my ( $added, $removed ) = ( 0, 0 );
721 print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
722 foreach ( keys %new_friends ) {
723 next if exists $friends{$_};
728 print $fh "type:debug Scanning for removed friends...\n"
729 if ( $fh and &debug );
730 foreach ( keys %friends ) {
731 next if exists $new_friends{$_};
736 return ( $added, $removed );
740 print scalar localtime, " - get_updates starting" if &debug;
743 Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
746 ->print( "Can't find a window named '"
747 . Irssi::settings_get_str('twitter_window')
748 . "'. Create it or change the value of twitter_window" );
751 return unless &logged_in($twit);
753 my ( $fh, $filename ) = File::Temp::tempfile();
754 binmode( $fh, ":utf8" );
758 Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
759 Irssi::pidwait_add($pid);
760 } elsif ( defined $pid ) { # child
769 foreach ( keys %twits ) {
770 $error++ unless &do_updates( $fh, $_, $twits{$_}, \%context_cache );
773 my ( $added, $removed ) = &load_friends($fh);
774 if ( $added + $removed ) {
775 print $fh "type:debug %R***%n Friends list updated: ",
777 sprintf( "%d added", $added ),
778 sprintf( "%d removed", $removed ) ),
781 print $fh "__friends__\n";
782 foreach ( sort keys %friends ) {
783 print $fh "$_ $friends{$_}\n";
787 print $fh "type:debug Update encountered errors. Aborted\n";
788 print $fh "-- $last_poll";
790 print $fh "-- $new_poll";
795 print scalar localtime, " - get_updates ends" if &debug;
799 my ( $fh, $username, $obj, $cache ) = @_;
801 my $rate_limit = $obj->rate_limit_status();
802 if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
803 ¬ice("Rate limit exceeded for $username");
807 print scalar localtime, " - Polling for updates for $username" if &debug;
811 if ( $id_map{__last_id}{$username}{timeline} )
813 $tweets = $obj->friends_timeline( { count => 100 } );
815 $tweets = $obj->friends_timeline();
820 print $fh "type:debug Error during friends_timeline call: Aborted.\n";
821 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($@);
825 unless ( ref $tweets ) {
826 if ( $obj->can("get_error") ) {
827 my $error = "Unknown error";
828 eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
829 unless ($@) { $error = $obj->get_error() }
831 "type:debug API Error during friends_timeline call: Aborted\n";
832 print $fh "type:debug : $_\n" foreach split /\n/, Dumper($error);
836 "type:debug API Error during friends_timeline call. Aborted.\n";
841 foreach my $t ( reverse @$tweets ) {
842 my $text = decode_entities( $t->{text} );
843 $text = &hilight($text);
845 if ( Irssi::settings_get_bool("show_reply_context")
846 and $t->{in_reply_to_screen_name} ne $username
847 and $t->{in_reply_to_screen_name}
848 and not exists $friends{ $t->{in_reply_to_screen_name} } )
850 $nicks{ $t->{in_reply_to_screen_name} } = time;
852 unless ( $cache->{ $t->{in_reply_to_status_id} } ) {
854 $cache->{ $t->{in_reply_to_status_id} } =
855 $obj->show_status( $t->{in_reply_to_status_id} );
859 $context = $cache->{ $t->{in_reply_to_status_id} };
862 my $ctext = decode_entities( $context->{text} );
863 $ctext = &hilight($ctext);
864 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
866 " -- http://twitter.com/$context->{user}{screen_name}"
867 . "/status/$context->{id}";
869 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
870 $context->{id}, $username,
871 $context->{user}{screen_name}, $ctext;
876 if $t->{user}{screen_name} eq $username
877 and not Irssi::settings_get_bool("show_own_tweets");
878 if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
879 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
880 . "/status/$t->{id}";
882 printf $fh "id:%d account:%s nick:%s type:%s %s\n",
883 $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
884 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
886 printf $fh "id:%d account:%s type:last_id timeline\n",
887 $new_poll_id, $username;
889 print scalar localtime, " - Polling for replies" if &debug;
892 if ( $id_map{__last_id}{$username}{reply} )
894 $tweets = $obj->replies(
895 { since_id => $id_map{__last_id}{$username}{reply} } )
898 $tweets = $obj->replies() || [];
903 print $fh "type:debug Error during replies call. Aborted.\n";
907 foreach my $t ( reverse @$tweets ) {
909 if exists $friends{ $t->{user}{screen_name} };
911 my $text = decode_entities( $t->{text} );
912 $text = &hilight($text);
913 if ( $t->{truncated} ) {
914 $text .= " -- http://twitter.com/$t->{user}{screen_name}"
915 . "/status/$t->{id}";
917 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
918 $t->{id}, $username, $t->{user}{screen_name}, $text;
919 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
921 printf $fh "id:%d account:%s type:last_id reply\n", $new_poll_id, $username;
923 print scalar localtime, " - Polling for DMs" if &debug;
926 if ( $id_map{__last_id}{$username}{dm} )
928 $tweets = $obj->direct_messages(
929 { since_id => $id_map{__last_id}{$username}{dm} } )
932 $tweets = $obj->direct_messages() || [];
937 print $fh "type:debug Error during direct_messages call. Aborted.\n";
941 foreach my $t ( reverse @$tweets ) {
942 my $text = decode_entities( $t->{text} );
943 $text = &hilight($text);
944 printf $fh "id:%d account:%s nick:%s type:dm %s\n",
945 $t->{id}, $username, $t->{sender_screen_name}, $text;
946 $new_poll_id = $t->{id} if $new_poll_id < $t->{id};
948 printf $fh "id:%d account:%s type:last_id dm\n", $new_poll_id, $username;
950 print scalar localtime, " - Polling for subscriptions" if &debug;
951 if ( $obj->can('search') and $id_map{__searches}{$username} ) {
953 foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
954 print $fh "type:debug searching for $topic since ",
955 "$id_map{__searches}{$username}{$topic}\n";
957 $search = $obj->search(
960 since_id => $id_map{__searches}{$username}{$topic}
967 "type:debug Error during search($topic) call. Aborted.\n";
971 unless ( $search->{max_id} ) {
972 print $fh "type:debug Invalid search results when searching",
973 " for $topic. Aborted.\n";
977 $id_map{__searches}{$username}{$topic} = $search->{max_id};
978 printf $fh "id:%d account:%s type:searchid topic:%s\n",
979 $search->{max_id}, $username, $topic;
981 foreach my $t ( reverse @{ $search->{results} } ) {
982 my $text = decode_entities( $t->{text} );
983 $text = &hilight($text);
984 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
985 $t->{id}, $username, $t->{from_user}, $topic, $text;
986 $new_poll_id = $t->{id}
988 or $t->{id} < $new_poll_id;
993 print scalar localtime, " - Done" if &debug;
1000 my $filename = $data->[0];
1001 my $attempt = $data->[1];
1003 print scalar localtime, " - checking child log at $filename ($attempt)"
1005 my ($new_last_poll);
1007 # first time we run we don't want to print out *everything*, so we just
1010 $suppress = 1 unless keys %tweet_cache;
1012 if ( open FILE, $filename ) {
1017 last if /^__friends__/;
1021 foreach my $key (qw/id account nick type topic/) {
1022 if (s/^$key:(\S+)\s*//) {
1027 if ( not $meta{type} or $meta{type} !~ /searchid|last_id/ ) {
1028 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
1032 $new_cache{ $meta{id} } = time;
1034 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
1040 $meta{account} =~ s/\@(\w+)$//;
1041 $meta{service} = $1;
1043 lc $meta{service} eq
1044 lc Irssi::settings_get_str("twirssi_default_service") )
1046 $account = "$meta{account}: "
1047 if lc "$meta{account}\@$meta{service}" ne lc
1048 "$user\@$defservice";
1050 $account = "$meta{account}\@$meta{service}: ";
1054 if ( $meta{type} ne 'dm'
1055 and Irssi::settings_get_bool("twirssi_track_replies")
1059 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
1060 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
1061 $id_map{__indexes}{ $meta{nick} } = $marker;
1062 $id_map{__tweets}{ lc $meta{nick} }[$marker] = $_;
1063 $marker = ":$marker";
1067 $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
1069 '@' . substr( $meta{account}, 0, index( $meta{account}, "@" ) );
1070 if ( $_ =~ /\Q$nick\E(?:\W|$)/i
1071 and Irssi::settings_get_bool("twirssi_hilights") )
1073 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
1074 $hilight = MSGLEVEL_HILIGHT;
1077 if ( $meta{type} =~ /tweet|reply/ ) {
1080 ( MSGLEVEL_PUBLIC | $hilight ),
1081 $meta{type}, $account, $meta{nick}, $marker, $_
1083 } elsif ( $meta{type} eq 'search' ) {
1086 ( MSGLEVEL_PUBLIC | $hilight ),
1087 $meta{type}, $account, $meta{topic},
1088 $meta{nick}, $marker, $_
1091 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1093 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1095 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1098 } elsif ( $meta{type} eq 'dm' ) {
1101 ( MSGLEVEL_MSGS | $hilight ),
1102 $meta{type}, $account, $meta{nick}, $_
1104 } elsif ( $meta{type} eq 'searchid' ) {
1105 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
1107 exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
1109 $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
1111 $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
1114 print "Search '$meta{topic}' returned invalid id $meta{id}";
1116 } elsif ( $meta{type} eq 'last_id' ) {
1117 $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} =
1119 if $id_map{__last_id}{"$meta{account}\@$meta{service}"}{$_} <
1121 } elsif ( $meta{type} eq 'error' ) {
1122 push @lines, [ MSGLEVEL_MSGS, $_ ];
1123 } elsif ( $meta{type} eq 'debug' ) {
1124 print "$_" if &debug,;
1126 print "Unknown line type $meta{type}: $_" if &debug,;
1133 ($new_last_poll) = ($1);
1136 my ( $f, $t ) = split ' ', $_;
1137 $nicks{$f} = $friends{$f} = $t;
1140 if ($new_last_poll) {
1141 print "new last_poll = $new_last_poll" if &debug;
1142 print "new last_poll_id = ", Dumper( $id_map{__last_id} ) if &debug;
1144 print "First call, not printing updates" if &debug;
1146 foreach my $line (@lines) {
1147 $window->printformat(
1149 "twirssi_" . $line->[1],
1150 @$line[ 2 .. $#$line ]
1157 or warn "Failed to remove $filename: $!"
1160 # commit the pending cache lines to the actual cache, now that
1161 # we've printed our output
1162 %tweet_cache = ( %tweet_cache, %new_cache );
1164 # keep enough cached tweets, to make sure we don't show duplicates.
1165 foreach ( keys %tweet_cache ) {
1166 next if $tweet_cache{$_} >= $last_poll - 3600;
1167 delete $tweet_cache{$_};
1169 $last_poll = $new_last_poll;
1174 Irssi::settings_get_str("twirssi_replies_store") )
1176 if ( open JSON, ">$file" ) {
1177 print JSON JSON::Any->objToJson( \%id_map );
1180 &ccrap("Failed to write replies to $file: $!");
1190 if ( $attempt < 24 ) {
1191 Irssi::timeout_add_once( 5000, 'monitor_child',
1192 [ $filename, $attempt + 1 ] );
1194 print "Giving up on polling $filename" if &debug;
1195 unlink $filename unless &debug;
1197 return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1200 my @time = localtime($last_poll);
1201 if ( time - $last_poll < 24 * 60 * 60 ) {
1202 $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1204 $since = scalar localtime($last_poll);
1207 if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1212 q{ .--./ / | _.---.| },
1223 &ccrap("Haven't been able to get updated tweets since $since");
1228 return Irssi::settings_get_bool("twirssi_debug");
1232 $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1236 $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1242 if ( Irssi::settings_get_bool("tweet_to_away")
1244 and $data !~ /^[dD] / )
1247 Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1249 $server->send_raw("away :$data");
1252 &ccrap( "Can't find bitlbee server.",
1253 "Update bitlbee_server or disable tweet_to_away" );
1263 my $noalert = shift;
1265 if ( length $data > 140 ) {
1266 ¬ice( "Tweet too long (" . length($data) . " characters) - aborted" )
1274 sub valid_username {
1275 my $username = shift;
1277 $username = &normalize_username($username);
1279 unless ( exists $twits{$username} ) {
1280 ¬ice("Unknown username $username");
1290 ¬ice("Not logged in! Use /twitter_login username pass!");
1298 my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1301 $linestart =~ /^\/(?:retweet|twitter_reply)(?:_as)?\s*$/
1302 or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1303 and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1305 { # /twitter_reply gets a nick:num
1307 @$complist = map { "$_:$id_map{__indexes}{$_}" }
1308 sort { $nicks{$b} <=> $nicks{$a} }
1310 keys %{ $id_map{__indexes} };
1313 # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1315 if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1316 my $prefix = $word =~ s/^@//;
1317 $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1318 push @$complist, grep /^\Q$word/i,
1319 sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1320 @$complist = map { "\@$_" } @$complist if $prefix;
1324 sub event_send_text {
1325 my ( $line, $server, $win ) = @_;
1326 my $awin = Irssi::active_win();
1328 # if the window where we got our text was the twitter window, and the user
1329 # wants to be lazy, tweet away!
1330 if ( ( $awin->get_active_name() eq $window->{name} )
1331 and Irssi::settings_get_bool("tweet_window_input") )
1333 &cmd_tweet( $line, $server, $win );
1338 my $poll = Irssi::settings_get_int("twitter_poll_interval");
1339 return $poll if $poll >= 60;
1346 if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1347 my $c = Irssi::settings_get_str("twirssi_nick_color");
1348 $c = $irssi_to_mirc_colors{$c};
1349 $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1351 if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1352 my $c = Irssi::settings_get_str("twirssi_topic_color");
1353 $c = $irssi_to_mirc_colors{$c};
1354 $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1356 $text =~ s/[\n\r]/ /g;
1364 my $provider = Irssi::settings_get_str("short_url_provider");
1367 Irssi::settings_get_bool("twirssi_always_shorten")
1368 or &too_long( $data, 1 )
1374 if ( $provider eq 'Bitly' ) {
1375 @args[ 1, 2 ] = split ',',
1376 Irssi::settings_get_str("short_url_args"), 2;
1377 unless ( @args == 3 ) {
1379 "WWW::Shorten::Bitly requires a username and API key.",
1380 "Set short_url_args to username,API_key or change your",
1381 "short_url_provider."
1387 foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1390 my $short = makeashorterlink(@args);
1392 $data =~ s/\Q$url/$short/g;
1394 ¬ice("Failed to shorten $url!");
1403 sub normalize_username {
1406 my ( $username, $service ) = split /\@/, $user, 2;
1408 $service = ucfirst lc $service;
1411 ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1412 unless ( exists $twits{"$username\@$service"} ) {
1414 foreach my $t ( sort keys %twits ) {
1415 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1421 ¬ice("Can't find a logged in user '$user'");
1426 return "$username\@$service";
1429 Irssi::signal_add( "send text", "event_send_text" );
1431 Irssi::theme_register(
1433 'twirssi_tweet', '[$0%B@$1%n$2] $3',
1434 'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1435 'twirssi_reply', '[$0\--> %B@$1%n$2] $3',
1436 'twirssi_dm', '[$0%r@$1%n (%WDM%n)] $2',
1437 'twirssi_error', 'ERROR: $0',
1441 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1442 Irssi::settings_add_str( "twirssi", "twitter_window", "twitter" );
1443 Irssi::settings_add_str( "twirssi", "bitlbee_server", "bitlbee" );
1444 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
1445 Irssi::settings_add_str( "twirssi", "short_url_args", undef );
1446 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
1447 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
1448 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1449 Irssi::settings_add_str( "twirssi", "twirssi_nick_color", "%B" );
1450 Irssi::settings_add_str( "twirssi", "twirssi_topic_color", "%r" );
1451 Irssi::settings_add_str( "twirssi", "twirssi_retweet_format",
1452 'RT $n: "$t" ${-- $c$}' );
1453 Irssi::settings_add_str( "twirssi", "twirssi_location",
1454 ".irssi/scripts/twirssi.pl" );
1455 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1456 ".irssi/scripts/twirssi.json" );
1457 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta", 0 );
1458 Irssi::settings_add_bool( "twirssi", "tweet_to_away", 0 );
1459 Irssi::settings_add_bool( "twirssi", "show_reply_context", 0 );
1460 Irssi::settings_add_bool( "twirssi", "show_own_tweets", 1 );
1461 Irssi::settings_add_bool( "twirssi", "twirssi_debug", 0 );
1462 Irssi::settings_add_bool( "twirssi", "twirssi_first_run", 1 );
1463 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies", 1 );
1464 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick", 1 );
1465 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1466 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts", 1 );
1467 Irssi::settings_add_bool( "twirssi", "twirssi_hilights", 1 );
1468 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten", 0 );
1469 Irssi::settings_add_bool( "twirssi", "tweet_window_input", 0 );
1471 $last_poll = time - &get_poll_time;
1472 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1475 ->print( "Couldn't find a window named '"
1476 . Irssi::settings_get_str('twitter_window')
1477 . "', trying to create it." );
1479 Irssi::Windowitem::window_create(
1480 Irssi::settings_get_str('twitter_window'), 1 );
1481 $window->set_name( Irssi::settings_get_str('twitter_window') );
1485 Irssi::command_bind( "dm", "cmd_direct" );
1486 Irssi::command_bind( "dm_as", "cmd_direct_as" );
1487 Irssi::command_bind( "tweet", "cmd_tweet" );
1488 Irssi::command_bind( "tweet_as", "cmd_tweet_as" );
1489 Irssi::command_bind( "retweet", "cmd_retweet" );
1490 Irssi::command_bind( "retweet_as", "cmd_retweet_as" );
1491 Irssi::command_bind( "twitter_reply", "cmd_reply" );
1492 Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
1493 Irssi::command_bind( "twitter_login", "cmd_login" );
1494 Irssi::command_bind( "twitter_logout", "cmd_logout" );
1495 Irssi::command_bind( "twitter_switch", "cmd_switch" );
1496 Irssi::command_bind( "twitter_subscribe", "cmd_add_search" );
1497 Irssi::command_bind( "twitter_unsubscribe", "cmd_del_search" );
1498 Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1499 Irssi::command_bind( "twirssi_upgrade", "cmd_upgrade" );
1500 Irssi::command_bind( "twitter_updates", "get_updates" );
1501 if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1502 Irssi::command_bind( "reply", "cmd_reply" );
1503 Irssi::command_bind( "reply_as", "cmd_reply_as" );
1505 Irssi::command_bind(
1508 print "twits: ", join ", ",
1509 map { "u: $_->{username}\@" . ref($_) } values %twits;
1510 print "selected: $user\@$defservice";
1511 print "friends: ", join ", ", sort keys %friends;
1512 print "nicks: ", join ", ", sort keys %nicks;
1513 print "searches: ", Dumper \%{ $id_map{__searches} };
1514 print "last poll: $last_poll";
1515 if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1516 print DUMP Dumper \%tweet_cache;
1518 print "cache written out to /tmp/twirssi.cache.txt";
1522 Irssi::command_bind(
1525 ¬ice("Twirssi v$VERSION (r$REV); "
1526 . "Net::Twitter v$Net::Twitter::VERSION. "
1528 . JSON::Any::handler()
1529 . ". See details at http://twirssi.com/" );
1532 Irssi::command_bind(
1535 "/twitter_friend <username>",
1537 sub { ¬ice("Following $_[0]"); $nicks{ $_[0] } = time; }
1540 Irssi::command_bind(
1543 "/twitter_unfriend <username>",
1545 sub { ¬ice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1548 Irssi::command_bind(
1549 "twitter_device_updates",
1551 "/twitter_device_updates none|im|sms",
1552 "update_delivery_device",
1553 sub { ¬ice("Device updated to $_[0]"); }
1556 Irssi::signal_add_last( 'complete word' => \&sig_complete );
1558 ¬ice(" %Y<%C(%B^%C)%N TWIRSSI v%R$VERSION%N (r$REV)");
1559 ¬ice(" %C(_(\\%N http://twirssi.com/ for full docs");
1561 " %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1563 my $file = Irssi::settings_get_str("twirssi_replies_store");
1564 if ( $file and -r $file ) {
1565 if ( open( JSON, $file ) ) {
1570 my $ref = JSON::Any->jsonToObj($json);
1572 my $num = keys %{ $id_map{__indexes} };
1573 ¬ice( sprintf "Loaded old replies from %d contact%s.",
1574 $num, ( $num == 1 ? "" : "s" ) );
1578 ¬ice("Failed to load old replies from $file: $!");
1582 if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1583 ¬ice("Loading WWW::Shorten::$provider...");
1584 eval "use WWW::Shorten::$provider;";
1588 "Failed to load WWW::Shorten::$provider - either clear",
1589 "short_url_provider or install the CPAN module"
1594 if ( my $autouser = Irssi::settings_get_str("twitter_usernames")
1595 and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1603 ->print( "Create a window named "
1604 . Irssi::settings_get_str('twitter_window')
1605 . " or change the value of twitter_window. Then, reload twirssi." );
1608 # vim: set sts=4 expandtab: