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