]> git.donarmstrong.com Git - infobot.git/blob - src/UserExtra.pl
added support for old Modules() for telling.
[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         $message        = $tell_obj;
330         $done++ unless (&Modules());
331
332         &DEBUG("setting old values of who and msgType.");
333         $who            = $oldwho;
334         $msgType        = $oldmtype;
335
336         if ($done) {
337             &msg($who, "told $target about CMD '$tell_obj'");
338         } else {
339             &msg($who, "i dunno what is '$tell_obj'.");
340         }
341
342         return;
343     }
344
345     # success.
346     &status("tell: <$who> telling $target about $tell_obj.");
347     if ($who ne $target) {
348         if ($dont_tell_me) {
349             &msg($who, "told $target about $tell_obj.");
350         } else {
351             &msg($who, "told $target about $tell_obj ($result)");
352         }
353
354         $reply = "$who wants you to know: $result";
355     } else {
356         $reply = "telling yourself: $result";
357     }
358
359     &msg($target, $reply);
360 }
361
362 sub DNS {
363     my $dns = shift;
364     my($match, $x, $y, $result);
365     my $pid;
366
367     if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
368         &status("DNS query by IP address: $in");
369         $match = $1;
370         $y = pack('C4', split(/\./, $match));
371         $x = (gethostbyaddr($y, &AF_INET));
372
373         if ($x !~ /^\s*$/) {
374             $result = $match." is ".$x unless ($x =~ /^\s*$/);
375         } else {
376             $result = "I can't seem to find that address in DNS";
377         }
378     } else {
379         &status("DNS query by name: $in");
380         $x = join('.',unpack('C4',(gethostbyname($in))[4]));
381
382         if ($x !~ /^\s*$/) {
383             $result = $in." is ".$x;
384         } else {
385             $result = "I can\'t find that machine name";
386         }
387     }
388
389     &performReply($result);
390 }
391
392
393 ###
394 ### amalgamated commands.
395 ###
396
397 sub userCommands {
398     # conversion: ascii.
399     if ($message =~ /^(asci*|chr) (\d+)$/) {
400         return '' unless (&IsParam("allowConv"));
401
402         $arg = $2;
403         if ($arg < 32) {
404             $arg += 64;
405             $result = "^".chr($arg);
406         } else {
407             $result = chr($2);
408         }
409         $result = "NULL"        if ($arg == 0);
410
411         &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
412         return;
413     }
414
415     # conversion: ord.
416     if ($message =~ /^ord (.)$/) {
417         return '' unless (&IsParam("allowConv"));
418
419         $arg = $1;
420         if (ord($arg) < 32) {
421             $arg = chr(ord($arg) + 64);
422             if ($arg eq chr(64)) {
423                 $arg = 'NULL';
424             } else {
425                 $arg = '^'.$arg;
426             }
427         }
428
429         &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
430         return;
431     }
432
433     # hex.
434     if ($message =~ /^hex(\s+(.*))?$/i) {
435         my $arg = $2;
436
437         if (!defined $arg) {
438             &help("hex");
439             return;
440         }
441
442         if (length $arg > 80) {
443             &msg($who, "Too long.");
444             return;
445         }
446
447         my $retval;
448         foreach (split //, $arg) {
449             $retval .= sprintf(" %X", ord($_));
450         }
451
452         &pSReply("$arg is$retval");
453
454         return;
455     }
456
457     # crypt.
458     if ($message =~ /^crypt\s+(\S+)\s*(?:,| )\s*(\S+)/) {
459         # word salt.
460         &pSReply(crypt($1, $2));
461         return;
462     }
463
464
465
466     # cycle.
467     if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
468         return unless (&hasFlag("o"));
469         my $chan = lc $3;
470
471         if ($chan eq "") {
472             if ($msgType =~ /public/) {
473                 $chan = $talkchannel;
474                 &DEBUG("cycle: setting chan to '$chan'.");
475             } else {
476                 &help("cycle");
477                 return;
478             }
479         }
480
481         if (&validChan($chan) == 0) {
482             &msg($who,"error: invalid channel \002$chan\002");
483             return;
484         }
485
486         &msg($chan, "I'm coming back. (courtesy of $who)");
487         &part($chan);
488 ###     &ScheduleThis(5, "getNickInUse") if (@_);
489         &status("Schedule rejoin in 5secs to $chan by $who.");
490         $conn->schedule(5, sub { &joinchan($chan); });
491
492         return;
493     }
494
495     # redir.
496     if ($message =~ /^redir(\s+(.*))?/i) {
497         return unless (&hasFlag("o"));
498         my $factoid = $2;
499
500         if (!defined $factoid) {
501             &help("redir");
502             return;
503         }
504
505         my $val  = &getFactInfo($factoid, "factoid_value");
506         if (!defined $val or $val eq "") {
507             &msg($who, "error: '$factoid' does not exist.");
508             return;
509         }
510         &DEBUG("val => '$val'.");
511         my @list = &searchTable("factoids", "factoid_key",
512                                         "factoid_value", "^$val\$");
513
514         if (scalar @list == 1) {
515             &msg($who, "hrm... '$factoid' is unique.");
516             return;
517         }
518         if (scalar @list > 5) {
519             &msg($who, "A bit too many factoids to be redirected, hey?");
520             return;
521         }
522
523         my @redir;
524         &status("Redirect '$factoid' (". ($#list) .")...");
525         for (@list) {
526             next if (/^\Q$factoid\E$/i);
527
528             &status("  Redirecting '$_'.");
529             my $was = &getFactoid($_);
530             &DEBUG("  was '$was'.");
531             push(@redir,$_);
532             &setFactInfo($_, "factoid_value", "<REPLY> see $factoid");
533         }
534         &status("Done.");
535
536         &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
537
538         return;
539     }
540
541     # rot13 it.
542     if ($message =~ /^rot13(\s+(.*))?/i) {
543         my $reply = $2;
544
545         if (!defined $reply) {
546             &help("rot13");
547             return;
548         }
549
550         $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
551         &pSReply($reply);
552
553         return;
554     }
555
556     # cpustats.
557     if ($message =~ /^cpustats$/i) {
558         if ($^O !~ /linux/) {
559             &ERROR("cpustats: your OS is not supported yet.");
560             return;
561         }
562
563         ### poor method to get info out of file, please fix.
564         open(STAT,"/proc/$$/stat");
565         my $line = <STAT>;
566         chop $line;
567         my @data = split(/ /, $line);
568         close STAT;
569
570         # utime(13) + stime(14).
571         my $cpu_usage   = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
572         my $time        = time() - $^T;
573         my $raw_perc    = $cpu_usage*100/$time;
574         my $perc;
575
576         if ($raw_perc > 1) {
577             $perc       = sprintf("%.01f", $raw_perc);
578         } elsif ($raw_perc > 0.1) {
579             $perc       = sprintf("%.02f", $raw_perc);
580         } else {                        # <=0.1
581             $perc       = sprintf("%.03f", $raw_perc);
582         }
583
584         &pSReply("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;
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         &pSReply($reply);
618                 
619         return;
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         &pSReply(
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;
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;
659     }
660
661     return "CONTINUE";
662 }
663
664 1;