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