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