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