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