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