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