8f7f966cd42fa7326cd4b5e4a664b092900208c9
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use Net::Twitter;
5 use HTTP::Date;
6 use HTML::Entities;
7 use File::Temp;
8 use LWP::Simple;
9 use Data::Dumper;
10 $Data::Dumper::Indent = 1;
11
12 use vars qw($VERSION %IRSSI);
13
14 $VERSION = "1.6.1";
15 my ($REV) = '$Rev: 336 $' =~ /(\d+)/;
16 %IRSSI = (
17     authors     => 'Dan Boger',
18     contact     => 'zigdon@gmail.com',
19     name        => 'twirssi',
20     description => 'Send twitter updates using /tweet.  '
21       . 'Can optionally set your bitlbee /away message to same',
22     license => 'GNU GPL v2',
23     url     => 'http://tinyurl.com/twirssi',
24     changed => 'Mon Dec  1 15:36:01 PST 2008',
25 );
26
27 my $window;
28 my $twit;
29 my %twits;
30 my $user;
31 my $poll;
32 my %nicks;
33 my %friends;
34 my $last_poll = time - 300;
35 my %tweet_cache;
36 my %id_map;
37
38 sub cmd_direct {
39     my ( $data, $server, $win ) = @_;
40
41     unless ($twit) {
42         &notice("Not logged in!  Use /twitter_login username pass!");
43         return;
44     }
45
46     my ( $target, $text ) = split ' ', $data, 2;
47     unless ( $target and $text ) {
48         &notice("Usage: /dm <nick> <message>");
49         return;
50     }
51
52     &cmd_direct_as( "$user $data", $server, $win );
53 }
54
55 sub cmd_direct_as {
56     my ( $data, $server, $win ) = @_;
57
58     unless ($twit) {
59         &notice("Not logged in!  Use /twitter_login username pass!");
60         return;
61     }
62
63     my ( $username, $target, $text ) = split ' ', $data, 3;
64     unless ( $username and $target and $text ) {
65         &notice("Usage: /dm_as <username> <nick> <message>");
66         return;
67     }
68
69     unless ( exists $twits{$username} ) {
70         &notice("Unknown username $username");
71         return;
72     }
73
74     eval {
75         unless ( $twits{$username}
76             ->new_direct_message( { user => $target, text => $text } ) )
77         {
78             &notice("DM to $target failed");
79             return;
80         }
81     };
82
83     if ($@) {
84         &notice("DM caused an error.  Aborted");
85         return;
86     }
87
88     &notice("DM sent to $target");
89     $nicks{$target} = time;
90 }
91
92 sub cmd_tweet {
93     my ( $data, $server, $win ) = @_;
94
95     unless ($twit) {
96         &notice("Not logged in!  Use /twitter_login username pass!");
97         return;
98     }
99
100     $data =~ s/^\s+|\s+$//;
101     unless ($data) {
102         &notice("Usage: /tweet <update>");
103         return;
104     }
105
106     &cmd_tweet_as( "$user $data", $server, $win );
107 }
108
109 sub cmd_tweet_as {
110     my ( $data, $server, $win ) = @_;
111
112     unless ($twit) {
113         &notice("Not logged in!  Use /twitter_login username pass!");
114         return;
115     }
116
117     $data =~ s/^\s+|\s+$//;
118     my ( $username, $data ) = split ' ', $data, 2;
119
120     unless ( $username and $data ) {
121         &notice("Usage: /tweet_as <username> <update>");
122         return;
123     }
124
125     unless ( exists $twits{$username} ) {
126         &notice("Unknown username $username");
127         return;
128     }
129
130     if ( Irssi::settings_get_str("short_url_provider") ) {
131         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
132             eval {
133                 my $short = makeashorterlink($url);
134                 $data =~ s/\Q$url/$short/g;
135             };
136         }
137     }
138
139     if ( length $data > 140 ) {
140         &notice(
141             "Tweet too long (" . length($data) . " characters) - aborted" );
142         return;
143     }
144
145     eval {
146         unless ( $twits{$username}->update($data) )
147         {
148             &notice("Update failed");
149             return;
150         }
151     };
152
153     if ($@) {
154         &notice("Update caused an error.  Aborted.");
155         return;
156     }
157
158     foreach ( $data =~ /@([-\w]+)/ ) {
159         $nicks{$1} = time;
160     }
161
162     my $away = 0;
163     if (    Irssi::settings_get_bool("tweet_to_away")
164         and $data !~ /\@\w/
165         and $data !~ /^[dD] / )
166     {
167         my $server =
168           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
169         if ($server) {
170             $server->send_raw("away :$data");
171             $away = 1;
172         } else {
173             &notice( "Can't find bitlbee server.",
174                 "Update bitlbee_server or disalbe tweet_to_away" );
175         }
176     }
177
178     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
179 }
180
181 sub cmd_reply {
182     my ( $data, $server, $win ) = @_;
183
184     unless ($twit) {
185         &notice("Not logged in!  Use /twitter_login username pass!");
186         return;
187     }
188
189     $data =~ s/^\s+|\s+$//;
190     unless ($data) {
191         &notice("Usage: /reply <nick[:num]> <update>");
192         return;
193     }
194
195     $data =~ s/^\s+|\s+$//;
196     my ( $id, $data ) = split ' ', $data, 2;
197     unless ( $id and $data ) {
198         &notice("Usage: /reply_as <nick[:num]> <update>");
199         return;
200     }
201
202     &cmd_reply_as( "$user $id $data", $server, $win );
203 }
204
205 sub cmd_reply_as {
206     my ( $data, $server, $win ) = @_;
207
208     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
209         &notice("twirssi_track_replies is required in order to reply to "
210               . "specific tweets.  Either enable it, or just use /tweet "
211               . "\@username <text>." );
212         return;
213     }
214
215     unless ($twit) {
216         &notice("Not logged in!  Use /twitter_login username pass!");
217         return;
218     }
219
220     $data =~ s/^\s+|\s+$//;
221     my ( $username, $id, $data ) = split ' ', $data, 3;
222
223     unless ( $username and $data ) {
224         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
225         return;
226     }
227
228     unless ( exists $twits{$username} ) {
229         &notice("Unknown username $username");
230         return;
231     }
232
233     my $nick;
234     $id =~ s/[^\w\d\-:]+//g;
235     ( $nick, $id ) = split /:/, $id;
236     unless ( exists $id_map{$nick} ) {
237         &notice("Can't find a tweet from $nick to reply to!");
238         return;
239     }
240
241     $id = $id_map{__indexes}{$nick} unless $id;
242     unless ( $id_map{ lc $nick }[$id] ) {
243         &notice("Can't find a tweet numbered $id from $nick to reply to!");
244         return;
245     }
246
247     # remove any @nick at the beginning of the reply, as we'll add it anyway
248     $data =~ s/^\s*\@?$nick\s*//;
249     $data = "\@$nick " . $data;
250
251     if ( Irssi::settings_get_str("short_url_provider") ) {
252         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
253             eval {
254                 my $short = makeashorterlink($url);
255                 $data =~ s/\Q$url/$short/g;
256             };
257         }
258     }
259
260     if ( length $data > 140 ) {
261         &notice(
262             "Tweet too long (" . length($data) . " characters) - aborted" );
263         return;
264     }
265
266     eval {
267         unless (
268             $twits{$username}->update(
269                 {
270                     status                => $data,
271                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
272                 }
273             )
274           )
275         {
276             &notice("Update failed");
277             return;
278         }
279     };
280
281     if ($@) {
282         &notice("Update caused an error.  Aborted");
283         return;
284     }
285
286     foreach ( $data =~ /@([-\w]+)/ ) {
287         $nicks{$1} = time;
288     }
289
290     my $away = 0;
291     if (    Irssi::settings_get_bool("tweet_to_away")
292         and $data !~ /\@\w/
293         and $data !~ /^[dD] / )
294     {
295         my $server =
296           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
297         if ($server) {
298             $server->send_raw("away :$data");
299             $away = 1;
300         } else {
301             &notice( "Can't find bitlbee server.",
302                 "Update bitlbee_server or disalbe tweet_to_away" );
303         }
304     }
305
306     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
307 }
308
309 sub gen_cmd {
310     my ( $usage_str, $api_name, $post_ref ) = @_;
311
312     return sub {
313         my ( $data, $server, $win ) = @_;
314
315         unless ($twit) {
316             &notice("Not logged in!  Use /twitter_login username pass!");
317             return;
318         }
319
320         $data =~ s/^\s+|\s+$//;
321         unless ($data) {
322             &notice("Usage: $usage_str");
323             return;
324         }
325
326         eval {
327             unless ( $twit->$api_name($data) )
328             {
329                 &notice("$api_name failed");
330                 return;
331             }
332         };
333
334         if ($@) {
335             &notice("$api_name caused an error.  Aborted.");
336             return;
337         }
338
339         &$post_ref($data) if $post_ref;
340       }
341 }
342
343 sub cmd_switch {
344     my ( $data, $server, $win ) = @_;
345
346     $data =~ s/^\s+|\s+$//g;
347     if ( exists $twits{$data} ) {
348         &notice("Switching to $data");
349         $twit = $twits{$data};
350         $user = $data;
351     } else {
352         &notice("Unknown user $data");
353     }
354 }
355
356 sub cmd_logout {
357     my ( $data, $server, $win ) = @_;
358
359     $data =~ s/^\s+|\s+$//g;
360     if ( $data and exists $twits{$data} ) {
361         &notice("Logging out $data...");
362         $twits{$data}->end_session();
363         delete $twits{$data};
364     } elsif ($data) {
365         &notice("Unknown username '$data'");
366     } else {
367         &notice("Logging out $user...");
368         $twit->end_session();
369         undef $twit;
370         delete $twits{$user};
371         if ( keys %twits ) {
372             &cmd_switch( ( keys %twits )[0], $server, $win );
373         } else {
374             Irssi::timeout_remove($poll) if $poll;
375             undef $poll;
376         }
377     }
378 }
379
380 sub cmd_login {
381     my ( $data, $server, $win ) = @_;
382     my $pass;
383     if ($data) {
384         ( $user, $pass ) = split ' ', $data, 2;
385     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
386         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
387     {
388         my @user = split /\s*,\s*/, $autouser;
389         my @pass = split /\s*,\s*/, $autopass;
390         if ( @user != @pass ) {
391             &notice("Number of usernames doesn't match "
392                   . "the number of passwords - auto-login failed" );
393         } else {
394             my ( $u, $p );
395             while ( @user and @pass ) {
396                 $u = shift @user;
397                 $p = shift @pass;
398                 &cmd_login("$u $p");
399             }
400             return;
401         }
402     } else {
403         &notice("/twitter_login requires either a username and password "
404               . "or twitter_usernames and twitter_passwords to be set." );
405         return;
406     }
407
408     %friends = %nicks = ();
409
410     $twit = Net::Twitter->new(
411         username => $user,
412         password => $pass,
413         source   => "twirssi"
414     );
415
416     unless ( $twit->verify_credentials() ) {
417         &notice("Login as $user failed");
418         $twit = undef;
419         if ( keys %twits ) {
420             &cmd_switch( ( keys %twits )[0], $server, $win );
421         }
422         return;
423     }
424
425     if ($twit) {
426         my $rate_limit = $twit->rate_limit_status();
427         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
428             &notice("Rate limit exceeded, try again later");
429             $twit = undef;
430             return;
431         }
432
433         $twits{$user} = $twit;
434         Irssi::timeout_remove($poll) if $poll;
435         $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
436         &notice("Logged in as $user, loading friends list...");
437         &load_friends();
438         &notice( "loaded friends: ", scalar keys %friends );
439         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
440             Irssi::settings_set_bool( "twirssi_first_run", 0 );
441             unless ( exists $friends{twirssi} ) {
442                 &notice("Welcome to twirssi!"
443                       . "  Perhaps you should add \@twirssi to your friends list,"
444                       . " so you can be notified when a new version is release?"
445                       . "  Just type /twitter_friend twirssi." );
446             }
447         }
448         %nicks = %friends;
449         $nicks{$user} = 0;
450         &get_updates;
451     } else {
452         &notice("Login failed");
453     }
454 }
455
456 sub cmd_upgrade {
457     my ( $data, $server, $win ) = @_;
458
459     my $loc = Irssi::settings_get_str("twirssi_location");
460     unless ( -w $loc ) {
461         &notice(
462 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
463         );
464         return;
465     }
466
467     if ( not -x "/usr/bin/md5sum" and not $data ) {
468         &notice(
469 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
470         );
471         return;
472     }
473
474     my $md5;
475     unless ($data) {
476         eval { use Digest::MD5; };
477
478         if ($@) {
479             &notice(
480 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
481             );
482             return;
483         }
484
485         $md5 = get("http://twirssi.com/md5sum");
486         chomp $md5;
487         $md5 =~ s/ .*//;
488         unless ($md5) {
489             &notice("Failed to download md5sum from peeron!  Aborting.");
490             return;
491         }
492
493         unless ( open( CUR, $loc ) ) {
494             &notice(
495 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
496             );
497             return;
498         }
499
500         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
501         close CUR;
502
503         if ( $cur_md5 eq $md5 ) {
504             &notice("Current twirssi seems to be up to date.");
505             return;
506         }
507     }
508
509     my $URL = "http://twirssi.com/twirssi.pl";
510     &notice("Downloading twirssi from $URL");
511     LWP::Simple::getstore( $URL, "$loc.upgrade" );
512
513     unless ($data) {
514         unless ( open( NEW, "$loc.upgrade" ) ) {
515             &notice(
516 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
517             );
518             return;
519         }
520
521         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
522         close NEW;
523
524         if ( $new_md5 ne $md5 ) {
525             &notice("MD5 verification failed. expected $md5, got $new_md5");
526             return;
527         }
528     }
529
530     rename $loc, "$loc.backup"
531       or &notice("Failed to back up $loc: $!.  Aborting")
532       and return;
533     rename "$loc.upgrade", $loc
534       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
535       and return;
536
537     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
538     if ( -e "$dir/autorun/$file" ) {
539         &notice("Updating $dir/autorun/$file");
540         unlink "$dir/autorun/$file"
541           or &notice("Failed to remove old $file from autorun: $!");
542         symlink "../$file", "$dir/autorun/$file"
543           or &notice("Failed to create symlink in autorun directory: $!");
544     }
545
546     &notice("Download complete.  Reload twirssi with /script load $file");
547 }
548
549 sub load_friends {
550     my $fh   = shift;
551     my $page = 1;
552     my %new_friends;
553     eval {
554         while (1)
555         {
556             print $fh "Loading friends page $page...\n" if ( $fh and &debug );
557             my $friends = $twit->friends( { page => $page } );
558             last unless $friends;
559             $new_friends{ $_->{screen_name} } = time foreach @$friends;
560             $page++;
561             last if @$friends == 0 or $page == 10;
562         }
563     };
564
565     if ($@) {
566         &notice("Error during friends list update.  Aborted.");
567         return;
568     }
569
570     my ( $added, $removed ) = ( 0, 0 );
571     print $fh "Scanning for new friends...\n" if ( $fh and &debug );
572     foreach ( keys %new_friends ) {
573         next if exists $friends{$_};
574         $friends{$_} = time;
575         $added++;
576     }
577
578     print $fh "Scanning for removed friends...\n" if ( $fh and &debug );
579     foreach ( keys %friends ) {
580         next if exists $new_friends{$_};
581         delete $friends{$_};
582         $removed++;
583     }
584
585     return ( $added, $removed );
586 }
587
588 sub get_updates {
589     print scalar localtime, " - get_updates starting" if &debug;
590
591     $window =
592       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
593     unless ($window) {
594         Irssi::active_win()
595           ->print( "Can't find a window named '"
596               . Irssi::settings_get_str('twitter_window')
597               . "'.  Create it or change the value of twitter_window" );
598     }
599     unless ($twit) {
600         &notice("Not logged in!  Use /twitter_login username pass!");
601         return;
602     }
603
604     my ( $fh, $filename ) = File::Temp::tempfile();
605     my $pid = fork();
606
607     if ($pid) {    # parent
608         Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
609         Irssi::pidwait_add($pid);
610     } elsif ( defined $pid ) {    # child
611         close STDIN;
612         close STDOUT;
613         close STDERR;
614
615         my $new_poll = time;
616
617         &do_updates( $fh, $user, $twit );
618         foreach ( keys %twits ) {
619             next if $_ eq $user;
620             &do_updates( $fh, $_, $twits{$_} );
621         }
622
623         my ( $added, $removed ) = &load_friends($fh);
624         if ( $added + $removed ) {
625             print $fh "%R***%n Friends list updated: ",
626               join( ", ",
627                 sprintf( "%d added",   $added ),
628                 sprintf( "%d removed", $removed ) ),
629               "\n";
630         }
631         print $fh "__friends__\n";
632         foreach ( sort keys %friends ) {
633             print $fh "$_ $friends{$_}\n";
634         }
635         print $fh $new_poll;
636         close $fh;
637         exit;
638     }
639     print scalar localtime, " - get_updates ends" if &debug;
640 }
641
642 sub do_updates {
643     my ( $fh, $username, $obj ) = @_;
644
645     print scalar localtime, " - Polling for updates for $username" if &debug;
646     my $tweets;
647     eval {
648         $tweets = $obj->friends_timeline(
649             { since => HTTP::Date::time2str($last_poll) } )
650           || [];
651     };
652
653     if ($@) {
654         printf $fh "type:error Error during friends_timeline call.  Aborted.\n"
655           return;
656     }
657
658     foreach my $t ( reverse @$tweets ) {
659         my $text = decode_entities( $t->{text} );
660         $text =~ s/%/%%/g;
661         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
662         my $reply = "tweet";
663         if (    Irssi::settings_get_bool("show_reply_context")
664             and $t->{in_reply_to_screen_name} ne $username
665             and $t->{in_reply_to_screen_name}
666             and not exists $friends{ $t->{in_reply_to_screen_name} } )
667         {
668             $nicks{ $t->{in_reply_to_screen_name} } = time;
669             my $context = $obj->show_status( $t->{in_reply_to_status_id} );
670             if ($context) {
671                 my $ctext = decode_entities( $context->{text} );
672                 $ctext =~ s/%/%%/g;
673                 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
674                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
675                   $context->{id}, $username,
676                   $context->{user}{screen_name}, $ctext;
677                 $reply = "reply";
678             } else {
679                 print "Failed to get context from $t->{in_reply_to_screen_name}"
680                   if &debug;
681             }
682         }
683         next
684           if $t->{user}{screen_name} eq $username
685               and not Irssi::settings_get_bool("show_own_tweets");
686         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
687           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
688     }
689
690     print scalar localtime, " - Polling for replies" if &debug;
691     eval {
692         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
693           || [];
694       }
695
696       if ($@) {
697         printf $fh "type:error Error during replies call.  Aborted.\n" return;
698     }
699
700     foreach my $t ( reverse @$tweets ) {
701         next
702           if exists $friends{ $t->{user}{screen_name} };
703
704         my $text = decode_entities( $t->{text} );
705         $text =~ s/%/%%/g;
706         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
707         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
708           $t->{id}, $username, $t->{user}{screen_name}, $text;
709     }
710
711     print scalar localtime, " - Polling for DMs" if &debug;
712     $tweets =
713       $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
714       || [];
715     foreach my $t ( reverse @$tweets ) {
716         my $text = decode_entities( $t->{text} );
717         $text =~ s/%/%%/g;
718         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
719         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
720           $t->{id}, $username, $t->{sender_screen_name}, $text;
721     }
722     print scalar localtime, " - Done" if &debug;
723 }
724
725 sub monitor_child {
726     my $data     = shift;
727     my $filename = $data->[0];
728
729     print scalar localtime, " - checking child log at $filename" if &debug;
730     my $old_last_poll = $last_poll;
731     if ( open FILE, $filename ) {
732         my @lines;
733         while (<FILE>) {
734             chomp;
735             last if /^__friends__/;
736             my %meta;
737             foreach my $key (qw/id account nick type/) {
738                 s/^$key:(\S+)\s*//;
739                 $meta{$key} = $1;
740             }
741
742             next if exists $tweet_cache{ $meta{id} };
743             $tweet_cache{ $meta{id} } = time;
744             my $account = "";
745             if ( $meta{account} ne $user ) {
746                 $account = "$meta{account}: ";
747             }
748
749             my $marker = "";
750             if (    $meta{type} ne 'dm'
751                 and Irssi::settings_get_bool("twirssi_track_replies")
752                 and $meta{nick}
753                 and $meta{id} )
754             {
755                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
756                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
757                 $id_map{__indexes}{ $meta{nick} }  = $marker;
758                 $marker                            = ":$marker";
759             }
760
761             if ( $meta{type} eq 'tweet' ) {
762                 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
763             } elsif ( $meta{type} eq 'reply' ) {
764                 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
765             } elsif ( $meta{type} eq 'dm' ) {
766                 push @lines, "[$account%B\@$meta{nick}%n (%%WDM%%n)] $_\n",;
767             } elsif ( $meta{type} eq 'error' ) {
768                 push @lines, "debug: $_\n" if &debug,;
769             } elsif ( $meta{type} eq 'debug' ) {
770                 push @lines, "debug: $_\n" if &debug,;
771             }
772         }
773
774         %friends = ();
775         while (<FILE>) {
776             if (/^\d+$/) {
777                 $last_poll = $_;
778                 last;
779             }
780             my ( $f, $t ) = split ' ', $_;
781             $nicks{$f} = $friends{$f} = $t;
782         }
783
784         if ( $last_poll != $old_last_poll ) {
785             print "new last_poll = $last_poll" if &debug;
786             foreach my $line (@lines) {
787                 chomp $line;
788                 $window->print( $line, MSGLEVEL_PUBLIC );
789                 foreach ( $line =~ /\@([-\w]+)/ ) {
790                     $nicks{$1} = time;
791                 }
792             }
793
794             close FILE;
795             unlink $filename
796               or warn "Failed to remove $filename: $!"
797               unless &debug;
798
799       # keep 10 minutes of cached tweets, to make sure we don't show duplicates.
800             foreach ( keys %tweet_cache ) {
801                 next if $tweet_cache{$_} > time - 600;
802                 delete $tweet_cache{$_};
803             }
804             return;
805         }
806     }
807
808     close FILE;
809     Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
810 }
811
812 sub debug {
813     return Irssi::settings_get_bool("twirssi_debug");
814 }
815
816 sub notice {
817     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
818 }
819
820 sub sig_complete {
821     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
822
823     if (
824         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
825         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
826             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
827       )
828     {    # /twitter_reply gets a nick:num
829         @$complist = grep /^\Q$word/i, sort keys %{ $id_map{__indexes} };
830     }
831
832     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
833     # arg to dm)
834     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
835         my $prefix = $word =~ s/^@//;
836         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
837         push @$complist, grep /^\Q$word/i,
838           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
839         @$complist = map { "\@$_" } @$complist if $prefix;
840     }
841 }
842
843 Irssi::settings_add_str( "twirssi", "twitter_window",     "twitter" );
844 Irssi::settings_add_str( "twirssi", "bitlbee_server",     "bitlbee" );
845 Irssi::settings_add_str( "twirssi", "short_url_provider", "TinyURL" );
846 Irssi::settings_add_str( "twirssi", "twirssi_location",
847     ".irssi/scripts/twirssi.pl" );
848 Irssi::settings_add_str( "twirssi", "twitter_usernames", undef );
849 Irssi::settings_add_str( "twirssi", "twitter_passwords", undef );
850 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
851 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
852 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
853 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
854 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
855 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
856 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
857 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
858
859 if ($window) {
860     Irssi::command_bind( "dm",               "cmd_direct" );
861     Irssi::command_bind( "dm_as",            "cmd_direct_as" );
862     Irssi::command_bind( "tweet",            "cmd_tweet" );
863     Irssi::command_bind( "tweet_as",         "cmd_tweet_as" );
864     Irssi::command_bind( "twitter_reply",    "cmd_reply" );
865     Irssi::command_bind( "twitter_reply_as", "cmd_reply_as" );
866     Irssi::command_bind( "twitter_login",    "cmd_login" );
867     Irssi::command_bind( "twitter_logout",   "cmd_logout" );
868     Irssi::command_bind( "twitter_switch",   "cmd_switch" );
869     Irssi::command_bind( "twirssi_upgrade",  "cmd_upgrade" );
870     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
871         Irssi::command_bind( "reply",    "cmd_reply" );
872         Irssi::command_bind( "reply_as", "cmd_reply_as" );
873     }
874     Irssi::command_bind(
875         "twitter_dump",
876         sub {
877             print "twits: ",   Dumper \%twits;
878             print "friends: ", join ", ", sort keys %friends;
879             print "nicks: ",   join ", ", sort keys %nicks;
880             print "last poll: $last_poll";
881         }
882     );
883     Irssi::command_bind(
884         "twirssi_version",
885         sub {
886             &notice(
887 "Twirssi v$VERSION (r$REV);  Net::Twitter v$Net::Twitter::VERSION. "
888                   . "See details at http://tinyurl.com/twirssi" );
889         }
890     );
891     Irssi::command_bind(
892         "twitter_friend",
893         &gen_cmd(
894             "/twitter_friend <username>",
895             "create_friend",
896             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
897         )
898     );
899     Irssi::command_bind(
900         "twitter_unfriend",
901         &gen_cmd(
902             "/twitter_unfriend <username>",
903             "destroy_friend",
904             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
905         )
906     );
907     Irssi::command_bind( "twitter_updates", "get_updates" );
908     Irssi::signal_add_last( 'complete word' => \&sig_complete );
909
910     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
911     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
912     &notice(
913         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
914
915     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
916         eval "use WWW::Shorten::$provider;";
917
918         if ($@) {
919             &notice(
920 "Failed to load WWW::Shorten::$provider - either clear short_url_provider or install the CPAN module"
921             );
922         }
923     }
924
925     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
926         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
927     {
928         &cmd_login();
929     }
930
931 } else {
932     Irssi::active_win()
933       ->print( "Create a window named "
934           . Irssi::settings_get_str('twitter_window')
935           . " or change the value of twitter_window.  Then, reload twirssi." );
936 }
937