]> git.donarmstrong.com Git - infobot.git/blob - src/UserExtra.pl
allow join to join irrelevent of being on chan
[infobot.git] / src / UserExtra.pl
1 #
2 # UserExtra.pl: User Commands, Public.
3 #       Author: dms
4 #      Version: v0.2b (20000707)
5 #      Created: 20000107
6 #
7
8 if (&IsParam("useStrict")) { use strict; }
9
10 use vars qw($message $arg $qWord $verb $lobotomized);
11 use vars qw(%channels %chanstats %cmdstats);
12
13 ###
14 ### Start of command hooks for UserExtra.
15 ###
16
17 &addCmdHook("main", 'chan(stats|info)', ('CODEREF' => 'chaninfo', ) );
18 &addCmdHook("main", 'cmd(stats|info)', ('CODEREF' => 'cmdstats', ) );
19 &addCmdHook("main", 'factinfo', ('CODEREF' => 'factinfo', 
20         'Cmdstats' => 'Factoid Info', Module => 'factoids', ) );
21 &addCmdHook("main", 'factstats?', ('CODEREF' => 'factstats', 
22         'Cmdstats' => 'Factoid Statistics', Help => "factstats", 
23         Forker => 1, 'Identifier' => 'factoids', ) );
24 &addCmdHook("main", 'help', ('CODEREF' => 'help', 
25         'Cmdstats' => 'Help', ) );
26 &addCmdHook("main", 'karma', ('CODEREF' => 'karma', ) );
27 &addCmdHook("main", 'i?spell', ('CODEREF' => 'ispell', 
28         Help => 'spell', Identifier => 'spell', ) );
29 &addCmdHook("main", 'd?nslookup', ('CODEREF' => 'DNS', 
30         Help => 'nslookup', Identifier => 'allowDNS',
31         Forker => "NULL", ) );
32 &addCmdHook("main", 'tell|explain', ('CODEREF' => 'tell', 
33         Help => 'tell', Identifier => 'allowTelling',
34         Cmdstats => 'Tell') );
35 &addCmdHook("main", 'news', ('CODEREF' => 'News::Parse', 
36         Module => 'news', ) );
37 #       Module => 'news', Identifier => 'news') );
38
39 &status("CMD: loaded ".scalar(keys %hooks_main)." MAIN command hooks.");
40
41 ###
42 ### Start of commands for hooks.
43 ###
44
45 sub chaninfo {
46     my $chan = lc shift(@_);
47     my $mode;
48
49     if ($chan eq "") {          # all channels.
50         my $i           = keys %channels;
51         my $reply       = "i am on \002$i\002 ".&fixPlural("channel",$i);
52         my $tucount     = 0;    # total user count.
53         my $uucount     = 0;    # unique user count.
54         my @array;
55
56         ### line 1.
57         foreach (sort keys %channels) {
58             if (/^\s*$/ or / /) {
59                 &status("chanstats: fe channels: chan == NULL.");
60                 &ircCheck();
61                 next;
62             }
63             push(@array, "$_ (".scalar(keys %{ $channels{$_}{''} }).")");
64         }
65         &pSReply($reply.": ".join(' ', @array));
66
67         ### total user count.
68         foreach $chan (keys %channels) {
69             $tucount += scalar(keys %{ $channels{$chan}{''} });
70         }
71
72         ### unique user count.
73         my @nicks;
74         foreach $chan (keys %channels) {
75             foreach (keys %{ $channels{$chan}{''} }) {
76                 next if (grep /^\Q$_\E$/, @nicks);
77                 $uucount++;
78                 push(@nicks, $_);
79             }
80         }
81         &DEBUG("nicks => '".scalar(@nicks)."'...");
82         if (scalar @nicks != $uucount) {
83             &DEBUG("nicks != uucount...");
84         }
85
86         my $chans = scalar(keys %channels);
87         &pSReply(
88             "i've cached \002$tucount\002 ". &fixPlural("user",$tucount).
89             ", \002$uucount\002 unique ". &fixPlural("user",$uucount).
90             ", distributed over \002$chans\002 ".
91             &fixPlural("channel", $chans)."."
92         );
93
94         return;
95     }
96
97     # channel specific.
98
99     if (&validChan($chan) == 0) {
100         &msg($who,"error: invalid channel \002$chan\002");
101         return;
102     }
103
104     # Step 1:
105     my @array;
106     foreach (sort keys %{ $chanstats{$chan} }) {
107         my $int = $chanstats{$chan}{$_};
108         next unless ($int);
109
110         push(@array, "\002$int\002 ". &fixPlural($_,$int));
111     }
112     my $reply = "On \002$chan\002, there ".
113                 &fixPlural("has",scalar(@array)). " been ".
114                 &IJoin(@array);
115
116     # Step 1b: check channel inconstencies.
117     $chanstats{$chan}{'Join'}           ||= 0;
118     $chanstats{$chan}{'SignOff'}        ||= 0;
119     $chanstats{$chan}{'Part'}           ||= 0;
120
121     my $delta_stats = $chanstats{$chan}{'Join'}
122                 - $chanstats{$chan}{'SignOff'}
123                 - $chanstats{$chan}{'Part'};
124
125     if ($delta_stats) {
126         my $total = scalar(keys %{ $channels{$chan}{''} });
127         &status("chaninfo: join ~= signoff + part (drift of $delta_stats < $total).");
128
129         if ($delta_stats > $total) {
130             &ERROR("chaninfo: delta_stats exceeds total users.");
131         }
132     }
133
134     # Step 2:
135     undef @array;
136     my $type;
137     foreach ("v","o","") {
138         my $int = scalar(keys %{ $channels{$chan}{$_} });
139         next unless ($int);
140
141         $type = "Voice" if ($_ eq "v");
142         $type = "Opped" if ($_ eq "o");
143         $type = "Total" if ($_ eq "");
144
145         push(@array,"\002$int\002 $type");
146     }
147     $reply .= ".  At the moment, ". &IJoin(@array);
148
149     # Step 3:
150     my %new;
151     foreach (keys %userstats) {
152         next unless (exists $userstats{$_}{'Count'});
153         $new{$_} = $userstats{$_}{'Count'};
154     }
155
156     my($count) = (sort { $b <=> $a } keys %new)[0];
157     if ($count) {
158         $reply .= ".  \002$new{$count}\002 has said the most with a total of \002$count\002 messages";
159     }
160     &pSReply("$reply.");
161 }
162
163 # Command statistics.
164 sub cmdstats {
165     my @array;
166
167     if (!scalar(keys %cmdstats)) {
168         &performReply("no-one has run any commands yet");
169         return;
170     }
171
172     my %countstats;
173     foreach (keys %cmdstats) {
174         $countstats{ $cmdstats{$_} }{$_} = 1;
175     }
176
177     foreach (sort {$b <=> $a} keys %countstats) {
178         my $int = $_;
179         next unless ($int);
180
181         foreach (keys %{ $countstats{$int} }) {
182             push(@array, "\002$int\002 of $_");
183         }
184     }
185     &pSReply("command usage include ". &IJoin(@array).".");
186 }
187
188 # Factoid extension info. xk++
189 sub factinfo {
190     my $faqtoid = lc shift(@_);
191     my $query   = "";
192
193     if ($faqtoid =~ /^\-(\S+)(\s+(.*))$/) {
194         &msg($who,"error: individual factoid info queries not supported as yet.");
195         &msg($who,"it's possible that the factoid mistakenly begins with '-'.");
196         return;
197
198         $query   = lc $1;
199         $faqtoid = lc $3;
200     }
201
202     &CmdFactInfo($faqtoid, $query);
203 }
204
205 sub factstats {
206     my $type = shift(@_);
207
208     &Forker("factoids", sub {
209         &pSReply( &CmdFactStats($type) );
210     } );
211 }
212
213 sub karma {
214     my $target  = lc( shift || $who );
215     my $karma   = &dbGet("karma", "nick",$target,"karma") || 0;
216
217     if ($karma != 0) {
218         &pSReply("$target has karma of $karma");
219     } else {
220         &pSReply("$target has neutral karma");
221     }
222 }
223
224 sub ispell {
225     my $query = shift;
226
227     if (! -x "/usr/bin/spell") {
228         &msg($who, "no binary found.");
229         return;
230     }
231
232     if (!&validExec($query)) {
233         &msg($who,"argument appears to be fuzzy.");
234         return;
235     }
236
237     my $reply = "I can't find alternate spellings for '$query'";
238
239     foreach (`/bin/echo '$query' | /usr/bin/ispell -a -S`) {
240         chop;
241         last if !length;                # end of query.
242
243         if (/^\@/) {            # intro line.
244             next;
245         } elsif (/^\*/) {               # possibly correct.
246             $reply = "'$query' may be spelled correctly";
247             last;
248         } elsif (/^\&/) {               # possible correction(s).
249             s/^\& (\S+) \d+ \d+: //;
250             my @array = split(/,? /);
251
252             $reply = "possible spellings for $query: @array";
253             last;
254         } elsif (/^\+/) {
255             &DEBUG("spell: '+' found => '$_'.");
256             last;
257         } else {
258             &DEBUG("spell: unknown: '$_'.");
259         }
260     }
261
262     &pSReply($reply);
263 }
264
265 sub nslookup {
266     my $query = shift;
267     &status("DNS Lookup: $query");
268     &DNS($query);
269 }
270
271 sub tell {
272     my $args = shift;
273     my ($target, $tell_obj) = ('','');
274     my $dont_tell_me    = 0;
275     my $reply;
276
277     ### is this fixed elsewhere?
278     $args =~ s/\s+/ /g;         # fix up spaces.
279     $args =~ s/^\s+|\s+$//g;    # again.
280
281     # this one catches most of them
282     if ($args =~ /^(\S+) (-?)about (.*)$/i) {
283         $target         = lc $1;
284         $tell_obj       = $3;
285         $dont_tell_me   = ($2) ? 1 : 0;
286
287         $tell_obj       = $who  if ($tell_obj =~ /^(me|myself)$/i);
288         $query          = $tell_obj;
289     } elsif ($args =~ /^(\S+) where (\S+) can (\S+) (.*)$/i) {
290         # i'm sure this could all be nicely collapsed
291         $target         = lc $1;
292         $tell_obj       = $4;
293         $query          = $tell_obj;
294
295     } elsif ($args =~ /^(\S+) (what|where) (.*?) (is|are)[.?!]*$/i) {
296         $target         = lc $1;
297         $qWord          = $2;
298         $tell_obj       = $3;
299         $verb           = $4;
300         $query          = "$qWord $verb $tell_obj";
301
302     } elsif ($args =~ /^(.*?) to (\S+)$/i) {
303         $target         = lc $3;
304         $tell_obj       = $2;
305         $query          = $tell_obj;
306     }
307
308     # check target type. Deny channel targets.
309     if ($target !~ /^$mask{nick}$/ or $target =~ /^$mask{chan}$/) {
310         &msg($who,"No, $who, I won't. (target invalid?)");
311         return;
312     }
313
314     $target     = $talkchannel  if ($target =~ /^us$/i);
315     $target     = $who          if ($target =~ /^(me|myself)$/i);
316
317     &status("tell: target = $target, query = $query");  
318
319     # "intrusive".
320     if ($target !~ /^$mask{chan}$/ and !&IsNickInAnyChan($target)) {
321         &msg($who, "No, $target is not in any of my chans.");
322         return;
323     }
324
325     ### TODO: don't "tell" if sender is not in target's channel.
326
327     # self.
328     if ($target eq $ident) {    # lc?
329         &msg($who, "Isn't that a bit silly?");
330         return;
331     }
332
333     my $oldwho          = $who;
334     my $oldmtype        = $msgType;
335     $who                = $target;
336     my $result = &doQuestion($tell_obj);
337         # ^ returns '0' if nothing was found.
338     $who                = $oldwho;
339
340     # no such factoid.
341     if ($result =~ /^0?$/) {
342         $who            = $target;
343         $msgType        = "private";
344
345         # support command redirection.
346         # recursive cmdHooks aswell :)
347         my $done = 0;
348         $done++ if &parseCmdHook("main", $tell_obj);
349         $done++ if &parseCmdHook("extra", $tell_obj);
350         $message        = $tell_obj;
351         $done++ unless (&Modules());
352
353         &DEBUG("setting old values of who and msgType.");
354         $who            = $oldwho;
355         $msgType        = $oldmtype;
356
357         if ($done) {
358             &msg($who, "told $target about CMD '$tell_obj'");
359         } else {
360             &msg($who, "i dunno what is '$tell_obj'.");
361         }
362
363         return;
364     }
365
366     # success.
367     &status("tell: <$who> telling $target about $tell_obj.");
368     if ($who ne $target) {
369         if ($dont_tell_me) {
370             &msg($who, "told $target about $tell_obj.");
371         } else {
372             &msg($who, "told $target about $tell_obj ($result)");
373         }
374
375         $reply = "$who wants you to know: $result";
376     } else {
377         $reply = "telling yourself: $result";
378     }
379
380     &msg($target, $reply);
381 }
382
383 sub DNS {
384     my $dns = shift;
385     my($match, $x, $y, $result);
386     my $pid;
387
388     if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
389         &status("DNS query by IP address: $in");
390         $match = $1;
391         $y = pack('C4', split(/\./, $match));
392         $x = (gethostbyaddr($y, &AF_INET));
393
394         if ($x !~ /^\s*$/) {
395             $result = $match." is ".$x unless ($x =~ /^\s*$/);
396         } else {
397             $result = "I can't seem to find that address in DNS";
398         }
399     } else {
400         &status("DNS query by name: $in");
401         $x = join('.',unpack('C4',(gethostbyname($in))[4]));
402
403         if ($x !~ /^\s*$/) {
404             $result = $in." is ".$x;
405         } else {
406             $result = "I can\'t find that machine name";
407         }
408     }
409
410     &performReply($result);
411 }
412
413
414 ###
415 ### amalgamated commands.
416 ###
417
418 sub userCommands {
419     # conversion: ascii.
420     if ($message =~ /^(asci*|chr) (\d+)$/) {
421         return unless (&IsParam("allowConv"));
422
423         $arg    = $2;
424         $result = chr($arg);
425         $result = "NULL"        if ($arg == 0);
426
427         &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
428
429         return;
430     }
431
432     # conversion: ord.
433     if ($message =~ /^ord (.)$/) {
434         return unless (&IsParam("allowConv"));
435
436         $arg = $1;
437         if (ord($arg) < 32) {
438             $arg = chr(ord($arg) + 64);
439             if ($arg eq chr(64)) {
440                 $arg = 'NULL';
441             } else {
442                 $arg = '^'.$arg;
443             }
444         }
445
446         &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
447         return;
448     }
449
450     # hex.
451     if ($message =~ /^hex(\s+(.*))?$/i) {
452         return unless (&IsParam("allowConv"));
453         my $arg = $2;
454
455         if (!defined $arg) {
456             &help("hex");
457             return;
458         }
459
460         if (length $arg > 80) {
461             &msg($who, "Too long.");
462             return;
463         }
464
465         my $retval;
466         foreach (split //, $arg) {
467             $retval .= sprintf(" %X", ord($_));
468         }
469
470         &pSReply("$arg is$retval");
471
472         return;
473     }
474
475     # crypt.
476     if ($message =~ /^crypt(\s+(.*))?$/i) {
477         my @args        = split /\s+/, $2;
478
479         if (!scalar @args or scalar @args > 2) {
480             &help("crypt");
481             return;
482         }
483
484         if (scalar @args == 2) {
485             if (length $args[0] != 2) {
486                 &msg($who, "invalid format...");
487                 return;
488             }
489
490             &pSReply( crypt($args[1], $args[0]) );
491         } else {
492             &pSReply( &mkcrypt($args[0]) );
493         }
494
495         return;
496     }
497
498     # cycle.
499     if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
500         return unless (&hasFlag("o"));
501         my $chan = lc $3;
502
503         if ($chan eq "") {
504             if ($msgType =~ /public/) {
505                 $chan = $talkchannel;
506                 &DEBUG("cycle: setting chan to '$chan'.");
507             } else {
508                 &help("cycle");
509                 return;
510             }
511         }
512
513         if (&validChan($chan) == 0) {
514             &msg($who,"error: invalid channel \002$chan\002");
515             return;
516         }
517
518         &msg($chan, "I'm coming back. (courtesy of $who)");
519         &part($chan);
520 ###     &ScheduleThis(5, "getNickInUse") if (@_);
521         &status("Schedule rejoin in 5secs to $chan by $who.");
522         $conn->schedule(5, sub { &joinchan($chan); });
523
524         return;
525     }
526
527     # redir.
528     if ($message =~ /^redir(\s+(.*))?/i) {
529         return unless (&hasFlag("o"));
530         my $factoid = $2;
531
532         if (!defined $factoid) {
533             &help("redir");
534             return;
535         }
536
537         my $val  = &getFactInfo($factoid, "factoid_value");
538         if (!defined $val or $val eq "") {
539             &msg($who, "error: '$factoid' does not exist.");
540             return;
541         }
542         &DEBUG("val => '$val'.");
543         my @list = &searchTable("factoids", "factoid_key",
544                                         "factoid_value", "^$val\$");
545
546         if (scalar @list == 1) {
547             &msg($who, "hrm... '$factoid' is unique.");
548             return;
549         }
550         if (scalar @list > 5) {
551             &msg($who, "A bit too many factoids to be redirected, hey?");
552             return;
553         }
554
555         my @redir;
556         &status("Redirect '$factoid' (". ($#list) .")...");
557         for (@list) {
558             my $x = $_;
559             next if (/^\Q$factoid\E$/i);
560
561             &status("  Redirecting '$_'.");
562             my $was = &getFactoid($_);
563             if ($was =~ /<REPLY> see/i) {
564                 &status("warn: not redirecting a redirection.");
565                 next;
566             }
567
568             &DEBUG("  was '$was'.");
569             push(@redir,$x);
570             &setFactInfo($x, "factoid_value", "<REPLY> see $factoid");
571         }
572         &status("Done.");
573
574         &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
575
576         return;
577     }
578
579     # rot13 it.
580     if ($message =~ /^rot13(\s+(.*))?/i) {
581         my $reply = $2;
582
583         if (!defined $reply) {
584             &help("rot13");
585             return;
586         }
587
588         $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
589         &pSReply($reply);
590
591         return;
592     }
593
594     # cpustats.
595     if ($message =~ /^cpustats$/i) {
596         if ($^O !~ /linux/) {
597             &ERROR("cpustats: your OS is not supported yet.");
598             return;
599         }
600
601         ### poor method to get info out of file, please fix.
602         open(STAT,"/proc/$$/stat");
603         my $line = <STAT>;
604         chop $line;
605         my @data = split(/ /, $line);
606         close STAT;
607
608         # utime(13) + stime(14).
609         my $cpu_usage   = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
610         my $time        = time() - $^T;
611         my $raw_perc    = $cpu_usage*100/$time;
612         my $perc;
613
614         if ($raw_perc > 1) {
615             $perc       = sprintf("%.01f", $raw_perc);
616         } elsif ($raw_perc > 0.1) {
617             $perc       = sprintf("%.02f", $raw_perc);
618         } else {                        # <=0.1
619             $perc       = sprintf("%.03f", $raw_perc);
620         }
621
622         &pSReply("Total CPU usage: $cpu_usage s ... Percentage CPU used: $perc %");
623         &DEBUG("15 => $data[15] (cutime)");
624         &DEBUG("16 => $data[16] (cstime)");
625
626         return;
627     }
628
629     # ircstats.
630     if ($message =~ /^ircstats?$/i) {
631         $ircstats{'TotalTime'}  ||= 0;
632         $ircstats{'OffTime'}    ||= 0;
633
634         my $count       = $ircstats{'ConnectCount'};
635         my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
636         my $total_time  = time() - $ircstats{'ConnectTime'} +
637                                 $ircstats{'TotalTime'};
638         my $reply;
639
640         my $connectivity = 100 * ($total_time - $ircstats{'OffTime'}) /
641                                 $total_time;
642         my $p = sprintf("%.03f", $connectivity);
643         $p =~ s/(\.\d*)0+$/$1/;
644         if ($p =~ s/\.0$//) {
645             # this should not happen... but why...
646         } else {
647             $p =~ s/\.$//
648         }
649
650         if ($total_time != (time() - $ircstats{'ConnectTime'}) ) {
651             my $tt_format = &Time2String($total_time);
652             &DEBUG("tt_format => $tt_format");
653         }
654
655         ### RECONNECT COUNT.
656         if ($count == 1) {      # good.
657             $reply = "I'm connected to $ircstats{'Server'} and have been so".
658                 " for $format_time";
659         } else {
660             $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
661                 " for $format_time.  ".
662                 "I had to reconnect \002$count\002 times.".
663                 "   Connectivity: $p %";
664         }
665
666         ### REASON.
667         my $reason = $ircstats{'DisconnectReason'};
668         if (defined $reason) {
669             $reply .= ".  I was last disconnected for '$reason'.";
670         }
671
672         &pSReply($reply);
673                 
674         return;
675     }
676
677     # status.
678     if ($message =~ /^statu?s$/i) {
679         my $startString = scalar(localtime $^T);
680         my $upString    = &Time2String(time() - $^T);
681         my $count       = &countKeys("factoids");
682
683         &pSReply(
684         "Since $startString, there have been".
685           " \002$count{'Update'}\002 ".
686                 &fixPlural("modification", $count{'Update'}).
687           " and \002$count{'Question'}\002 ".
688                 &fixPlural("question",$count{'Question'}).
689           " and \002$count{'Dunno'}\002 ".
690                 &fixPlural("dunno",$count{'Dunno'}).
691           " and \002$count{'Moron'}\002 ".
692                 &fixPlural("moron",$count{'Moron'}).
693           ".  I have been awake for $upString this session, and ".
694           "currently reference \002$count\002 factoids.  ".
695           "I'm using about \002$memusage\002 ".
696           "kB of memory."
697         );
698
699         return;
700     }
701
702     # wantNick. xk++
703     if ($message =~ /^wantNick$/i) {
704         if ($param{'ircNick'} eq $ident) {
705             &msg($who, "I hope you're right. I'll try anyway.");
706         }
707
708         if (! &IsNickInAnyChan( $param{ircNick} ) ) {
709             my $str = "attempting to change nick to $param{'ircNick'}";
710             &status($str);
711             &msg($who, $str);
712             &nick($param{'ircNick'});
713         } else {
714             &msg($who, "hrm... can't do it");
715             &DEBUG("wN: nick is somewhere... should try later.");
716         }
717
718         return;
719     }
720
721     return "CONTINUE";
722 }
723
724 1;