0805eab86a9a041878894f0366aa3c38d2d16e25
[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";
15 my ($REV) = '$Rev: 334 $' =~ /(\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     ( $nick, $id ) = split /:/, $id;
220     unless ( exists $id_map{$nick} ) {
221         &notice("Can't find a tweet from $nick to reply to!");
222         return;
223     }
224
225     $id = $id_map{__indexes}{$nick} unless $id;
226     unless ( $id_map{$nick}[$id] ) {
227         &notice("Can't find a tweet numbered $id from $nick to reply to!");
228         return;
229     }
230
231     # remove any @nick at the beginning of the reply, as we'll add it anyway
232     $data =~ s/^\s*\@?$nick\s*//;
233     $data = "\@$nick " . $data;
234
235     if ( Irssi::settings_get_str("short_url_provider") ) {
236         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
237             eval {
238                 my $short = makeashorterlink($url);
239                 $data =~ s/\Q$url/$short/g;
240             };
241         }
242     }
243
244     if ( length $data > 140 ) {
245         &notice(
246             "Tweet too long (" . length($data) . " characters) - aborted" );
247         return;
248     }
249
250     unless (
251         $twits{$username}->update(
252             { status => $data, in_reply_to_status_id => $id_map{$nick}[$id] }
253         )
254       )
255     {
256         &notice("Update failed");
257         return;
258     }
259
260     foreach ( $data =~ /@([-\w]+)/ ) {
261         $nicks{$1} = time;
262     }
263
264     my $away = 0;
265     if (    Irssi::settings_get_bool("tweet_to_away")
266         and $data !~ /\@\w/
267         and $data !~ /^[dD] / )
268     {
269         my $server =
270           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
271         if ($server) {
272             $server->send_raw("away :$data");
273             $away = 1;
274         } else {
275             &notice( "Can't find bitlbee server.",
276                 "Update bitlbee_server or disalbe tweet_to_away" );
277         }
278     }
279
280     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
281 }
282
283 sub gen_cmd {
284     my ( $usage_str, $api_name, $post_ref ) = @_;
285
286     return sub {
287         my ( $data, $server, $win ) = @_;
288
289         unless ($twit) {
290             &notice("Not logged in!  Use /twitter_login username pass!");
291             return;
292         }
293
294         $data =~ s/^\s+|\s+$//;
295         unless ($data) {
296             &notice("Usage: $usage_str");
297             return;
298         }
299
300         unless ( $twit->$api_name($data) ) {
301             &notice("$api_name failed");
302             return;
303         }
304
305         &$post_ref($data) if $post_ref;
306       }
307 }
308
309 sub cmd_switch {
310     my ( $data, $server, $win ) = @_;
311
312     $data =~ s/^\s+|\s+$//g;
313     if ( exists $twits{$data} ) {
314         &notice("Switching to $data");
315         $twit = $twits{$data};
316         $user = $data;
317     } else {
318         &notice("Unknown user $data");
319     }
320 }
321
322 sub cmd_logout {
323     my ( $data, $server, $win ) = @_;
324
325     $data =~ s/^\s+|\s+$//g;
326     if ( $data and exists $twits{$data} ) {
327         &notice("Logging out $data...");
328         $twits{$data}->end_session();
329         delete $twits{$data};
330     } elsif ($data) {
331         &notice("Unknown username '$data'");
332     } else {
333         &notice("Logging out $user...");
334         $twit->end_session();
335         undef $twit;
336         delete $twits{$user};
337         if ( keys %twits ) {
338             &cmd_switch( ( keys %twits )[0], $server, $win );
339         } else {
340             Irssi::timeout_remove($poll) if $poll;
341             undef $poll;
342         }
343     }
344 }
345
346 sub cmd_login {
347     my ( $data, $server, $win ) = @_;
348     my $pass;
349     if ($data) {
350         ( $user, $pass ) = split ' ', $data, 2;
351     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
352         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
353     {
354         my @user = split /\s*,\s*/, $autouser;
355         my @pass = split /\s*,\s*/, $autopass;
356         if ( @user != @pass ) {
357             &notice("Number of usernames doesn't match "
358                   . "the number of passwords - auto-login failed" );
359         } else {
360             my ( $u, $p );
361             while ( @user and @pass ) {
362                 $u = shift @user;
363                 $p = shift @pass;
364                 &cmd_login("$u $p");
365             }
366             return;
367         }
368     } else {
369         &notice("/twitter_login requires either a username and password "
370               . "or twitter_usernames and twitter_passwords to be set." );
371         return;
372     }
373
374     %friends = %nicks = ();
375
376     $twit = Net::Twitter->new(
377         username => $user,
378         password => $pass,
379         source   => "twirssi"
380     );
381
382     unless ( $twit->verify_credentials() ) {
383         &notice("Login as $user failed");
384         $twit = undef;
385         if ( keys %twits ) {
386             &cmd_switch( ( keys %twits )[0], $server, $win );
387         }
388         return;
389     }
390
391     if ($twit) {
392         my $rate_limit = $twit->rate_limit_status();
393         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
394             &notice("Rate limit exceeded, try again later");
395             $twit = undef;
396             return;
397         }
398
399         $twits{$user} = $twit;
400         Irssi::timeout_remove($poll) if $poll;
401         $poll = Irssi::timeout_add( 300 * 1000, \&get_updates, "" );
402         &notice("Logged in as $user, loading friends list...");
403         &load_friends();
404         &notice( "loaded friends: ", scalar keys %friends );
405         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
406             Irssi::settings_set_bool( "twirssi_first_run", 0 );
407             unless ( exists $friends{twirssi} ) {
408                 &notice("Welcome to twirssi!"
409                       . "  Perhaps you should add \@twirssi to your friends list,"
410                       . " so you can be notified when a new version is release?"
411                       . "  Just type /twitter_friend twirssi." );
412             }
413         }
414         %nicks = %friends;
415         $nicks{$user} = 0;
416         &get_updates;
417     } else {
418         &notice("Login failed");
419     }
420 }
421
422 sub cmd_upgrade {
423     my ( $data, $server, $win ) = @_;
424
425     my $loc = Irssi::settings_get_str("twirssi_location");
426     unless ( -w $loc ) {
427         &notice(
428 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
429         );
430         return;
431     }
432
433     if ( not -x "/usr/bin/md5sum" and not $data ) {
434         &notice(
435 "/usr/bin/md5sum can't be found - try '/twirssi_upgrade nomd5' to skip MD5 verification"
436         );
437         return;
438     }
439
440     my $md5;
441     unless ($data) {
442         eval { use Digest::MD5; };
443
444         if ($@) {
445             &notice(
446 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
447             );
448             return;
449         }
450
451         $md5 = get("http://twirssi.com/md5sum");
452         chomp $md5;
453         $md5 =~ s/ .*//;
454         unless ($md5) {
455             &notice("Failed to download md5sum from peeron!  Aborting.");
456             return;
457         }
458
459         unless ( open( CUR, $loc ) ) {
460             &notice(
461 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
462             );
463             return;
464         }
465
466         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
467         close CUR;
468
469         if ( $cur_md5 eq $md5 ) {
470             &notice("Current twirssi seems to be up to date.");
471             return;
472         }
473     }
474
475     my $URL = "http://twirssi.com/twirssi.pl";
476     &notice("Downloading twirssi from $URL");
477     LWP::Simple::getstore( $URL, "$loc.upgrade" );
478
479     unless ($data) {
480         unless ( open( NEW, "$loc.upgrade" ) ) {
481             &notice(
482 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
483             );
484             return;
485         }
486
487         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
488         close NEW;
489
490         if ( $new_md5 ne $md5 ) {
491             &notice("MD5 verification failed. expected $md5, got $new_md5");
492             return;
493         }
494     }
495
496     rename $loc, "$loc.backup"
497       or &notice("Failed to back up $loc: $!.  Aborting")
498       and return;
499     rename "$loc.upgrade", $loc
500       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
501       and return;
502
503     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
504     if ( -e "$dir/autorun/$file" ) {
505         &notice("Updating $dir/autorun/$file");
506         unlink "$dir/autorun/$file"
507           or &notice("Failed to remove old $file from autorun: $!");
508         symlink "../$file", "$dir/autorun/$file"
509           or &notice("Failed to create symlink in autorun directory: $!");
510     }
511
512     &notice("Download complete.  Reload twirssi with /script load $file");
513 }
514
515 sub load_friends {
516     my $fh   = shift;
517     my $page = 1;
518     my %new_friends;
519     while (1) {
520         print $fh "Loading friends page $page...\n" if ( $fh and &debug );
521         my $friends = $twit->friends( { page => $page } );
522         last unless $friends;
523         $new_friends{ $_->{screen_name} } = time foreach @$friends;
524         $page++;
525         last if @$friends == 0 or $page == 10;
526     }
527
528     my ( $added, $removed ) = ( 0, 0 );
529     print $fh "Scanning for new friends...\n" if ( $fh and &debug );
530     foreach ( keys %new_friends ) {
531         next if exists $friends{$_};
532         $friends{$_} = time;
533         $added++;
534     }
535
536     print $fh "Scanning for removed friends...\n" if ( $fh and &debug );
537     foreach ( keys %friends ) {
538         next if exists $new_friends{$_};
539         delete $friends{$_};
540         $removed++;
541     }
542
543     return ( $added, $removed );
544 }
545
546 sub get_updates {
547     print scalar localtime, " - get_updates starting" if &debug;
548
549     $window =
550       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
551     unless ($window) {
552         Irssi::active_win()
553           ->print( "Can't find a window named '"
554               . Irssi::settings_get_str('twitter_window')
555               . "'.  Create it or change the value of twitter_window" );
556     }
557     unless ($twit) {
558         &notice("Not logged in!  Use /twitter_login username pass!");
559         return;
560     }
561
562     my ( $fh, $filename ) = File::Temp::tempfile();
563     my $pid = fork();
564
565     if ($pid) {    # parent
566         Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
567         Irssi::pidwait_add($pid);
568     } elsif ( defined $pid ) {    # child
569         close STDIN;
570         close STDOUT;
571         close STDERR;
572
573         my $new_poll = time;
574
575         &do_updates( $fh, $user, $twit );
576         foreach ( keys %twits ) {
577             next if $_ eq $user;
578             &do_updates( $fh, $_, $twits{$_} );
579         }
580
581         my ( $added, $removed ) = &load_friends($fh);
582         if ( $added + $removed ) {
583             print $fh "%R***%n Friends list updated: ",
584               join( ", ",
585                 sprintf( "%d added",   $added ),
586                 sprintf( "%d removed", $removed ) ),
587               "\n";
588         }
589         print $fh "__friends__\n";
590         foreach ( sort keys %friends ) {
591             print $fh "$_ $friends{$_}\n";
592         }
593         print $fh $new_poll;
594         close $fh;
595         exit;
596     }
597     print scalar localtime, " - get_updates ends" if &debug;
598 }
599
600 sub do_updates {
601     my ( $fh, $username, $obj ) = @_;
602
603     print scalar localtime, " - Polling for updates for $username" if &debug;
604     my $tweets =
605       $obj->friends_timeline( { since => HTTP::Date::time2str($last_poll) } )
606       || [];
607     foreach my $t ( reverse @$tweets ) {
608         my $text = decode_entities( $t->{text} );
609         $text =~ s/%/%%/g;
610         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
611         my $reply = "tweet";
612         if (    Irssi::settings_get_bool("show_reply_context")
613             and $t->{in_reply_to_screen_name} ne $username
614             and $t->{in_reply_to_screen_name}
615             and not exists $friends{ $t->{in_reply_to_screen_name} } )
616         {
617             $nicks{ $t->{in_reply_to_screen_name} } = time;
618             my $context = $obj->show_status( $t->{in_reply_to_status_id} );
619             if ($context) {
620                 my $ctext = decode_entities( $context->{text} );
621                 $ctext =~ s/%/%%/g;
622                 $ctext =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
623                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
624                   $context->{id}, $username,
625                   $context->{user}{screen_name}, $ctext;
626                 $reply = "reply";
627             } else {
628                 print "Failed to get context from $t->{in_reply_to_screen_name}"
629                   if &debug;
630             }
631         }
632         next
633           if $t->{user}{screen_name} eq $username
634               and not Irssi::settings_get_bool("show_own_tweets");
635         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
636           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
637     }
638
639     print scalar localtime, " - Polling for replies" if &debug;
640     $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
641       || [];
642     foreach my $t ( reverse @$tweets ) {
643         next
644           if exists $friends{ $t->{user}{screen_name} };
645
646         my $text = decode_entities( $t->{text} );
647         $text =~ s/%/%%/g;
648         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
649         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
650           $t->{id}, $username, $t->{user}{screen_name}, $text;
651     }
652
653     print scalar localtime, " - Polling for DMs" if &debug;
654     $tweets =
655       $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
656       || [];
657     foreach my $t ( reverse @$tweets ) {
658         my $text = decode_entities( $t->{text} );
659         $text =~ s/%/%%/g;
660         $text =~ s/(^|\W)\@([-\w]+)/$1%B\@$2%n/g;
661         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
662           $t->{id}, $username, $t->{sender_screen_name}, $text;
663     }
664     print scalar localtime, " - Done" if &debug;
665 }
666
667 sub monitor_child {
668     my $data     = shift;
669     my $filename = $data->[0];
670
671     print scalar localtime, " - checking child log at $filename" if &debug;
672     my $old_last_poll = $last_poll;
673     if ( open FILE, $filename ) {
674         my @lines;
675         while (<FILE>) {
676             chomp;
677             last if /^__friends__/;
678             my %meta;
679             foreach my $key (qw/id account nick type/) {
680                 s/^$key:(\S+)\s*//;
681                 $meta{$key} = $1;
682             }
683
684             next if exists $tweet_cache{ $meta{id} };
685             $tweet_cache{ $meta{id} } = time;
686             my $account = "";
687             if ( $meta{account} ne $user ) {
688                 $account = "$meta{account}: ";
689             }
690
691             my $marker = "";
692             if (    $meta{type} ne 'dm'
693                 and Irssi::settings_get_bool("twirssi_track_replies")
694                 and $meta{nick}
695                 and $meta{id} )
696             {
697                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
698                 $id_map{ $meta{nick} }[$marker]   = $meta{id};
699                 $id_map{__indexes}{ $meta{nick} } = $marker;
700                 $marker                           = ":$marker";
701             }
702
703             if ( $meta{type} eq 'tweet' ) {
704                 push @lines, "[$account%B\@$meta{nick}%n$marker] $_\n",;
705             } elsif ( $meta{type} eq 'reply' ) {
706                 push @lines, "[$account\\--> %B\@$meta{nick}%n$marker] $_\n",;
707             } elsif ( $meta{type} eq 'dm' ) {
708                 push @lines, "[$account%B\@$meta{nick}%n (%%WDM%%n)] $_\n",;
709             } elsif ( $meta{type} eq 'debug' ) {
710                 push @lines, "debug: $_\n" if &debug,;
711             }
712         }
713
714         %friends = ();
715         while (<FILE>) {
716             if (/^\d+$/) {
717                 $last_poll = $_;
718                 last;
719             }
720             my ( $f, $t ) = split ' ', $_;
721             $nicks{$f} = $friends{$f} = $t;
722         }
723
724         if ( $last_poll != $old_last_poll ) {
725             print "new last_poll = $last_poll" if &debug;
726             foreach my $line (@lines) {
727                 chomp $line;
728                 $window->print( $line, MSGLEVEL_PUBLIC );
729                 foreach ( $line =~ /\@([-\w]+)/ ) {
730                     $nicks{$1} = time;
731                 }
732             }
733
734             close FILE;
735             unlink $filename
736               or warn "Failed to remove $filename: $!"
737               unless &debug;
738
739       # keep 10 minutes of cached tweets, to make sure we don't show duplicates.
740             foreach ( keys %tweet_cache ) {
741                 next if $tweet_cache{$_} > time - 600;
742                 delete $tweet_cache{$_};
743             }
744             return;
745         }
746     }
747
748     close FILE;
749     Irssi::timeout_add_once( 5000, 'monitor_child', [$filename] );
750 }
751
752 sub debug {
753     return Irssi::settings_get_bool("twirssi_debug");
754 }
755
756 sub notice {
757     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
758 }
759
760 sub sig_complete {
761     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
762
763     if (
764         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
765         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
766             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
767       )
768     {    # /twitter_reply gets a nick:num
769         @$complist = grep { $_ ne "__indexes" } grep /^\Q$word/i,
770           sort keys %id_map;
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