r554 - Fix hilighting given @service
[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.1.3beta";
14 my ($REV) = '$Rev: 554 $' =~ /(\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-15 23:09:56 -0700 (Sun, 15 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                 printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
751                   $context->{id}, $username,
752                   $context->{user}{screen_name}, $ctext;
753                 if ( $context->{truncated} and ref($obj) ne 'Net::Identica' ) {
754                     printf $fh "id:%s account:%s nick:%s type:ellispis %s\n",
755                       $context->{id} . "-url", $username,
756                       $context->{user}{screen_name},
757 "http://twitter.com/$context->{user}{screen_name}/status/$context->{id}";
758                 }
759                 $reply = "reply";
760             } elsif ($@) {
761                 print $fh "type:debug request to get context failed: $@";
762             } else {
763                 print $fh
764 "type:debug Failed to get context from $t->{in_reply_to_screen_name}\n"
765                   if &debug;
766             }
767         }
768         next
769           if $t->{user}{screen_name} eq $username
770               and not Irssi::settings_get_bool("show_own_tweets");
771         printf $fh "id:%d account:%s nick:%s type:%s %s\n",
772           $t->{id}, $username, $t->{user}{screen_name}, $reply, $text;
773         if ( $t->{truncated} and ref($obj) ne 'Net::Identica' ) {
774             printf $fh "id:%s account:%s nick:%s type:ellispis %s\n",
775               $t->{id} . "-url", $username,
776               $t->{user}{screen_name},
777               "http://twitter.com/$t->{user}{screen_name}/status/$t->{id}";
778         }
779     }
780
781     print scalar localtime, " - Polling for replies" if &debug;
782     eval {
783         $tweets = $obj->replies( { since => HTTP::Date::time2str($last_poll) } )
784           || [];
785     };
786
787     if ($@) {
788         print $fh "type:debug Error during replies call.  Aborted.\n";
789         return 1;
790     }
791
792     foreach my $t ( reverse @$tweets ) {
793         next
794           if exists $friends{ $t->{user}{screen_name} };
795
796         my $text = decode_entities( $t->{text} );
797         $text = &hilight($text);
798         printf $fh "id:%d account:%s nick:%s type:tweet %s\n",
799           $t->{id}, $username, $t->{user}{screen_name}, $text;
800         if ( $t->{truncated} ) {
801             printf $fh "id:%s account:%s nick:%s type:ellispis %s\n",
802               $t->{id} . "-url", $username,
803               $t->{user}{screen_name},
804               "http://twitter.com/$t->{user}{screen_name}/status/$t->{id}";
805         }
806     }
807
808     print scalar localtime, " - Polling for DMs" if &debug;
809     eval {
810         $tweets =
811           $obj->direct_messages( { since => HTTP::Date::time2str($last_poll) } )
812           || [];
813     };
814
815     if ($@) {
816         print $fh "type:debug Error during direct_messages call.  Aborted.\n";
817         return 1;
818     }
819
820     foreach my $t ( reverse @$tweets ) {
821         my $text = decode_entities( $t->{text} );
822         $text = &hilight($text);
823         printf $fh "id:%d account:%s nick:%s type:dm %s\n",
824           $t->{id}, $username, $t->{sender_screen_name}, $text;
825     }
826
827     print scalar localtime, " - Polling for subscriptions" if &debug;
828     if ( $obj->can('search') and $id_map{__searches}{$username} ) {
829         my $search;
830         foreach my $topic ( sort keys %{ $id_map{__searches}{$username} } ) {
831             print $fh "type:debug searching for $topic since ",
832               "$id_map{__searches}{$username}{$topic}\n";
833             eval {
834                 $search = $obj->search(
835                     {
836                         q        => $topic,
837                         since_id => $id_map{__searches}{$username}{$topic}
838                     }
839                 );
840             };
841
842             if ($@) {
843                 print $fh
844                   "type:debug Error during search($topic) call.  Aborted.\n";
845                 return 1;
846             }
847
848             unless ( $search->{max_id} ) {
849                 print $fh
850 "type:debug Invalid search results when searching for $topic.",
851                   "  Aborted.\n";
852                 return 1;
853             }
854
855             $id_map{__searches}{$username}{$topic} = $search->{max_id};
856             printf $fh "id:%d account:%s type:searchid topic:%s\n",
857               $search->{max_id}, $username, $topic;
858
859             foreach my $t ( reverse @{ $search->{results} } ) {
860                 my $text = decode_entities( $t->{text} );
861                 $text = &hilight($text);
862                 printf $fh "id:%d account:%s nick:%s type:search topic:%s %s\n",
863                   $t->{id}, $username, $t->{from_user}, $topic, $text;
864             }
865         }
866     }
867
868     print scalar localtime, " - Done" if &debug;
869
870     return 0;
871 }
872
873 sub monitor_child {
874     my ($data)   = @_;
875     my $filename = $data->[0];
876     my $attempt  = $data->[1];
877
878     print scalar localtime, " - checking child log at $filename ($attempt)"
879       if &debug;
880     my $new_last_poll;
881
882     # first time we run we don't want to print out *everything*, so we just
883     # pretend
884     my $suppress = 0;
885     $suppress = 1 unless keys %tweet_cache;
886
887     if ( open FILE, $filename ) {
888         my @lines;
889         my %new_cache;
890         while (<FILE>) {
891             chomp;
892             last if /^__friends__/;
893             my $hilight = 0;
894             my %meta;
895             foreach my $key (qw/id account nick type topic/) {
896                 if (s/^$key:(\S+)\s*//) {
897                     $meta{$key} = $1;
898                 }
899             }
900
901             if ( not $meta{type} or $meta{type} ne 'searchid' ) {
902                 if ( exists $meta{id} and exists $new_cache{ $meta{id} } ) {
903                     next;
904                 }
905
906                 $new_cache{ $meta{id} } = time;
907
908                 if ( exists $meta{id} and exists $tweet_cache{ $meta{id} } ) {
909                     next;
910                 }
911             }
912
913             my $account = "";
914             if ( lc $meta{account} ne lc "$user\@$defservice" ) {
915                 $meta{account} =~ s/\@(\w+)$//;
916                 my $service = $1;
917                 if (
918                     lc $service eq
919                     lc Irssi::settings_get_str("twirssi_default_service") )
920                 {
921                     $account = "$meta{account}: ";
922                 } else {
923                     $account = "$meta{account}\@$service: ";
924                 }
925             }
926
927             my $marker = "";
928             if (    $meta{type} ne 'dm'
929                 and Irssi::settings_get_bool("twirssi_track_replies")
930                 and $meta{nick}
931                 and $meta{id} )
932             {
933                 $marker = ( $id_map{__indexes}{ $meta{nick} } + 1 ) % 100;
934                 $id_map{ lc $meta{nick} }[$marker] = $meta{id};
935                 $id_map{__indexes}{ $meta{nick} }  = $marker;
936                 $marker                            = ":$marker";
937             }
938
939             my $hilight_color =
940               $irssi_to_mirc_colors{ Irssi::settings_get_str("hilight_color") };
941             if ( $_ eq '@'.substr($meta{account}, 0, index($meta{account}, "@"))
942                 and Irssi::settings_get_bool("twirssi_hilights") )
943             {
944                 $meta{nick} = "\cC$hilight_color$meta{nick}\cO";
945                 $hilight = MSGLEVEL_HILIGHT;
946             }
947
948             if ( $meta{type} =~ /tweet|reply/ ) {
949                 push @lines,
950                   [
951                     ( MSGLEVEL_PUBLIC | $hilight ),
952                     $meta{type}, $account, $meta{nick}, $marker, $_
953                   ];
954             } elsif ( $meta{type} eq 'ellispis' ) {
955                 push @lines,
956                   [ MSGLEVEL_PUBLIC, "tweet", $account, $meta{nick}, "", $_ ];
957             } elsif ( $meta{type} eq 'search' ) {
958                 push @lines,
959                   [
960                     ( MSGLEVEL_PUBLIC | $hilight ),
961                     $meta{type}, $account, $meta{topic},
962                     $meta{nick}, $marker,  $_
963                   ];
964                 if (
965                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
966                     and $meta{id} >
967                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
968                 {
969                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
970                       $meta{id};
971                 }
972             } elsif ( $meta{type} eq 'dm' ) {
973                 push @lines,
974                   [
975                     ( MSGLEVEL_MSGS | $hilight ),
976                     $meta{type}, $account, $meta{nick}, $_
977                   ];
978             } elsif ( $meta{type} eq 'searchid' ) {
979                 print "Search '$meta{topic}' returned id $meta{id}" if &debug;
980                 if (
981                     exists $id_map{__searches}{ $meta{account} }{ $meta{topic} }
982                     and $meta{id} >=
983                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } )
984                 {
985                     $id_map{__searches}{ $meta{account} }{ $meta{topic} } =
986                       $meta{id};
987                 } elsif (&debug) {
988                     print "Search '$meta{topic}' returned invalid id $meta{id}";
989                 }
990             } elsif ( $meta{type} eq 'error' ) {
991                 push @lines, [ MSGLEVEL_MSGS, $_ ];
992             } elsif ( $meta{type} eq 'debug' ) {
993                 print "$_" if &debug,;
994             } else {
995                 print "Unknown line type $meta{type}: $_" if &debug,;
996             }
997         }
998
999         %friends = ();
1000         while (<FILE>) {
1001             if (/^\d+$/) {
1002                 $new_last_poll = $_;
1003                 last;
1004             }
1005             my ( $f, $t ) = split ' ', $_;
1006             $nicks{$f} = $friends{$f} = $t;
1007         }
1008
1009         if ($new_last_poll) {
1010             print "new last_poll = $new_last_poll" if &debug;
1011             if ($suppress) {
1012                 print "First call, not printing updates" if &debug;
1013             } else {
1014                 foreach my $line (@lines) {
1015                     $window->printformat(
1016                         $line->[0],
1017                         "twirssi_" . $line->[1],
1018                         @$line[ 2 .. $#$line ]
1019                     );
1020                 }
1021             }
1022
1023             close FILE;
1024             unlink $filename
1025               or warn "Failed to remove $filename: $!"
1026               unless &debug;
1027
1028             # commit the pending cache lines to the actual cache, now that
1029             # we've printed our output
1030             %tweet_cache = ( %tweet_cache, %new_cache );
1031
1032             # keep enough cached tweets, to make sure we don't show duplicates.
1033             foreach ( keys %tweet_cache ) {
1034                 next if $tweet_cache{$_} >= $last_poll - 3600;
1035                 delete $tweet_cache{$_};
1036             }
1037             $last_poll = $new_last_poll;
1038
1039             # save id_map hash
1040             if ( keys %id_map
1041                 and my $file =
1042                 Irssi::settings_get_str("twirssi_replies_store") )
1043             {
1044                 if ( open JSON, ">$file" ) {
1045                     print JSON JSON::Any->objToJson( \%id_map );
1046                     close JSON;
1047                 } else {
1048                     &ccrap("Failed to write replies to $file: $!");
1049                 }
1050             }
1051             $failwhale = 0;
1052             return;
1053         }
1054     }
1055
1056     close FILE;
1057
1058     if ( $attempt < 24 ) {
1059         Irssi::timeout_add_once( 5000, 'monitor_child',
1060             [ $filename, $attempt + 1 ] );
1061     } else {
1062         print "Giving up on polling $filename" if &debug;
1063         unlink $filename unless &debug;
1064
1065         return unless Irssi::settings_get_bool("twirssi_notify_timeouts");
1066
1067         my $since;
1068         my @time = localtime($last_poll);
1069         if ( time - $last_poll < 24 * 60 * 60 ) {
1070             $since = sprintf( "%d:%02d", @time[ 2, 1 ] );
1071         } else {
1072             $since = scalar localtime($last_poll);
1073         }
1074
1075         if ( not $failwhale and time - $last_poll > 60 * 60 ) {
1076             foreach my $whale (
1077                 q{     v  v        v},
1078                 q{     |  |  v     |  v},
1079                 q{     | .-, |     |  |},
1080                 q{  .--./ /  |  _.---.| },
1081                 q{   '-. (__..-"       \\},
1082                 q{      \\          a    |},
1083                 q{       ',.__.   ,__.-'/},
1084                 q{         '--/_.'----'`}
1085               )
1086             {
1087                 &ccrap($whale);
1088             }
1089             $failwhale = 1;
1090         }
1091         &ccrap("Haven't been able to get updated tweets since $since");
1092     }
1093 }
1094
1095 sub debug {
1096     return Irssi::settings_get_bool("twirssi_debug");
1097 }
1098
1099 sub notice {
1100     $window->print( "%R***%n @_", MSGLEVEL_PUBLIC );
1101 }
1102
1103 sub ccrap {
1104     $window->print( "%R***%n @_", MSGLEVEL_CLIENTCRAP );
1105 }
1106
1107 sub update_away {
1108     my $data = shift;
1109
1110     if (    Irssi::settings_get_bool("tweet_to_away")
1111         and $data !~ /\@\w/
1112         and $data !~ /^[dD] / )
1113     {
1114         my $server =
1115           Irssi::server_find_tag( Irssi::settings_get_str("bitlbee_server") );
1116         if ($server) {
1117             $server->send_raw("away :$data");
1118             return 1;
1119         } else {
1120             &ccrap( "Can't find bitlbee server.",
1121                 "Update bitlbee_server or disable tweet_to_away" );
1122             return 0;
1123         }
1124     }
1125
1126     return 0;
1127 }
1128
1129 sub too_long {
1130     my $data    = shift;
1131     my $noalert = shift;
1132
1133     if ( length $data > 140 ) {
1134         &notice( "Tweet too long (" . length($data) . " characters) - aborted" )
1135           unless $noalert;
1136         return 1;
1137     }
1138
1139     return 0;
1140 }
1141
1142 sub valid_username {
1143     my $username = shift;
1144
1145     $username = &normalize_username($username);
1146
1147     unless ( exists $twits{$username} ) {
1148         &notice("Unknown username $username");
1149         return undef;
1150     }
1151
1152     return $username;
1153 }
1154
1155 sub logged_in {
1156     my $obj = shift;
1157     unless ($obj) {
1158         &notice("Not logged in!  Use /twitter_login username pass!");
1159         return 0;
1160     }
1161
1162     return 1;
1163 }
1164
1165 sub sig_complete {
1166     my ( $complist, $window, $word, $linestart, $want_space ) = @_;
1167
1168     if (
1169         $linestart =~ /^\/twitter_reply(?:_as)?\s*$/
1170         or ( Irssi::settings_get_bool("twirssi_use_reply_aliases")
1171             and $linestart =~ /^\/reply(?:_as)?\s*$/ )
1172       )
1173     {    # /twitter_reply gets a nick:num
1174         $word =~ s/^@//;
1175         @$complist = map { "$_:$id_map{__indexes}{$_}" }
1176           sort { $nicks{$b} <=> $nicks{$a} }
1177           grep /^\Q$word/i,
1178           keys %{ $id_map{__indexes} };
1179     }
1180
1181     # /tweet, /tweet_as, /dm, /dm_as - complete @nicks (and nicks as the first
1182     # arg to dm)
1183     if ( $linestart =~ /^\/(?:tweet|dm)/ ) {
1184         my $prefix = $word =~ s/^@//;
1185         $prefix = 0 if $linestart eq '/dm' or $linestart eq '/dm_as';
1186         push @$complist, grep /^\Q$word/i,
1187           sort { $nicks{$b} <=> $nicks{$a} } keys %nicks;
1188         @$complist = map { "\@$_" } @$complist if $prefix;
1189     }
1190 }
1191
1192 sub event_send_text {
1193     my ( $line, $server, $win ) = @_;
1194     my $awin = Irssi::active_win();
1195
1196     # if the window where we got our text was the twitter window, and the user
1197     # wants to be lazy, tweet away!
1198     if ( ( $awin->get_active_name() eq $window->{name} )
1199         and Irssi::settings_get_bool("tweet_window_input") )
1200     {
1201         &cmd_tweet( $line, $server, $win );
1202     }
1203 }
1204
1205 sub get_poll_time {
1206     my $poll = Irssi::settings_get_int("twitter_poll_interval");
1207     return $poll if $poll >= 60;
1208     return 60;
1209 }
1210
1211 sub hilight {
1212     my $text = shift;
1213
1214     if ( Irssi::settings_get_str("twirssi_nick_color") ) {
1215         my $c = Irssi::settings_get_str("twirssi_nick_color");
1216         $c = $irssi_to_mirc_colors{$c};
1217         $text =~ s/(^|\W)\@([-\w]+)/$1\cC$c\@$2\cO/g if $c;
1218     }
1219     if ( Irssi::settings_get_str("twirssi_topic_color") ) {
1220         my $c = Irssi::settings_get_str("twirssi_topic_color");
1221         $c = $irssi_to_mirc_colors{$c};
1222         $text =~ s/(^|\W)\#([-\w]+)/$1\cC$c\#$2\cO/g if $c;
1223     }
1224     $text =~ s/[\n\r]/ /g;
1225
1226     return $text;
1227 }
1228
1229 sub shorten {
1230     my $data = shift;
1231
1232     my $provider = Irssi::settings_get_str("short_url_provider");
1233     if (
1234         (
1235             Irssi::settings_get_bool("twirssi_always_shorten")
1236             or &too_long( $data, 1 )
1237         )
1238         and $provider
1239       )
1240     {
1241         my @args;
1242         if ( $provider eq 'Bitly' ) {
1243             @args[ 1, 2 ] = split ',',
1244               Irssi::settings_get_str("short_url_args"), 2;
1245             unless ( @args == 3 ) {
1246                 &ccrap(
1247                     "WWW::Shorten::Bitly requires a username and API key.",
1248                     "Set short_url_args to username,API_key or change your",
1249                     "short_url_provider."
1250                 );
1251                 return $data;
1252             }
1253         }
1254
1255         foreach my $url ( $data =~ /(https?:\/\/\S+[\w\/])/g ) {
1256             eval {
1257                 $args[0] = $url;
1258                 my $short = makeashorterlink(@args);
1259                 if ($short) {
1260                     $data =~ s/\Q$url/$short/g;
1261                 } else {
1262                     &notice("Failed to shorten $url!");
1263                 }
1264             };
1265         }
1266     }
1267
1268     return $data;
1269 }
1270
1271 sub normalize_username {
1272     my $user = shift;
1273
1274     my ( $username, $service ) = split /\@/, $user, 2;
1275     if ($service) {
1276         $service = ucfirst lc $service;
1277     } else {
1278         $service =
1279           ucfirst lc Irssi::settings_get_str("twirssi_default_service");
1280         unless ( exists $twits{"$username\@$service"} ) {
1281             $service = undef;
1282             foreach my $t ( sort keys %twits ) {
1283                 next unless $t =~ /^\Q$username\E\@(Twitter|Identica)/;
1284                 $service = $1;
1285                 last;
1286             }
1287
1288             unless ($service) {
1289                 &notice("Can't find a logged in user '$user'");
1290             }
1291         }
1292     }
1293
1294     return "$username\@$service";
1295 }
1296
1297 Irssi::signal_add( "send text", "event_send_text" );
1298
1299 Irssi::theme_register(
1300     [
1301         'twirssi_tweet',  '[$0%B@$1%n$2] $3',
1302         'twirssi_search', '[$0%r$1%n:%B@$2%n$3] $4',
1303         'twirssi_reply',  '[$0\--> %B@$1%n$2] $3',
1304         'twirssi_dm',     '[$0%r@$1%n (%WDM%n)] $2',
1305         'twirssi_error',  'ERROR: $0',
1306     ]
1307 );
1308
1309 Irssi::settings_add_int( "twirssi", "twitter_poll_interval", 300 );
1310 Irssi::settings_add_str( "twirssi", "twitter_window",          "twitter" );
1311 Irssi::settings_add_str( "twirssi", "bitlbee_server",          "bitlbee" );
1312 Irssi::settings_add_str( "twirssi", "short_url_provider",      "TinyURL" );
1313 Irssi::settings_add_str( "twirssi", "short_url_args",          undef );
1314 Irssi::settings_add_str( "twirssi", "twitter_usernames",       undef );
1315 Irssi::settings_add_str( "twirssi", "twitter_passwords",       undef );
1316 Irssi::settings_add_str( "twirssi", "twirssi_default_service", "Twitter" );
1317 Irssi::settings_add_str( "twirssi", "twirssi_nick_color",      "%B" );
1318 Irssi::settings_add_str( "twirssi", "twirssi_topic_color",     "%r" );
1319 Irssi::settings_add_str( "twirssi", "twirssi_location",
1320     ".irssi/scripts/twirssi.pl" );
1321 Irssi::settings_add_str( "twirssi", "twirssi_replies_store",
1322     ".irssi/scripts/twirssi.json" );
1323 Irssi::settings_add_bool( "twirssi", "twirssi_upgrade_beta",      0 );
1324 Irssi::settings_add_bool( "twirssi", "tweet_to_away",             0 );
1325 Irssi::settings_add_bool( "twirssi", "show_reply_context",        0 );
1326 Irssi::settings_add_bool( "twirssi", "show_own_tweets",           1 );
1327 Irssi::settings_add_bool( "twirssi", "twirssi_debug",             0 );
1328 Irssi::settings_add_bool( "twirssi", "twirssi_first_run",         1 );
1329 Irssi::settings_add_bool( "twirssi", "twirssi_track_replies",     1 );
1330 Irssi::settings_add_bool( "twirssi", "twirssi_replies_autonick",  1 );
1331 Irssi::settings_add_bool( "twirssi", "twirssi_use_reply_aliases", 0 );
1332 Irssi::settings_add_bool( "twirssi", "twirssi_notify_timeouts",   1 );
1333 Irssi::settings_add_bool( "twirssi", "twirssi_hilights",          1 );
1334 Irssi::settings_add_bool( "twirssi", "twirssi_always_shorten",    0 );
1335 Irssi::settings_add_bool( "twirssi", "tweet_window_input",        0 );
1336
1337 $last_poll = time - &get_poll_time;
1338 $window = Irssi::window_find_name( Irssi::settings_get_str('twitter_window') );
1339 if ( !$window ) {
1340     Irssi::active_win()
1341       ->print( "Couldn't find a window named '"
1342           . Irssi::settings_get_str('twitter_window')
1343           . "', trying to create it." );
1344     $window =
1345       Irssi::Windowitem::window_create(
1346         Irssi::settings_get_str('twitter_window'), 1 );
1347     $window->set_name( Irssi::settings_get_str('twitter_window') );
1348 }
1349
1350 if ($window) {
1351     Irssi::command_bind( "dm",                         "cmd_direct" );
1352     Irssi::command_bind( "dm_as",                      "cmd_direct_as" );
1353     Irssi::command_bind( "tweet",                      "cmd_tweet" );
1354     Irssi::command_bind( "tweet_as",                   "cmd_tweet_as" );
1355     Irssi::command_bind( "twitter_reply",              "cmd_reply" );
1356     Irssi::command_bind( "twitter_reply_as",           "cmd_reply_as" );
1357     Irssi::command_bind( "twitter_login",              "cmd_login" );
1358     Irssi::command_bind( "twitter_logout",             "cmd_logout" );
1359     Irssi::command_bind( "twitter_switch",             "cmd_switch" );
1360     Irssi::command_bind( "twitter_subscribe",          "cmd_add_search" );
1361     Irssi::command_bind( "twitter_unsubscribe",        "cmd_del_search" );
1362     Irssi::command_bind( "twitter_list_subscriptions", "cmd_list_search" );
1363     Irssi::command_bind( "twirssi_upgrade",            "cmd_upgrade" );
1364     Irssi::command_bind( "twitter_updates",            "get_updates" );
1365     if ( Irssi::settings_get_bool("twirssi_use_reply_aliases") ) {
1366         Irssi::command_bind( "reply",    "cmd_reply" );
1367         Irssi::command_bind( "reply_as", "cmd_reply_as" );
1368     }
1369     Irssi::command_bind(
1370         "twirssi_dump",
1371         sub {
1372             print "twits: ", join ", ",
1373               map { "u: $_->{username}\@" . ref($_) } values %twits;
1374             print "selected: $user\@$defservice";
1375             print "friends: ", join ", ", sort keys %friends;
1376             print "nicks: ",   join ", ", sort keys %nicks;
1377             print "searches: ", Dumper \%{ $id_map{__searches} };
1378             print "last poll: $last_poll";
1379             if ( open DUMP, ">/tmp/twirssi.cache.txt" ) {
1380                 print DUMP Dumper \%tweet_cache;
1381                 close DUMP;
1382                 print "cache written out to /tmp/twirssi.cache.txt";
1383             }
1384         }
1385     );
1386     Irssi::command_bind(
1387         "twirssi_version",
1388         sub {
1389             &notice("Twirssi v$VERSION (r$REV); "
1390                   . "Net::Twitter v$Net::Twitter::VERSION. "
1391                   . "JSON in use: "
1392                   . JSON::Any::handler()
1393                   . ".  See details at http://twirssi.com/" );
1394         }
1395     );
1396     Irssi::command_bind(
1397         "twitter_friend",
1398         &gen_cmd(
1399             "/twitter_friend <username>",
1400             "create_friend",
1401             sub { &notice("Following $_[0]"); $nicks{ $_[0] } = time; }
1402         )
1403     );
1404     Irssi::command_bind(
1405         "twitter_unfriend",
1406         &gen_cmd(
1407             "/twitter_unfriend <username>",
1408             "destroy_friend",
1409             sub { &notice("Stopped following $_[0]"); delete $nicks{ $_[0] }; }
1410         )
1411     );
1412     Irssi::command_bind(
1413         "twitter_device_updates",
1414         &gen_cmd(
1415             "/twitter_device_updates none|im|sms",
1416             "update_delivery_device",
1417             sub { &notice("Device updated to $_[0]"); }
1418         )
1419     );
1420     Irssi::signal_add_last( 'complete word' => \&sig_complete );
1421
1422     &notice("  %Y<%C(%B^%C)%N                   TWIRSSI v%R$VERSION%N (r$REV)");
1423     &notice("   %C(_(\\%N           http://twirssi.com/ for full docs");
1424     &notice(
1425         "    %Y||%C `%N Log in with /twitter_login, send updates with /tweet");
1426
1427     my $file = Irssi::settings_get_str("twirssi_replies_store");
1428     if ( $file and -r $file ) {
1429         if ( open( JSON, $file ) ) {
1430             local $/;
1431             my $json = <JSON>;
1432             close JSON;
1433             eval {
1434                 my $ref = JSON::Any->jsonToObj($json);
1435                 %id_map = %$ref;
1436                 my $num = keys %{ $id_map{__indexes} };
1437                 &notice( sprintf "Loaded old replies from %d contact%s.",
1438                     $num, ( $num == 1 ? "" : "s" ) );
1439                 &cmd_list_search;
1440             };
1441         } else {
1442             &notice("Failed to load old replies from $file: $!");
1443         }
1444     }
1445
1446     if ( my $provider = Irssi::settings_get_str("short_url_provider") ) {
1447         &notice("Loading WWW::Shorten::$provider...");
1448         eval "use WWW::Shorten::$provider;";
1449
1450         if ($@) {
1451             &notice(
1452                 "Failed to load WWW::Shorten::$provider - either clear",
1453                 "short_url_provider or install the CPAN module"
1454             );
1455         }
1456     }
1457
1458     if (    my $autouser = Irssi::settings_get_str("twitter_usernames")
1459         and my $autopass = Irssi::settings_get_str("twitter_passwords") )
1460     {
1461         &cmd_login();
1462         &get_updates;
1463     }
1464
1465 } else {
1466     Irssi::active_win()
1467       ->print( "Create a window named "
1468           . Irssi::settings_get_str('twitter_window')
1469           . " or change the value of twitter_window.  Then, reload twirssi." );
1470 }
1471
1472 # vim: set sts=4 expandtab: