c4b4e4b857490a3a47f0df28d96362bff80bb3a9
[twirssi-net-twitter-lite.git] / twirssi.pl
1 use strict;
2 use Irssi;
3 use Irssi::Irc;
4 use HTTP::Date;
5 use HTML::Entities;
6 use File::Temp;
7 use LWP::Simple;
8 use Data::Dumper;
9 $Data::Dumper::Indent = 1;
10
11 use vars qw($VERSION %IRSSI);
12
13 $VERSION = "2.2.1beta";
14 my ($REV) = '$Rev: 569 $' =~ /(\d+)/;
15 %IRSSI = (
16     authors     => 'Dan Boger',
17     contact     => 'zigdon@gmail.com',
18     name        => 'twirssi',
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-03-19 11:44:03 -0700 (Thu, 19 Mar 2009) $',
24 );
25
26 my $window;
27 my $twit;
28 my %twits;
29 my $user;
30 my $defservice;
31 my $poll;
32 my $last_poll;
33 my %nicks;
34 my %friends;
35 my %tweet_cache;
36 my %id_map;
37 my $failwhale            = 0;
38 my %irssi_to_mirc_colors = (
39     '%k' => '01',
40     '%r' => '05',
41     '%g' => '03',
42     '%y' => '07',
43     '%b' => '02',
44     '%m' => '06',
45     '%c' => '10',
46     '%w' => '15',
47     '%K' => '14',
48     '%R' => '04',
49     '%G' => '09',
50     '%Y' => '08',
51     '%B' => '12',
52     '%M' => '13',
53     '%C' => '11',
54     '%W' => '00',
55 );
56
57 sub cmd_direct {
58     my ( $data, $server, $win ) = @_;
59
60     return unless &logged_in($twit);
61
62     my ( $target, $text ) = split ' ', $data, 2;
63     unless ( $target and $text ) {
64         &notice("Usage: /dm <nick> <message>");
65         return;
66     }
67
68     &cmd_direct_as( "$user $data", $server, $win );
69 }
70
71 sub cmd_direct_as {
72     my ( $data, $server, $win ) = @_;
73
74     return unless &logged_in($twit);
75
76     my ( $username, $target, $text ) = split ' ', $data, 3;
77     unless ( $username and $target and $text ) {
78         &notice("Usage: /dm_as <username> <nick> <message>");
79         return;
80     }
81
82     return unless $username = &valid_username($username);
83
84     eval {
85         if ( $twits{$username}
86             ->new_direct_message( { user => $target, text => $text } ) )
87         {
88             &notice("DM sent to $target");
89             $nicks{$target} = time;
90         } else {
91             my $error;
92             eval {
93                 $error = JSON::Any->jsonToObj( $twits{$username}->get_error() );
94                 $error = $error->{error};
95             };
96             die $error if $error;
97             &notice("DM to $target failed");
98         }
99     };
100
101     if ($@) {
102         &notice("DM caused an error: $@");
103         return;
104     }
105 }
106
107 sub cmd_tweet {
108     my ( $data, $server, $win ) = @_;
109
110     return unless &logged_in($twit);
111
112     $data =~ s/^\s+|\s+$//;
113     unless ($data) {
114         &notice("Usage: /tweet <update>");
115         return;
116     }
117
118     &cmd_tweet_as( "$user\@$defservice $data", $server, $win );
119 }
120
121 sub cmd_tweet_as {
122     my ( $data, $server, $win ) = @_;
123
124     return unless &logged_in($twit);
125
126     $data =~ s/^\s+|\s+$//;
127     $data =~ s/\s\s+/ /g;
128     my ( $username, $data ) = split ' ', $data, 2;
129
130     unless ( $username and $data ) {
131         &notice("Usage: /tweet_as <username> <update>");
132         return;
133     }
134
135     return unless $username = &valid_username($username);
136
137     $data = &shorten($data);
138
139     return if &too_long($data);
140
141     my $success = 1;
142     eval {
143         unless ( $twits{$username}->update($data) )
144         {
145             &notice("Update failed");
146             $success = 0;
147         }
148     };
149     return unless $success;
150
151     if ($@) {
152         &notice("Update caused an error: $@.  Aborted.");
153         return;
154     }
155
156     foreach ( $data =~ /@([-\w]+)/ ) {
157         $nicks{$1} = time;
158     }
159
160     my $away = &update_away($data);
161
162     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
163 }
164
165 sub cmd_reply {
166     my ( $data, $server, $win ) = @_;
167
168     return unless &logged_in($twit);
169
170     $data =~ s/^\s+|\s+$//;
171     unless ($data) {
172         &notice("Usage: /reply <nick[:num]> <update>");
173         return;
174     }
175
176     $data =~ s/^\s+|\s+$//;
177     my ( $id, $data ) = split ' ', $data, 2;
178     unless ( $id and $data ) {
179         &notice("Usage: /reply_as <nick[:num]> <update>");
180         return;
181     }
182
183     &cmd_reply_as( "$user $id $data", $server, $win );
184 }
185
186 sub cmd_reply_as {
187     my ( $data, $server, $win ) = @_;
188
189     unless ( Irssi::settings_get_bool("twirssi_track_replies") ) {
190         &notice("twirssi_track_replies is required in order to reply to "
191               . "specific tweets.  Either enable it, or just use /tweet "
192               . "\@username <text>." );
193         return;
194     }
195
196     return unless &logged_in($twit);
197
198     $data =~ s/^\s+|\s+$//;
199     my ( $username, $id, $data ) = split ' ', $data, 3;
200
201     unless ( $username and $data ) {
202         &notice("Usage: /reply_as <username> <nick[:num]> <update>");
203         return;
204     }
205
206     return unless $username = &valid_username($username);
207
208     my $nick;
209     $id =~ s/[^\w\d\-:]+//g;
210     ( $nick, $id ) = split /:/, $id;
211     unless ( exists $id_map{ lc $nick } ) {
212         &notice("Can't find a tweet from $nick to reply to!");
213         return;
214     }
215
216     $id = $id_map{__indexes}{$nick} unless $id;
217     unless ( $id_map{ lc $nick }[$id] ) {
218         &notice("Can't find a tweet numbered $id from $nick to reply to!");
219         return;
220     }
221
222     if ( Irssi::settings_get_bool("twirssi_replies_autonick") ) {
223
224         # remove any @nick at the beginning of the reply, as we'll add it anyway
225         $data =~ s/^\s*\@?$nick\s*//;
226         $data = "\@$nick " . $data;
227     }
228
229     $data = &shorten($data);
230
231     return if &too_long($data);
232
233     my $success = 1;
234     eval {
235         unless (
236             $twits{$username}->update(
237                 {
238                     status                => $data,
239                     in_reply_to_status_id => $id_map{ lc $nick }[$id]
240                 }
241             )
242           )
243         {
244             &notice("Update failed");
245             $success = 0;
246         }
247     };
248     return unless $success;
249
250     if ($@) {
251         &notice("Update caused an error: $@.  Aborted");
252         return;
253     }
254
255     foreach ( $data =~ /@([-\w]+)/ ) {
256         $nicks{$1} = time;
257     }
258
259     my $away = &update_away($data);
260
261     &notice( "Update sent" . ( $away ? " (and away msg set)" : "" ) );
262 }
263
264 sub gen_cmd {
265     my ( $usage_str, $api_name, $post_ref ) = @_;
266
267     return sub {
268         my ( $data, $server, $win ) = @_;
269
270         return unless &logged_in($twit);
271
272         $data =~ s/^\s+|\s+$//;
273         unless ($data) {
274             &notice("Usage: $usage_str");
275             return;
276         }
277
278         my $success = 1;
279         eval {
280             unless ( $twit->$api_name($data) )
281             {
282                 &notice("$api_name failed");
283                 $success = 0;
284             }
285         };
286         return unless $success;
287
288         if ($@) {
289             &notice("$api_name caused an error.  Aborted.");
290             return;
291         }
292
293         &$post_ref($data) if $post_ref;
294       }
295 }
296
297 sub cmd_switch {
298     my ( $data, $server, $win ) = @_;
299
300     $data =~ s/^\s+|\s+$//g;
301     $data = &normalize_username($data);
302     if ( exists $twits{$data} ) {
303         &notice("Switching to $data");
304         $twit = $twits{$data};
305         if ( $data =~ /(.*)\@(.*)/ ) {
306             $user       = $1;
307             $defservice = $2;
308         } else {
309             &notice("Couldn't figure out what service '$data' is on");
310         }
311     } else {
312         &notice("Unknown user $data");
313     }
314 }
315
316 sub cmd_logout {
317     my ( $data, $server, $win ) = @_;
318
319     $data =~ s/^\s+|\s+$//g;
320     $data = $user unless $data;
321     return unless $data = &valid_username($data);
322
323     &notice("Logging out $data...");
324     $twits{$data}->end_session();
325     delete $twits{$data};
326     undef $twit;
327     if ( keys %twits ) {
328         &cmd_switch( ( keys %twits )[0], $server, $win );
329     } else {
330         Irssi::timeout_remove($poll) if $poll;
331         undef $poll;
332     }
333 }
334
335 sub cmd_login {
336     my ( $data, $server, $win ) = @_;
337     my $pass;
338     if ($data) {
339         ( $user, $pass ) = split ' ', $data, 2;
340     } elsif ( my $autouser = Irssi::settings_get_str("twitter_usernames")
341         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
342     {
343         my @user = split /\s*,\s*/, $autouser;
344         my @pass = split /\s*,\s*/, $autopass;
345
346         # if a password ends with a '\', it was meant to escape the comma, and
347         # it should be concatinated with the next one
348         my @unescaped;
349         while (@pass) {
350             my $p = shift @pass;
351             while ( $p =~ /\\$/ and @pass ) {
352                 $p .= "," . shift @pass;
353             }
354             push @unescaped, $p;
355         }
356
357         if ( @user != @unescaped ) {
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 @unescaped ) {
363                 $u = shift @user;
364                 $p = shift @unescaped;
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     my $service;
378     if ( $user =~ /^(.*)@(twitter|identica)$/ ) {
379         ( $user, $service ) = ( $1, $2 );
380     } else {
381         $service = Irssi::settings_get_str("twirssi_default_service");
382     }
383     $defservice = $service = ucfirst lc $service;
384
385     eval "use Net::$service";
386     if ($@) {
387         &notice(
388             "Failed to load Net::$service when trying to log in as $user: $@");
389         return;
390     }
391
392     $twit = "Net::$service"->new(
393         username => $user,
394         password => $pass,
395         source   => "twirssi"
396     );
397
398     unless ( $twit->verify_credentials() ) {
399         &notice("Login as $user\@$service failed");
400         $twit = undef;
401         if ( keys %twits ) {
402             &cmd_switch( ( keys %twits )[0], $server, $win );
403         }
404         return;
405     }
406
407     if ($twit) {
408         my $rate_limit = $twit->rate_limit_status();
409         if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
410             &notice(
411                 "Rate limit exceeded, try again after $rate_limit->{reset_time}"
412             );
413             $twit = undef;
414             return;
415         }
416
417         $twits{"$user\@$service"} = $twit;
418         Irssi::timeout_remove($poll) if $poll;
419         $poll = Irssi::timeout_add( &get_poll_time * 1000, \&get_updates, "" );
420         &notice("Logged in as $user\@$service, loading friends list...");
421         &load_friends();
422         &notice( "loaded friends: ", scalar keys %friends );
423         if ( Irssi::settings_get_bool("twirssi_first_run") ) {
424             Irssi::settings_set_bool( "twirssi_first_run", 0 );
425             unless ( exists $friends{twirssi} ) {
426                 &notice("Welcome to twirssi!"
427                       . "  Perhaps you should add \@twirssi to your friends list,"
428                       . " so you can be notified when a new version is release?"
429                       . "  Just type /twitter_friend twirssi." );
430             }
431         }
432         %nicks = %friends;
433         $nicks{$user} = 0;
434         return 1;
435     } else {
436         &notice("Login failed");
437     }
438 }
439
440 sub cmd_add_search {
441     my ( $data, $server, $win ) = @_;
442
443     unless ( $twit and $twit->can('search') ) {
444         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
445               . "doesn't support searches." );
446         return;
447     }
448
449     $data =~ s/^\s+|\s+$//;
450     $data = lc $data;
451
452     unless ($data) {
453         &notice("Usage: /twitter_subscribe <topic>");
454         return;
455     }
456
457     if ( exists $id_map{__searches}{$user}{$data} ) {
458         &notice("Already had a subscription for '$data'");
459         return;
460     }
461
462     $id_map{__searches}{$user}{$data} = 1;
463     &notice("Added subscription for '$data'");
464 }
465
466 sub cmd_del_search {
467     my ( $data, $server, $win ) = @_;
468
469     unless ( $twit and $twit->can('search') ) {
470         &notice("ERROR: Your version of Net::Twitter ($Net::Twitter::VERSION) "
471               . "doesn't support searches." );
472         return;
473     }
474     $data =~ s/^\s+|\s+$//;
475     $data = lc $data;
476
477     unless ($data) {
478         &notice("Usage: /twitter_unsubscribe <topic>");
479         return;
480     }
481
482     unless ( exists $id_map{__searches}{$user}{$data} ) {
483         &notice("No subscription found for '$data'");
484         return;
485     }
486
487     delete $id_map{__searches}{$user}{$data};
488     &notice("Removed subscription for '$data'");
489 }
490
491 sub cmd_list_search {
492     my ( $data, $server, $win ) = @_;
493
494     my $found = 0;
495     foreach my $suser ( sort keys %{ $id_map{__searches} } ) {
496         my $topics;
497         foreach my $topic ( sort keys %{ $id_map{__searches}{$suser} } ) {
498             $topics = $topics ? "$topics, $topic" : $topic;
499         }
500         if ($topics) {
501             $found = 1;
502             &notice("Search subscriptions for \@$suser: $topics");
503         }
504     }
505
506     unless ($found) {
507         &notice("No search subscriptions set up");
508     }
509 }
510
511 sub cmd_upgrade {
512     my ( $data, $server, $win ) = @_;
513
514     my $loc = Irssi::settings_get_str("twirssi_location");
515     unless ( -w $loc ) {
516         &notice(
517 "$loc isn't writable, can't upgrade.  Perhaps you need to /set twirssi_location?"
518         );
519         return;
520     }
521
522     my $md5;
523     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
524         eval { use Digest::MD5; };
525
526         if ($@) {
527             &notice(
528 "Failed to load Digest::MD5.  Try '/twirssi_upgrade nomd5' to skip MD5 verification"
529             );
530             return;
531         }
532
533         $md5 = get("http://twirssi.com/md5sum");
534         chomp $md5;
535         $md5 =~ s/ .*//;
536         unless ($md5) {
537             &notice("Failed to download md5sum from peeron!  Aborting.");
538             return;
539         }
540
541         unless ( open( CUR, $loc ) ) {
542             &notice(
543 "Failed to read $loc.  Check that /set twirssi_location is set to the correct location."
544             );
545             return;
546         }
547
548         my $cur_md5 = Digest::MD5::md5_hex(<CUR>);
549         close CUR;
550
551         if ( $cur_md5 eq $md5 ) {
552             &notice("Current twirssi seems to be up to date.");
553             return;
554         }
555     }
556
557     my $URL =
558       Irssi::settings_get_bool("twirssi_upgrade_beta")
559       ? "http://github.com/zigdon/twirssi/raw/master/twirssi.pl"
560       : "http://twirssi.com/twirssi.pl";
561     &notice("Downloading twirssi from $URL");
562     LWP::Simple::getstore( $URL, "$loc.upgrade" );
563
564     unless ( $data or Irssi::settings_get_bool("twirssi_upgrade_beta") ) {
565         unless ( open( NEW, "$loc.upgrade" ) ) {
566             &notice(
567 "Failed to read $loc.upgrade.  Check that /set twirssi_location is set to the correct location."
568             );
569             return;
570         }
571
572         my $new_md5 = Digest::MD5::md5_hex(<NEW>);
573         close NEW;
574
575         if ( $new_md5 ne $md5 ) {
576             &notice("MD5 verification failed. expected $md5, got $new_md5");
577             return;
578         }
579     }
580
581     rename $loc, "$loc.backup"
582       or &notice("Failed to back up $loc: $!.  Aborting")
583       and return;
584     rename "$loc.upgrade", $loc
585       or &notice("Failed to rename $loc.upgrade: $!.  Aborting")
586       and return;
587
588     my ( $dir, $file ) = ( $loc =~ m{(.*)/([^/]+)$} );
589     if ( -e "$dir/autorun/$file" ) {
590         &notice("Updating $dir/autorun/$file");
591         unlink "$dir/autorun/$file"
592           or &notice("Failed to remove old $file from autorun: $!");
593         symlink "../$file", "$dir/autorun/$file"
594           or &notice("Failed to create symlink in autorun directory: $!");
595     }
596
597     &notice("Download complete.  Reload twirssi with /script load $file");
598 }
599
600 sub load_friends {
601     my $fh   = shift;
602     my $page = 1;
603     my %new_friends;
604     eval {
605         while (1)
606         {
607             print $fh "type:debug Loading friends page $page...\n"
608               if ( $fh and &debug );
609             my $friends = $twit->friends( { page => $page } );
610             last unless $friends;
611             $new_friends{ $_->{screen_name} } = time foreach @$friends;
612             $page++;
613             last if @$friends == 0 or $page == 10;
614         }
615     };
616
617     if ($@) {
618         print $fh "type:debug Error during friends list update.  Aborted.\n";
619         return;
620     }
621
622     my ( $added, $removed ) = ( 0, 0 );
623     print $fh "type:debug Scanning for new friends...\n" if ( $fh and &debug );
624     foreach ( keys %new_friends ) {
625         next if exists $friends{$_};
626         $friends{$_} = time;
627         $added++;
628     }
629
630     print $fh "type:debug Scanning for removed friends...\n"
631       if ( $fh and &debug );
632     foreach ( keys %friends ) {
633         next if exists $new_friends{$_};
634         delete $friends{$_};
635         $removed++;
636     }
637
638     return ( $added, $removed );
639 }
640
641 sub get_updates {
642     print scalar localtime, " - get_updates starting" if &debug;
643
644     $window =
645       Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
646     unless ($window) {
647         Irssi::active_win()
648           ->print( "Can't find a window named '"
649               . Irssi::settings_get_str('twitter_window')
650               . "'.  Create it or change the value of twitter_window" );
651     }
652
653     return unless &logged_in($twit);
654
655     my ( $fh, $filename ) = File::Temp::tempfile();
656     binmode( $fh, ":utf8" );
657     my $pid = fork();
658
659     if ($pid) {    # parent
660         Irssi::timeout_add_once( 5000, 'monitor_child', [ $filename, 0 ] );
661         Irssi::pidwait_add($pid);
662     } elsif ( defined $pid ) {    # child
663         close STDIN;
664         close STDOUT;
665         close STDERR;
666
667         my $new_poll = time;
668
669         my $error = 0;
670         foreach ( keys %twits ) {
671             $error += &do_updates( $fh, $_, $twits{$_} );
672         }
673
674         my ( $added, $removed ) = &load_friends($fh);
675         if ( $added + $removed ) {
676             print $fh "type:debug %R***%n Friends list updated: ",
677               join( ", ",
678                 sprintf( "%d added",   $added ),
679                 sprintf( "%d removed", $removed ) ),
680               "\n";
681         }
682         print $fh "__friends__\n";
683         foreach ( sort keys %friends ) {
684             print $fh "$_ $friends{$_}\n";
685         }
686
687         if ($error) {
688             print $fh "type:debug Update encountered errors.  Aborted\n";
689             print $fh $last_poll;
690         } else {
691             print $fh $new_poll;
692         }
693         close $fh;
694         exit;
695     }
696     print scalar localtime, " - get_updates ends" if &debug;
697 }
698
699 sub do_updates {
700     my ( $fh, $username, $obj ) = @_;
701
702     my $rate_limit = $obj->rate_limit_status();
703     if ( $rate_limit and $rate_limit->{remaining_hits} < 1 ) {
704         &notice("Rate limit exceeded for $username");
705         return 1;
706     }
707
708     print scalar localtime, " - Polling for updates for $username" if &debug;
709     my $tweets;
710     eval { $tweets = $obj->friends_timeline(); };
711
712     if ($@) {
713         print $fh
714           "type:debug Error during friends_timeline call: $@.  Aborted.\n";
715         return 1;
716     }
717
718     unless ( ref $tweets ) {
719         if ( $obj->can("get_error") ) {
720             my $error;
721             eval { $error = JSON::Any->jsonToObj( $obj->get_error() ) };
722             if ($@) { $error = $obj->get_error() }
723             print $fh "type:debug API Error during friends_timeline call: ",
724               "$error  Aborted.\n";
725         } else {
726             print $fh
727               "type:debug API Error during friends_timeline call. Aborted.\n";
728         }
729         return 1;
730     }
731
732     foreach my $t ( reverse @$tweets ) {
733         my $text = decode_entities( $t->{text} );
734         $text = &hilight($text);
735         my $reply = "tweet";
736         if (    Irssi::settings_get_bool("show_reply_context")
737             and $t->{in_reply_to_screen_name} ne $username
738             and $t->{in_reply_to_screen_name}
739             and not exists $friends{ $t->{in_reply_to_screen_name} } )
740         {
741             $nicks{ $t->{in_reply_to_screen_name} } = time;
742             my $context;
743             eval {
744                 $context = $obj->show_status( $t->{in_reply_to_status_id} );
745             };
746
747             if ($context) {
748                 my $ctext = decode_entities( $context->{text} );
749                 $ctext = &hilight($ctext);
750                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
751                     $ctext .=
752                         " -- http://twitter.com/$context->{user}{screen_name}"
753                       . "/status/$context->{id}";
754                 }
755                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
756                   $context->{id}, $username,
757                   $context->{user}{screen_name}, $ctext;
758                 $reply = "reply";
759             } elsif ($@) {
760                 print $fh "type:debug request to get context failed: $@";
761             } else {
762                 print $fh
763 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
764                   if &debug;
765             }
766         }
767         next
768           if $t->{user}{screen_name} eq $username
769               and not Irssi::settings_get_bool("show_own_tweets");
770         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
771             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
772               . "/status/$t->{id}";
773         }
774         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
775           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
776     }
777
778     print scalar localtime, " - Polling for replies" if &debug;
779     eval {
780         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
781           || [];
782     };
783
784     if ($@) {
785         print $fh "type:debug Error during replies call.  Aborted.\n";
786         return 1;
787     }
788
789     foreach my $t ( reverse @$tweets ) {
790         next
791           if exists $friends{ $t->{user}{screen_name} };
792
793         my $text = decode_entities( $t->{text} );
794         $text = &hilight($text);
795         if ( $t->{truncated} ) {
796             $text .= " -- http://twitter.com/$t->{user}{screen_name}"
797               . "/status/$t->{id}";
798         }
799         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
800           $t->{id}, $username, $t->{user}{screen_name}, $text;
801     }
802
803     print scalar localtime, " - Polling for DMs" if &debug;
804     eval {
805         $tweets =
806           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
807           || [];
808     };
809
810     if ($@) {
811         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
812         return 1;
813     }
814
815     foreach my $t ( reverse @$tweets ) {
816         my $text = decode_entities( $t->{text} );
817         $text = &hilight($text);
818         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
819           $t->{id}, $username, $t->{sender_screen_name}, $text;
820     }
821
822     print scalar localtime, " - Polling for subscriptions" if &debug;
823     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
824         my $search;
825         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
826             print $fh "type:debug searching for $topic since ",
827               "$id_map{__searches}{$username}{$topic}\n";
828             eval {
829                 $search = $obj->search(
830                     {
831                         q        => $topic,
832                         since_id => $id_map{__searches}{$username}{$topic}
833                     }
834                 );
835             };
836
837             if ($@) {
838                 print $fh
839                   "type:debug Error during search($topic) call.  Aborted.\n";
840                 return 1;
841             }
842
843             unless ( $search->{max_id} ) {
844                 print $fh
845 "type:debug Invalid search results when searching for $topic.",
846                   "  Aborted.\n";
847                 return 1;
848             }
849
850             $id_map{__searches}{$username}{$topic} = $search->{max_id};
851             printf $fh "id:%d account:%s type:searchid topic:%s\n",
852               $search->{max_id}, $username, $topic;
853
854             foreach my $t ( reverse @{ $search->{results} } ) {
855                 my $text = decode_entities( $t->{text} );
856                 $text = &hilight($text);
857                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
858                   $t->{id}, $username, $t->{from_user}, $topic, $text;
859             }
860         }
861     }
862
863     print scalar localtime, " - Done" if &debug;
864
865     return 0;
866 }
867
868 sub monitor_child {
869     my ($data)   = @_;
870     my $filename = $data->[0];
871     my $attempt  = $data->[1];
872
873     print scalar localtime, " - checking child log at $filename ($attempt)"
874       if &debug;
875     my $new_last_poll;
876
877     # first time we run we don't want to print out *everything*, so we just
878     # pretend
879     my $suppress = 0;
880     $suppress = 1 unless keys %tweet_cache;
881
882     if ( open FILE, $filename ) {
883         my @lines;
884         my %new_cache;
885         while (<FILE>) {
886             chomp;
887             last if /^__friends__/;
888             my $hilight = 0;
889             my %meta;
890             foreach my $key (qw/id account nick type topic/) {
891                 if (s/^$key:(\S+)\s*//) {
892                     $meta{$key} = $1;
893                 }
894             }
895
896             if ( not $meta{type} or $meta{type} ne 'searchid' ) {
897                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
898                     next;
899                 }
900
901                 $new_cache{ $meta{id} } = time;
902
903                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
904                     next;
905                 }
906             }
907
908             my $account = "";
909             if ( lc $meta{account} ne lc "$user\@$defservice" ) {
910                 $meta{account} =~ s/\@(\w+)$//;
911                 my $service = $1;
912                 if (
913                     lc $service eq
914                     lc Irssi::settings_get_str("twirssi_default_service") )
915                 {
916                     $account = "$meta{account}: ";
917                 } else {
918                     $account = "$meta{account}\@$service: ";
919                 }
920             }
921
922             my $marker = "";
923             if (    $meta{type} ne 'dm'
924                 and Irssi::settings_get_bool("twirssi_track_replies")
925                 and $meta{nick}
926                 and $meta{id} )
927             {
928                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
929                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
930                 $id_map{__indexes}{ $meta{nick} }  = $marker;
931                 $marker                            = ":$marker";
932             }
933
934             my $hilight_color =
935               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
936             my $nick =
937               '@' . substr( $meta{account}, 0, index( $meta{account}, "@" ) );
938             if ( $_ =~ /\Q$nick\E(?:\W|$)/i
939                 and Irssi::settings_get_bool("twirssi_hilights") )
940             {
941                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
942                 $hilight = MSGLEVEL_HILIGHT;
943             }
944
945             if ( $meta{type} =~ /tweet|reply/ ) {
946                 push @lines,
947                   [
948                     ( MSGLEVEL_PUBLIC | $hilight ),
949                     $meta{type}, $account, $meta{nick}, $marker, $_
950                   ];
951             } elsif ( $meta{type} eq 'search' ) {
952                 push @lines,
953                   [
954                     ( MSGLEVEL_PUBLIC | $hilight ),
955                     $meta{type}, $account, $meta{topic},
956                     $meta{nick}, $marker,  $_
957                   ];
958                 if (
959                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
960                     and $meta{id} >
961                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
962                 {
963                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
964                       $meta{id};
965                 }
966             } elsif ( $meta{type} eq 'dm' ) {
967                 push @lines,
968                   [
969                     ( MSGLEVEL_MSGS | $hilight ),
970                     $meta{type}, $account, $meta{nick}, $_
971                   ];
972             } elsif ( $meta{type} eq 'searchid' ) {
973                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
974                 if (
975                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
976                     and $meta{id} >=
977                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
978                 {
979                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
980                       $meta{id};
981                 } elsif (&debug) {
982                     print "Search '$meta{topic}' returned invalid id $meta{id}";
983                 }
984             } elsif ( $meta{type} eq 'error' ) {
985                 push @lines, [ MSGLEVEL_MSGS, $_ ];
986             } elsif ( $meta{type} eq 'debug' ) {
987                 print "$_" if &debug,;
988             } else {
989                 print "Unknown line type $meta{type}: $_" if &debug,;
990             }
991         }
992
993         %friends = ();
994         while (<FILE>) {
995             if (/^\d+$/) {
996                 $new_last_poll = $_;
997                 last;
998             }
999             my ( $f, $t ) = split ' ', $_;
1000             $nicks{$f} = $friends{$f} = $t;
1001         }
1002
1003         if ($new_last_poll) {
1004             print "new last_poll = $new_last_poll" if &debug;
1005             if ($suppress) {
1006                 print "First call, not printing updates" if &debug;
1007             } else {
1008                 foreach my $line (@lines) {
1009                     $window->printformat(
1010                         $line->[0],
1011                         "twirssi_" . $line->[1],
1012                         @$line[ 2 .. $#$line ]
1013                     );
1014                 }
1015             }
1016
1017             close FILE;
1018             unlink $filename
1019               or warn "Failed to remove $filename: $!"
1020               unless &debug;
1021
1022             # commit the pending cache lines to the actual cache, now that
1023             # we've printed our output
1024             %tweet_cache = ( %tweet_cache, %new_cache );
1025
1026             # keep enough cached tweets, to make sure we don't show duplicates.
1027             foreach ( keys %tweet_cache ) {
1028                 next if $tweet_cache{$_} >= $last_poll - 3600;
1029                 delete $tweet_cache{$_};
1030             }
1031             $last_poll = $new_last_poll;
1032
1033             # save id_map hash
1034             if ( keys %id_map
1035                 and my $file =
1036                 Irssi::settings_get_str("twirssi_replies_store") )
1037             {
1038                 if ( open JSON, ">$file" ) {
1039                     print JSON JSON::Any->objToJson( \%id_map );
1040                     close JSON;
1041                 } else {
1042                     &ccrap("Failed to write replies to $file: $!");
1043                 }
1044             }
1045             $failwhale = 0;
1046             return;
1047         }
1048     }
1049
1050     close FILE;
1051
1052     if ( $attempt < 24 ) {
1053         Irssi::timeout_add_once( 5000, 'monitor_child',
1054             [ $filename, $attempt + 1 ] );
1055     } else {
1056         print "Giving up on polling $filename" if &debug;
1057         unlink $filename unless &debug;
1058
1059         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1060
1061         my $since;
1062         my @time = localtime($last_poll);
1063         if ( time - $last_poll < 24 * 60 * 60 ) {
1064             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1065         } else {
1066             $since = scalar localtime($last_poll);
1067         }
1068
1069         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1070             foreach my $whale (
1071                 q{     v  v        v},
1072                 q{     |  |  v     |  v},
1073                 q{     | .-, |     |  |},
1074                 q{  .--./ /  |  _.---.| },
1075                 q{   '-. (__..-"       \\},
1076                 q{      \\          a    |},
1077                 q{       ',.__.   ,__.-'/},
1078                 q{         '--/_.'----'`}
1079               )
1080             {
1081                 &ccrap($whale);
1082             }
1083             $failwhale = 1;
1084         }
1085         &ccrap("Haven't been able to get updated tweets since $since");
1086     }
1087 }
1088
1089 sub debug {
1090     return Irssi::settings_get_bool("twirssi_debug");
1091 }
1092
1093 sub notice {
1094     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1095 }
1096
1097 sub ccrap {
1098     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1099 }
1100
1101 sub update_away {
1102     my $data = shift;
1103
1104     if (    Irssi::settings_get_bool("tweet_to_away")
1105         and $data !~ /\@\w/
1106         and $data !~ /^[dD] / )
1107     {
1108         my $server =
1109           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1110         if ($server) {
1111             $server->send_raw("away :$data");
1112             return 1;
1113         } else {
1114             &ccrap( "Can't find bitlbee server.",
1115                 "Update bitlbee_server or disable tweet_to_away" );
1116             return 0;
1117         }
1118     }
1119
1120     return 0;
1121 }
1122
1123 sub too_long {
1124     my $data    = shift;
1125     my $noalert = shift;
1126
1127     if ( length $data > 140 ) {
1128         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1129           unless $noalert;
1130         return 1;
1131     }
1132
1133     return 0;
1134 }
1135
1136 sub valid_username {
1137     my $username = shift;
1138
1139     $username = &normalize_username($username);
1140
1141     unless ( exists $twits{$username} ) {
1142         &notice("Unknown username $username");
1143         return undef;
1144     }
1145
1146     return $username;
1147 }
1148
1149 sub logged_in {
1150     my $obj = shift;
1151     unless ($obj) {
1152         &notice("Not logged in!  Use /twitter_login username pass!");
1153         return 0;
1154     }
1155
1156     return 1;
1157 }
1158
1159 sub sig_complete {
1160     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1161
1162     if (
1163         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1164         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1165             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1166       )
1167     {    # /twitter_reply gets a nick:num
1168         $word =~ s/^@//;
1169         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1170           sort { $nicks{$b} <=> $nicks{$a} }
1171           grep /^\Q$word/i,
1172           keys %{ $id_map{__indexes} };
1173     }
1174
1175     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1176     # arg to dm)
1177     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1178         my $prefix = $word =~ s/^@//;
1179         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1180         push @$complist, grep /^\Q$word/i,
1181           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1182         @$complist = map { "\@$_" } @$complist if $prefix;
1183     }
1184 }
1185
1186 sub event_send_text {
1187     my ( $line, $server, $win ) = @_;
1188     my $awin = Irssi::active_win();
1189
1190     # if the window where we got our text was the twitter window, and the user
1191     # wants to be lazy, tweet away!
1192     if ( ( $awin->get_active_name() eq $window->{name} )
1193         and Irssi::settings_get_bool("tweet_window_input") )
1194     {
1195         &cmd_tweet( $line, $server, $win );
1196     }
1197 }
1198
1199 sub get_poll_time {
1200     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1201     return $poll if $poll >= 60;
1202     return 60;
1203 }
1204
1205 sub hilight {
1206     my $text = shift;
1207
1208     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1209         my $c = Irssi::settings_get_str("twirssi_nick_color");
1210         $c = $irssi_to_mirc_colors{$c};
1211         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1212     }
1213     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1214         my $c = Irssi::settings_get_str("twirssi_topic_color");
1215         $c = $irssi_to_mirc_colors{$c};
1216         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1217     }
1218     $text =~ s/[\n\r]/ /g;
1219
1220     return $text;
1221 }
1222
1223 sub shorten {
1224     my $data = shift;
1225
1226     my $provider = Irssi::settings_get_str("short_url_provider");
1227     if (
1228         (
1229             Irssi::settings_get_bool("twirssi_always_shorten")
1230             or &too_long( $data, 1 )
1231         )
1232         and $provider
1233       )
1234     {
1235         my @args;
1236         if ( $provider eq 'Bitly' ) {
1237             @args[ 1, 2 ] = split ',',
1238               Irssi::settings_get_str("short_url_args"), 2;
1239             unless ( @args == 3 ) {
1240                 &ccrap(
1241                     "WWW::Shorten::Bitly requires a username and API key.",
1242                     "Set short_url_args to username,API_key or change your",
1243                     "short_url_provider."
1244                 );
1245                 return $data;
1246             }
1247         }
1248
1249         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1250             eval {
1251                 $args[0] = $url;
1252                 my $short = makeashorterlink(@args);
1253                 if ($short) {
1254                     $data =~ s/\Q$url/$short/g;
1255                 } else {
1256                     &notice("Failed to shorten $url!");
1257                 }
1258             };
1259         }
1260     }
1261
1262     return $data;
1263 }
1264
1265 sub normalize_username {
1266     my $user = shift;
1267
1268     my ( $username, $service ) = split /\@/, $user, 2;
1269     if ($service) {
1270         $service = ucfirst lc $service;
1271     } else {
1272         $service =
1273           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1274         unless ( exists $twits{"$username\@$service"} ) {
1275             $service = undef;
1276             foreach my $t ( sort keys %twits ) {
1277                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1278                 $service = $1;
1279                 last;
1280             }
1281
1282             unless ($service) {
1283                 &notice("Can't find a logged in user '$user'");
1284             }
1285         }
1286     }
1287
1288     return "$username\@$service";
1289 }
1290
1291 Irssi::signal_add( "send text", "event_send_text" );
1292
1293 Irssi::theme_register(
1294     [
1295         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1296         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1297         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1298         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1299         'twirssi_error',  'ERROR: $0',
1300     ]
1301 );
1302
1303 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1304 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1305 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1306 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1307 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1308 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1309 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1310 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1311 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1312 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1313 Irssi::settings_add_str( "twirssi", "twirssi_location",
1314     ".irssi/scripts/twirssi.pl" );
1315 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1316     ".irssi/scripts/twirssi.json" );
1317 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1318 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1319 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1320 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1321 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1322 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1323 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1324 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1325 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1326 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1327 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1328 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1329 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1330
1331 $last_poll = time - &get_poll_time;
1332 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1333 if ( !$window ) {
1334     Irssi::active_win()
1335       ->print( "Couldn't find a window named '"
1336           . Irssi::settings_get_str('twitter_window')
1337           . "', trying to create it." );
1338     $window =
1339       Irssi::Windowitem::window_create(
1340         Irssi::settings_get_str('twitter_window'), 1 );
1341     $window->set_name( Irssi::settings_get_str('twitter_window') );
1342 }
1343
1344 if ($window) {
1345     Irssi::command_bind( "dm",                         "cmd_direct" );
1346     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1347     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1348     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1349     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1350     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1351     Irssi::command_bind( "twitter_login",              "cmd_login" );
1352     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1353     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1354     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1355     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1356     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1357     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1358     Irssi::command_bind( "twitter_updates",            "get_updates" );
1359     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1360         Irssi::command_bind( "reply",    "cmd_reply" );
1361         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1362     }
1363     Irssi::command_bind(
1364         "twirssi_dump",
1365         sub {
1366             print "twits: ", join ", ",
1367               map { "u: $_->{username}\@" . ref($_) } values %twits;
1368             print "selected: $user\@$defservice";
1369             print "friends: ", join ", ", sort keys %friends;
1370             print "nicks: ",   join ", ", sort keys %nicks;
1371             print "searches: ", Dumper \%{ $id_map{__searches} };
1372             print "last poll: $last_poll";
1373             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1374                 print DUMP Dumper \%tweet_cache;
1375                 close DUMP;
1376                 print "cache written out to /tmp/twirssi.cache.txt";
1377             }
1378         }
1379     );
1380     Irssi::command_bind(
1381         "twirssi_version",
1382         sub {
1383             &notice("Twirssi v$VERSION (r$REV); "
1384                   . "Net::Twitter v$Net::Twitter::VERSION. "
1385                   . "JSON in use: "
1386                   . JSON::Any::handler()
1387                   . ".  See details at http://twirssi.com/" );
1388         }
1389     );
1390     Irssi::command_bind(
1391         "twitter_friend",
1392         &gen_cmd(
1393             "/twitter_friend <username>",
1394             "create_friend",
1395             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1396         )
1397     );
1398     Irssi::command_bind(
1399         "twitter_unfriend",
1400         &gen_cmd(
1401             "/twitter_unfriend <username>",
1402             "destroy_friend",
1403             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1404         )
1405     );
1406     Irssi::command_bind(
1407         "twitter_device_updates",
1408         &gen_cmd(
1409             "/twitter_device_updates none|im|sms",
1410             "update_delivery_device",
1411             sub { &notice("Device updated to $_[0]"); }
1412         )
1413     );
1414     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1415
1416     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1417     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1418     &notice(
1419         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1420
1421     my $file = Irssi::settings_get_str("twirssi_replies_store");
1422     if ( $file and -r $file ) {
1423         if ( open( JSON, $file ) ) {
1424             local $/;
1425             my $json = <JSON>;
1426             close JSON;
1427             eval {
1428                 my $ref = JSON::Any->jsonToObj($json);
1429                 %id_map = %$ref;
1430                 my $num = keys %{ $id_map{__indexes} };
1431                 &notice( sprintf "Loaded old replies from %d contact%s.",
1432                     $num, ( $num == 1 ? "" : "s" ) );
1433                 &cmd_list_search;
1434             };
1435         } else {
1436             &notice("Failed to load old replies from $file: $!");
1437         }
1438     }
1439
1440     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1441         &notice("Loading WWW::Shorten::$provider...");
1442         eval "use WWW::Shorten::$provider;";
1443
1444         if ($@) {
1445             &notice(
1446                 "Failed to load WWW::Shorten::$provider - either clear",
1447                 "short_url_provider or install the CPAN module"
1448             );
1449         }
1450     }
1451
1452     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1453         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1454     {
1455         &cmd_login();
1456         &get_updates;
1457     }
1458
1459 } else {
1460     Irssi::active_win()
1461       ->print( "Create a window named "
1462           . Irssi::settings_get_str('twitter_window')
1463           . " or change the value of twitter_window.  Then, reload twirssi." );
1464 }
1465
1466 # vim: set sts=4 expandtab: