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