]> git.donarmstrong.com Git - infobot.git/blob - blootbot/src/UserExtra.pl
- if - is used before -about, don't tell us about what was told.
[infobot.git] / blootbot / 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("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     &DEBUG("result => $result.");
316 #    return if ($result eq);
317
318     # no such factoid.
319     if ($result eq "") {
320         &msg($who, "i dunno what is '$tell_obj'.");
321         return;
322     }
323
324     # success.
325     &status("tell: <$who> telling $target about $tell_obj.");
326     if ($who ne $target) {
327         &msg($who, "told $target about $tell_obj ($result)")
328                                                 unless ($dont_tell_me);
329         $reply = "$who wants you to know: $result";
330     } else {
331         $reply = "telling yourself: $result";
332     }
333
334     &msg($target, $reply);
335 }
336
337 sub DNS {
338     my $dns = shift;
339     my($match, $x, $y, $result);
340     my $pid;
341
342     if ($dns =~ /(\d+\.\d+\.\d+\.\d+)/) {
343         &status("DNS query by IP address: $in");
344         $match = $1;
345         $y = pack('C4', split(/\./, $match));
346         $x = (gethostbyaddr($y, &AF_INET));
347
348         if ($x !~ /^\s*$/) {
349             $result = $match." is ".$x unless ($x =~ /^\s*$/);
350         } else {
351             $result = "I can't seem to find that address in DNS";
352         }
353     } else {
354         &status("DNS query by name: $in");
355         $x = join('.',unpack('C4',(gethostbyname($in))[4]));
356
357         if ($x !~ /^\s*$/) {
358             $result = $in." is ".$x;
359         } else {
360             $result = "I can\'t find that machine name";
361         }
362     }
363
364     &performReply($result);
365 }
366
367
368 ###
369 ### amalgamated commands.
370 ###
371
372 sub userCommands {
373     # conversion: ascii.
374     if ($message =~ /^(asci*|chr) (\d+)$/) {
375         return '' unless (&IsParam("allowConv"));
376
377         $arg = $2;
378         if ($arg < 32) {
379             $arg += 64;
380             $result = "^".chr($arg);
381         } else {
382             $result = chr($2);
383         }
384         $result = "NULL"        if ($arg == 0);
385
386         &performReply( sprintf("ascii %s is '%s'", $arg, $result) );
387         return;
388     }
389
390     # conversion: ord.
391     if ($message =~ /^ord (.)$/) {
392         return '' unless (&IsParam("allowConv"));
393
394         $arg = $1;
395         if (ord($arg) < 32) {
396             $arg = chr(ord($arg) + 64);
397             if ($arg eq chr(64)) {
398                 $arg = 'NULL';
399             } else {
400                 $arg = '^'.$arg;
401             }
402         }
403
404         &performReply( sprintf("'%s' is ascii %s", $arg, ord $1) );
405         return;
406     }
407
408     # hex.
409     if ($message =~ /^hex(\s+(.*))?$/i) {
410         my $arg = $2;
411
412         if (!defined $arg) {
413             &help("hex");
414             return;
415         }
416
417         if (length $arg > 80) {
418             &msg($who, "Too long.");
419             return;
420         }
421
422         my $retval;
423         foreach (split //, $arg) {
424             $retval .= sprintf(" %X", ord($_));
425         }
426
427         &pSReply("$arg is$retval");
428
429         return;
430     }
431
432     # crypt.
433     if ($message =~ /^crypt\s+(\S+)\s*(?:,| )\s*(\S+)/) {
434         # word salt.
435         &pSReply(crypt($1, $2));
436         return;
437     }
438
439
440
441     # cycle.
442     if ($message =~ /^(cycle)(\s+(\S+))?$/i) {
443         return unless (&hasFlag("o"));
444         my $chan = lc $3;
445
446         if ($chan eq "") {
447             if ($msgType =~ /public/) {
448                 $chan = $talkchannel;
449                 &DEBUG("cycle: setting chan to '$chan'.");
450             } else {
451                 &help("cycle");
452                 return;
453             }
454         }
455
456         if (&validChan($chan) == 0) {
457             &msg($who,"error: invalid channel \002$chan\002");
458             return;
459         }
460
461         &msg($chan, "I'm coming back. (courtesy of $who)");
462         &part($chan);
463 ###     &ScheduleThis(5, "getNickInUse") if (@_);
464         &status("Schedule rejoin in 5secs to $chan by $who.");
465         $conn->schedule(5, sub { &joinchan($chan); });
466
467         return;
468     }
469
470     # redir.
471     if ($message =~ /^redir(\s+(.*))?/i) {
472         return unless (&hasFlag("o"));
473         my $factoid = $2;
474
475         if (!defined $factoid) {
476             &help("redir");
477             return;
478         }
479
480         my $val  = &getFactInfo($factoid, "factoid_value");
481         if (!defined $val or $val eq "") {
482             &msg($who, "error: '$factoid' does not exist.");
483             return;
484         }
485         &DEBUG("val => '$val'.");
486         my @list = &searchTable("factoids", "factoid_key",
487                                         "factoid_value", "^$val\$");
488
489         if (scalar @list == 1) {
490             &msg($who, "hrm... '$factoid' is unique.");
491             return;
492         }
493         if (scalar @list > 5) {
494             &msg($who, "A bit too many factoids to be redirected, hey?");
495             return;
496         }
497
498         my @redir;
499         &status("Redirect '$factoid' (". ($#list) .")...");
500         for (@list) {
501             next if (/^\Q$factoid\E$/i);
502
503             &status("  Redirecting '$_'.");
504             my $was = &getFactoid($_);
505             &DEBUG("  was '$was'.");
506             push(@redir,$_);
507             &setFactInfo($_, "factoid_value", "<REPLY> see $factoid");
508         }
509         &status("Done.");
510
511         &msg($who, &formListReply(0, "'$factoid' is redirected to by '", @redir));
512
513         return;
514     }
515
516     # rot13 it.
517     if ($message =~ /^rot13(\s+(.*))?/i) {
518         my $reply = $2;
519
520         if (!defined $reply) {
521             &help("rot13");
522             return;
523         }
524
525         $reply =~ y/A-Za-z/N-ZA-Mn-za-m/;
526         &pSReply($reply);
527
528         return;
529     }
530
531     # cpustats.
532     if ($message =~ /^cpustats$/i) {
533         if ($^O !~ /linux/) {
534             &ERROR("cpustats: your OS is not supported yet.");
535             return;
536         }
537
538         ### poor method to get info out of file, please fix.
539         open(STAT,"/proc/$$/stat");
540         my $line = <STAT>;
541         chop $line;
542         my @data = split(/ /, $line);
543         close STAT;
544
545         # utime(13) + stime(14).
546         my $cpu_usage   = sprintf("%.01f", ($data[13]+$data[14]) / 100 );
547         my $time        = time() - $^T;
548         my $raw_perc    = $cpu_usage*100/$time;
549         my $perc;
550
551         if ($raw_perc > 1) {
552             $perc       = sprintf("%.01f", $raw_perc);
553         } elsif ($raw_perc > 0.1) {
554             $perc       = sprintf("%.02f", $raw_perc);
555         } else {                        # <=0.1
556             $perc       = sprintf("%.03f", $raw_perc);
557         }
558
559         &pSReply("Total CPU usage: $cpu_usage s ... Percentage CPU used: $perc %");
560         &DEBUG("15 => $data[15] (cutime)");
561         &DEBUG("16 => $data[16] (cstime)");
562
563         return;
564     }
565
566     # ircstats.
567     if ($message =~ /^ircstats$/i) {
568         my $count       = $ircstats{'ConnectCount'};
569         my $format_time = &Time2String(time() - $ircstats{'ConnectTime'});
570         my $reply;
571
572         foreach (keys %ircstats) {
573             &DEBUG("ircstats: $_ => '$ircstats{$_}'.");
574         }
575
576         ### RECONNECT COUNT.
577         if ($count == 1) {      # good.
578             $reply = "I'm connected to $ircstats{'Server'} and have been so".
579                 " for $format_time";
580         } else {
581             $reply = "Currently I'm hooked up to $ircstats{'Server'} but only".
582                 " for $format_time.  ".
583                 "I had to reconnect \002$count\002 times.";
584         }
585
586         ### REASON.
587         my $reason = $ircstats{'DisconnectReason'};
588         if (defined $reason) {
589             $reply .= "  I was last disconnected for '$reason'.";
590         }
591
592         &pSReply($reply);
593                 
594         return;
595     }
596
597     # status.
598     if ($message =~ /^statu?s$/i) {
599         my $startString = scalar(localtime $^T);
600         my $upString    = &Time2String(time() - $^T);
601         my $count       = &countKeys("factoids");
602
603         &pSReply(
604         "Since $startString, there have been".
605           " \002$count{'Update'}\002 ".
606                 &fixPlural("modification", $count{'Update'}).
607           " and \002$count{'Question'}\002 ".
608                 &fixPlural("question",$count{'Question'}).
609           " and \002$count{'Dunno'}\002 ".
610                 &fixPlural("dunno",$count{'Dunno'}).
611           " and \002$count{'Moron'}\002 ".
612                 &fixPlural("moron",$count{'Moron'}).
613           ".  I have been awake for $upString this session, and ".
614           "currently reference \002$count\002 factoids.  ".
615           "I'm using about \002$memusage\002 ".
616           "kB of memory."
617         );
618
619         return;
620     }
621
622     # wantNick. xk++
623     if ($message =~ /^wantNick$/i) {
624         if ($param{'ircNick'} eq $ident) {
625             &msg($who, "I hope you're right. I'll try anyway.");
626         }
627
628         my $str = "attempting to change nick to $param{'ircNick'}";
629         &status($str);
630         &msg($who, $str);
631
632         &nick($param{'ircNick'});
633         return;
634     }
635
636     return "CONTINUE";
637 }
638
639 1;