This repository was archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimbot.pl
More file actions
executable file
·1841 lines (1647 loc) · 62.2 KB
/
simbot.pl
File metadata and controls
executable file
·1841 lines (1647 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# SimBot
#
# Copyright (C) 2002-05, Kevin M Stange <kevin@simguy.net>
#
# This program is free software; you can redistribute and/or modify it
# under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# NOTE: You should not edit this file other than the path to perl at the top
# unless you know what you are doing. Submit bugfixes back to:
# http://sf.net/projects/simbot
# Hi, my name(space) is:
package SimBot;
BEGIN {
unshift (@INC, "./lib");
}
use SimBot::Util;
use Data::Dumper;
# Sometimes we end up in Unicode. Since IRC and Unicode are not good
# friends, we'll take a ride back to ISO-8859-1 before we send the
# server any questionable strings. This requires Perl 5.8.0 or a perl
# with the equivalent Encode module.
use Encode;
use constant TARGET_ENCODING => 'iso-8859-1';
# We hold our code up to some standards.
# For some well-meaning reason, strict does not allow the use of strings
# for literal references to functions and objects so we'll just tell Perl
# to let us do that without complaining.
use warnings;
use strict;
no strict 'refs';
# ****************************************
# *********** Random Variables ***********
# ****************************************
# Variables we want to use without an explicit package name
use vars qw( %chat_words $chosen_nick $chosen_server $alarm_sched_60
%plugin_help %plugin_params %hostmask_cache @servers
);
# ****************************************
# ************ Start of Script ***********
# ****************************************
&debug(DEBUG_NONE, PROJECT . " " . VERSION . "\n\n");
# Read command line options
my %args = &get_args();
# Help output
if (defined $args{help}) {
print "Usage: simbot.pl [options]\n\n"
. " --config=\"filename\"\tLoads filename.ini as the config file\n"
. " --debug=#\t\tOverrides the default debug level.\n"
. "\t\t\t 0 is silent, 1 shows errors, 2 shows alerts\n"
. "\t\t\t 3 shows IRC output, 4 shows debug output,\n"
. "\t\t\t 5 shows excessive debug output,\n"
. "\n";
exit(0);
}
# Load the configuration file.
&load_config(defined $args{config} ? $args{config} : "./config.ini");
# Check some config options or bail out!
die("Your configuration is lacking an IRC server to connect to")
unless option_list('network', 'server');
die("Your configuration is lacking a channel to join")
unless option('network', 'channel');
die("Your configuration is lacking a valid default nickname")
unless option('global', 'nickname');
die("Your configuration has an extra sentence % >= 100%")
unless option('chat', 'new_sentence_chance') < 100;
die("Your configuration has no rulefile to load")
unless option('global', 'rules');
# These are intializations of the hash tables we'll be using for
# callbacks and plugin information.
### Plugin Events ###
# Plugin events get params:
# (kernel)
our %event_plugin_load = ();
our %event_plugin_reload = ();
our %event_plugin_unload = ();
# Call event gets params:
# (kernel, from, channel, command string)
our %event_plugin_call = ();
# Bot addressing gets params:
# (kernel, from, channel, text string)
our %event_bot_addressed = ();
### Channel Events ###
# Channel events get params:
# (kernel, from, channel, eventname, params)
our %event_channel_message = (); # eventname = SAY (text)
our %event_channel_message_out = (); # eventname = SAY (text)
our %event_channel_action = (); # eventname = ACTION (text)
our %event_channel_action_out = (); # eventname = ACTION (text)
our %event_channel_notice = (); # eventname = NOTICE (text)
our %event_channel_notice_out = (); # eventname = NOTICE (text)
our %event_channel_kick = (); # eventname = KICKED (text, kicker)
our %event_channel_mode = (); # eventname = MODE (modes, arguments...)
our %event_channel_topic = (); # eventname = TOPIC (text)
our %event_channel_join = (); # eventname = JOINED ()
our %event_channel_part = (); # eventname = PARTED (message)
our %event_channel_quit = (); # eventname = QUIT (message)
our %event_channel_mejoin = (); # eventname = JOINED ()
our %event_channel_nojoin = (); # eventname = NOTJOINED (message)
our %event_channel_novoice = (); # eventname = CANTSAY ()
our %event_channel_invite = (); # eventname = INVITED ()
### Private Events ###
# Private events get params:
# (kernel, from, eventname, text)
our %event_private_message = (); # eventname = PRIVMSG ()
our %event_private_action = (); # eventname = PRIVACTION ()
our %event_private_notice = (); # eventname = NOTICE ()
# (kernel, from, dest, eventname, text)
our %event_private_message_out = (); # eventname = PRIVMSG ()
our %event_private_action_out = (); # eventname = PRIVACTION ()
our %event_private_notice_out = (); # eventname = NOTICE ()
### Server Events ###
# Server events get params:
# (kernel, server, nickname, params)
our %event_server_connect = (); # ()
our %event_server_ison = (); # (nicks list...)
our %event_server_nick = (); # (new nickname)
### Function Queries ###
# Function queries get params:
# (kernel, params)
our %query_word_score = (); # (text, start score)
our %query_userhost_mask = (); # (user@host)
our @list_nicks_ison = (
option('global', 'nickname'),
);
### Stock IRC Operations ###
# Your services plugin will probably want to override these, however
# if you do, it might not be a terrible idea to grab the original
# reference and call that if you still want to use the standard IRC
# functionality in your routine.
our %commands = (
# kick (kernel, channel, user, message)
kick => \&irc_ops_kick,
# ban (kernel, channel, user, time (secs), message)
ban => \&irc_ops_ban,
# unban (kernel, channel, user)
unban => \&irc_ops_unban,
# op (kernel, channel, user)
op => \&irc_ops_op,
# deop (kernel, channel, user)
deop => \&irc_ops_deop,
# voice (kernel, channel, user)
voice => \&irc_ops_voice,
# devoice (kernel, channel, user)
devoice => \&irc_ops_devoice,
# topic (kernel, channel, new topic)
topic => \&irc_ops_topic,
);
# This provides the descriptions of plugins. If a plugin has no
# defined description, it is "hidden" and will not appear in help.
&debug(DEBUG_SPAM, "Registering internal plugins... \n");
# register the snooze plugin only if snooze is allowed
if(option('chat','snooze') !~ m/always|never/) {
&plugin_register(plugin_id => "snooze",
plugin_params => "<on|off>",
plugin_help => "Toggles snooze mode which prevents " .
"recording and responding to chat. Commands are still " .
"processed.",
event_plugin_call => \&set_snooze,
);
}
&plugin_register(plugin_id => "stats",
plugin_help => "Shows various statistics about the database.",
event_plugin_call => \&print_stats,
);
&plugin_register(plugin_id => "help",
plugin_params => "<command name>",
plugin_help => "Seems like you've already figured out what this does, eh? Leave off the command for a list.",
event_plugin_call => \&print_help,
);
# Register the delete plugin only if the option is enabled
if(option('chat', 'delete_usage_max') != -1) {
&plugin_register(plugin_id => "delete",
plugin_params => "<word>",
plugin_help => "Erases a word that has been previously learned.",
event_plugin_call => \&delete_words,
);
}
# Now that we've initialized the callback tables, let's load
# all the plugins that we can from the plugins directory.
opendir(DIR, "./plugins");
foreach my $plugin (readdir(DIR)) {
if($plugin =~ /.*\.pl$/) {
if($plugin =~ /^services\.(.+)\.pl$/) {
&debug(DEBUG_SPAM, "$1 services plugin found.\n");
if (option('services','type') eq $1) {
&debug(DEBUG_SPAM, "$1 services plugin was selected. Attempting to load...\n");
if (eval { require "./plugins/$plugin"; }) {
&debug(DEBUG_STD, "$1 services plugin loaded successfully.\n");
} else {
&debug(DEBUG_ERR, "$@");
&debug(DEBUG_WARN, "$1 service plugin did not load due to errors.\n");
}
} else {
&debug(DEBUG_SPAM, "$1 services plugin was not selected.\n");
}
} elsif(eval { require "./plugins/$plugin"; }) {
&debug(DEBUG_STD, "$plugin plugin loaded successfully.\n");
} else {
&debug(DEBUG_ERR, "$@");
&debug(DEBUG_WARN, "$plugin plugin did not load due to errors.\n");
}
}
}
closedir(DIR);
# Here are some globals that should be initialized because someone
# might try to look at them before they get set to something.
our $loaded = 0; # The rules are not loaded yet.
our $items = 0; # We haven't seen any lines yet.
our $terminating = 0; # We are not terminating in the default case.
# set the snooze variable to the proper default
our $snooze = (option('chat','snooze') =~ m/on|always/) ? 1 : 0;
# Load the massive table of rules simbot will need.
&load;
# Now that everything is loaded, let's prepare to connect to IRC.
# We'll need this perl module to be able to do anything meaningful.
our $kernel = new POE::Kernel;
use POE;
use POE::Component::IRC;
# Create a new IRC connection.
POE::Component::IRC->spawn(alias => 'bot');
# Add the handlers for different IRC events we want to know about.
POE::Session->create(
inline_states => {
_start => \&initialize,
irc_001 => \&irc_connected, # connected
irc_005 => \&server_supports, # RPL_ISUPPORT
irc_433 => \&pick_new_nick, # nickname in use
irc_socketerr => \&socket_error, # internet wants to yell at us
irc_error => \&server_error, # server wants to yell at us
irc_465 => \&server_banned, # ERR_YOUREBANNEDCREEP
irc_disconnected => \&irc_disconnected, # disconnected
irc_303 => \&server_ison, # check ison reply
irc_352 => \&server_who, # check who reply
irc_nick => \&server_nick_change,
irc_401 => \&server_no_such_nick, # No such nick/chan error
irc_msg => \&private_message,
irc_public => \&channel_message,
irc_kick => \&channel_kick,
irc_join => \&channel_join,
irc_part => \&channel_part,
irc_quit => \&channel_quit,
irc_404 => \&channel_novoice, # we can't speak for some reason
irc_471 => \&channel_nojoin, # channel is at limit
irc_473 => \&channel_nojoin, # channel invite only
irc_474 => \&channel_nojoin, # banned from channel
irc_475 => \&channel_nojoin, # bad channel key
irc_invite => \&channel_invite,
irc_topic => \&channel_topic,
irc_mode => \&channel_mode,
irc_notice => \&process_notice,
irc_ctcp_action => \&process_action,
irc_ctcp_version => \&process_version,
irc_ctcp_time => \&process_time,
irc_ctcp_finger => \&process_finger,
irc_ctcp_ping => \&process_ping,
irc_snotice => \&server_notice,
# Custom Events
scheduler_60 => \&run_scheduler_60, # run events every 60 seconds
cont_send_pieces => \&cont_send_pieces, # send the rest of the pieces
quit_session => \&quit_session, # end the session and terminate
restart => \&restart, # end the session and restart
rehash => \&rehash, # reload data files
},
);
# ****************************************
# ********* Start of Subroutines *********
# ****************************************
# ########### GENERAL PURPOSE ############
# HOSTMASK: Generates a 'type 3' hostmask from a nick!user@host address
sub hostmask {
my ($nick, $user, $host) = split(/[@!]/, $_[0]);
if (!defined $user && !defined $host) {
if (defined &get_hostmask($nick)) {
(undef, $user, $host) = split(/[@!]/, &get_hostmask($nick));
} else {
$user = "*";
$host = "*";
}
}
my $changed = 0;
foreach my $plugin (keys(%query_userhost_mask)) {
my $newmask = &plugin_callback($plugin, $query_userhost_mask{$plugin}, ("$user\@$host"));
if (defined $newmask && $newmask =~ /.@./) {
&debug(DEBUG_SPAM, "hostmask: the $plugin plugin changed the user\@host mask\n");
($user, $host) = split(/@/, $newmask);
$changed = 1;
last;
}
}
$nick = "*" unless ($host =~ /\*/ && $user eq "*");
$user =~ s/^~?/*/ unless $user eq "*";
if (!$changed) {
if ($host =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
$host =~ s/(\.\d{1,3}){2}$/\.\*/;
} elsif ($host =~ /(([A-F0-9]{0,4}:){3})[A-F0-9]{0,4}$/i) {
$host =~ "$1:*";
} elsif ($host =~ /^(.*)(\.\w*?\.[\w\.]{3,6})$/) {
$host = "*$2";
}
}
&debug(DEBUG_SPAM, "hostmask: returning type 3 hostmask: $nick!$user\@$host\n");
return "$nick!$user\@$host";
}
# SET_HOSTMASK: Caches a new hostmask for a nickname
sub set_hostmask {
my ($nick, $mask) = @_;
if (defined $mask) {
$hostmask_cache{lc($nick)} = $mask;
} else {
delete $hostmask_cache{lc($nick)};
}
}
# GET_HOSTMASK: Returns the hostmask for a nickname
sub get_hostmask {
my $nick = lc($_[0]);
return (defined $hostmask_cache{$nick} ? $hostmask_cache{$nick} : undef);
}
# ############ IRC OPERATIONS ############
# These are the functions that a plugin should call to run an IRC operation.
# The kernel does not need to be passed to these functions
sub send_kick { &{$commands{kick}} ($kernel, @_); }
sub send_ban { &{$commands{ban}} ($kernel, @_); }
sub send_unban { &{$commands{unban}} ($kernel, @_); }
sub send_op { &{$commands{op}} ($kernel, @_); }
sub send_deop { &{$commands{deop}} ($kernel, @_); }
sub send_voice { &{$commands{voice}} ($kernel, @_); }
sub send_devoice { &{$commands{devoice}}($kernel, @_); }
sub send_topic { &{$commands{topic}} ($kernel, @_); }
sub irc_ops_kick {
my ($kernel, $channel, $user, $message) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to kick $user from $channel ($message)\n");
$kernel->post(bot => kick => $channel, $user, $message);
}
sub irc_ops_ban {
my ($kernel, $channel, $user, $time, $message) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to ban $user from $channel ($message)"
. ($time > 0 ? " for $time seconds" : "") . "\n");
$kernel->post(bot => mode => $channel, "+b", hostmask($user));
send_kick($channel, $user, $message);
if ($time > 0) {
$kernel->delay('irc_ops_unban', $time, $channel, hostmask($user));
}
}
sub irc_ops_unban {
my ($kernel, $channel, $user) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to unban $user from $channel\n");
$kernel->post(bot => mode => $channel, "-b", hostmask($user));
}
sub irc_ops_op {
my ($kernel, $channel, $user) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to op $user on $channel\n");
$kernel->post(bot => mode => $channel, "+o", $user);
}
sub irc_ops_deop {
my ($kernel, $channel, $user) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to deop $user on $channel\n");
$kernel->post(bot => mode => $channel, "-o", $user);
}
sub irc_ops_voice {
my ($kernel, $channel, $user) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to voice $user on $channel\n");
$kernel->post(bot => mode => $channel, "+v", $user);
}
sub irc_ops_devoice {
my ($kernel, $channel, $user) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to devoice $user on $channel\n");
$kernel->post(bot => mode => $channel, "-v", $user);
}
sub irc_ops_topic {
my ($kernel, $channel, $topic) = @_;
&debug(DEBUG_INFO, "Irc Ops: attempting to set the topic to $topic on $channel\n");
$kernel->post(bot => topic => $channel, $topic);
}
# ########### FILE OPERATIONS ############
# LOAD: This will load our rules.
sub load {
my $rulefile = option('global', 'rules');
my ($lfound, $rfound);
my $deleted = 0;
&debug(DEBUG_STD, "Loading $rulefile... ");
$loaded = 0;
if(open(RULES, $rulefile)) {
foreach(<RULES>) {
chomp;
s/\r//;
my @rule = split (/\t/);
$chat_words{$rule[0]}{$rule[1]}[1] = $rule[2];
$chat_words{$rule[1]}{$rule[0]}[0] = $rule[2];
}
close(RULES);
&debug(DEBUG_STD, "Rules loaded successfully!\n", DEBUG_NO_PREFIX);
$loaded = 1;
&debug(DEBUG_STD, "Checking for lost words... ");
foreach my $word (keys(%chat_words)) {
next if ($word =~ /^__[\!\?]?[A-Z]*$/);
$lfound = 0;
$rfound = 0;
foreach (keys(%{$chat_words{$word}})) {
# If we find out a word has any links to the right, we're good.
if (defined $chat_words{$word}{$_}[1] && $rfound == 0) {
$rfound = 1;
}
# If we find out a word has any links to the left, we're good.
if (defined $chat_words{$word}{$_}[0] && $lfound == 0) {
$lfound = 1;
}
}
if ($lfound == 0 || $rfound == 0) {
print "\n" if !$deleted;
$deleted = 1;
delete_word($word, 0);
}
}
if (!$deleted) {
&debug(DEBUG_STD, "No lost words found!\n");
} else {
&debug(DEBUG_STD, "All lost words removed successfully.\n");
}
} elsif (!-e $rulefile) {
&debug(DEBUG_WARN, "File does not exist and will be created on save.\n");
$loaded = 1;
} else {
&debug(DEBUG_ERR, "Cannot read from the rules file! This session will not be saved!\n");
}
}
# SAVE: This will save our rules.
sub save {
my $rulefile = option('global', 'rules');
&debug(DEBUG_STD, "Saving $rulefile... ");
if ($loaded == 1) {
if(open(RULES, ">$rulefile")) {
flock(RULES, 2);
foreach(keys(%chat_words)) {
my $a = $_;
foreach(keys(%{$chat_words{$a}})) {
my $b = $_;
my $c = $chat_words{$a}{$b}[1];
print RULES "$a\t$b\t$c\n" if defined $c;
}
}
flock(RULES, 8);
close(RULES);
&debug(DEBUG_STD, "Rules saved successfully!\n");
} else {
&debug(DEBUG_ERR, "Cannot write to the rules file! This session will be lost!\n");
}
} else {
&debug(DEBUG_WARN, "Opting not to save. Rules are not loaded.\n");
}
$items = 0;
}
# ########### PLUGIN OPERATIONS ############
# PLUGIN_REGISTER: Registers a plugin (or doesn't).
sub plugin_register {
my %data = @_;
$data{plugin_id} = lc($data{plugin_id});
if(!$event_plugin_call{$data{plugin_id}}) {
&debug(DEBUG_SPAM, $data{plugin_id} . ": no plugin conflicts detected\n");
} else {
die("$data{plugin_id}: a plugin is already registered to this handle");
}
if ($data{event_plugin_load}) {
if (!&plugin_callback($data{plugin_id}, $data{event_plugin_load})) {
die("$data{plugin_id}: the plugin returned an error on load");
}
}
$event_plugin_call{$data{plugin_id}} = $data{event_plugin_call};
if(!$data{plugin_help}) {
&debug(DEBUG_SPAM, $data{plugin_id} . ": this plugin has no help text and will be hidden\n");
} else {
$plugin_help{$data{plugin_id}} = $data{plugin_help};
}
$plugin_params{$data{plugin_id}} = $data{plugin_params};
foreach (keys(%data)) {
if ($_ =~ /^event_(plugin|bot|channel|private|server)_.*/) {
$$_{$data{plugin_id}} = $data{$_};
} elsif ($_ =~ /^query_.*/) {
$$_{$data{plugin_id}} = $data{$_};
} elsif ($_ =~ /^list_.*/) {
my @list = split(/,\s*/, $data{$_});
push(@{$_}, @list);
} elsif ($_ =~ /^hash_.*/) {
$$_{$data{plugin_id}} = $data{$_};
}
}
return 1;
}
# PLUGIN_CALLBACK: Calls the given plugin function with paramters.
sub plugin_callback {
my ($plugin, $function, @params) = @_;
&debug(DEBUG_SPAM, "Running callback to $function in $plugin.\n");
return &$function($kernel, @params);
}
# SET_SNOOZE: Sets the snooze mode on or off.
sub set_snooze {
my ($nick, $channel, $option) = @_[1,2,4];
if (lc($option) eq "off") {
if ($snooze) {
$snooze = 0;
&debug(DEBUG_STD, "snooze: Snooze mode was turned OFF by $nick.\n");
&send_action($channel, "streches and yawns.");
&send_message($channel, "$nick: Thanks for the wake up call. Time to get back to work!");
} else {
&debug(DEBUG_INFO, "snooze: Snooze mode was OFF, but $nick wanted to try anyway.\n");
&send_message($channel, "$nick: Do I look like I'm sleeping to you?");
}
} elsif (lc($option) eq "on") {
if ($snooze) {
&debug(DEBUG_INFO, "snooze: Snooze mode was ON, but $nick wanted to try anyway.\n");
&send_message($channel, "$nick: You're waking me up to tell me to take a nap? What kind of monster are you!?");
} else {
$snooze = 1;
&debug(DEBUG_STD, "snooze: Snooze mode was turned ON by $nick.\n");
&send_message($channel, "$nick: You know, a nap sounds great right about now. Wake me if you need anything.");
&send_action($channel, "lays down and begins to snore....");
}
} else {
&send_message($channel, "$nick: Snooze mode is " . ($snooze ? "ON" : "OFF") . ". Specify 'on' to enter snooze mode. I will stop paying attention to chat, but I'll still look for commands. Specify 'off' to wake me back up.");
}
}
# PRINT_HELP: Prints a list of valid commands privately to the user.
sub print_help {
my ($nick, $command) = @_[1,4];
my $prefix = option('global', 'command_prefix');
my $message;
&debug(DEBUG_INFO, "help: requested by " . $nick . "." .
(defined $command ? " ($command)" : "") . "\n");
if (!defined $command) {
$message = "Prefix commands with '$prefix' when you use them. For help with a command, try typing %bold%" . $prefix . "help <command>%bold%\n";
my $count = 0;
my @commands = sort {$a cmp $b} keys(%plugin_help);
while (defined $commands[$count]) {
$message .= sprintf(" %-12s %-12s %-12s %-12s\n",
$commands[$count++], $commands[$count++],
$commands[$count++], $commands[$count++]);
}
} else {
$command =~ s/^$prefix//;
if (!defined $plugin_help{$command} &&
!defined $plugin_params{$command}) {
$message = "There is no help for that command, or it does not exist.";
} else {
$message = "%uline%Usage:%uline% %bold%${prefix}$command%bold% "
. (defined $plugin_params{$command}
? $plugin_params{$command} : "")
. (defined $plugin_help{$command}
? "\n$plugin_help{$command}" : "");
}
}
$message = parse_style($message);
chomp $message;
&send_pieces($nick, undef, $message);
}
# PRINT_STATS: Prints some useless stats about the bot to the channel.
sub print_stats {
my $nick = $_[1];
my $channel = $_[2];
my (@ldeadwords, @rdeadwords) = ();
my ($message, $wordpop);
my ($lfound, $lcount, $rfound, $rcount, $wordpopcount) = (0, 0, 0, 0, 0);
&debug(DEBUG_INFO, "stats: requested by " . $nick . ".\n");
my $count = keys(%chat_words);
my $begins = keys(%{$chat_words{'__BEGIN'}}) + keys(%{$chat_words{'__!BEGIN'}}) + keys(%{$chat_words{'__?BEGIN'}});
my $ends = keys(%{$chat_words{'__END'}}) + keys(%{$chat_words{'__!END'}}) + keys(%{$chat_words{'__?END'}});
my $actions = keys(%{$chat_words{'__ACTION'}});
&send_message($channel, "In total, I know $count words. I've learned $begins words that I can start a sentence with, and $ends words that I can end one with. I know of $actions ways to start an IRC action (/me).");
# Process through the list and find words that have no links in one or
# both directions (because we can never use these words safely). We'll
# be nice and efficient and use this same loop to find the most frequent
# two word sequence.
foreach my $word (keys(%chat_words)) {
next if ($word =~ /^__[\!\?]?[A-Z]*$/);
$lfound = 0;
$rfound = 0;
foreach (keys(%{$chat_words{$word}})) {
# If we find out a word has any links to the right, we're good.
if (defined $chat_words{$word}{$_}[1] && $rfound == 0) {
$rfound = 1;
}
# If we find out a word has any links to the left, we're good.
if (defined $chat_words{$word}{$_}[0] && $lfound == 0) {
$lfound = 1;
}
# Find the most popular two word sequence.
if (defined $chat_words{$word}{$_}[1]) {
if ($chat_words{$word}{$_}[1] > $wordpopcount
&& $_ !~ /^__[\!\?]?[A-Z]*$/
&& length($word) > 3 && length($_) > 3) {
$wordpop = "$word $_";
$wordpopcount = $chat_words{$word}{$_}[1];
}
}
}
if ($lfound == 0) {
$lcount++;
push(@ldeadwords, "'$word'");
}
if ($rfound == 0) {
$rcount++;
push(@rdeadwords, "'$word'");
}
}
&send_message($channel, "The most popular two word sequence (with more than 3 letters) is \"$wordpop\" which has been used $wordpopcount times.");
if ($rcount > 0) {
&send_pieces($channel, "", "There are $rcount words that lead me to unexpected dead ends. They are: @rdeadwords");
}
if ($lcount > 0) {
&send_pieces($channel, "", "There are $lcount words that lead me to unexpected dead beginnings. They are: @ldeadwords");
}
}
# DELETE_WORDS: This removes a word, if it hasn't been deeply ingrained
# in the database (used a lot) and tells the user what has been done.
sub delete_words {
my (undef, $nick, $channel, undef, $word) = @_;
my $max = option('chat', 'delete_usage_max');
$word = lc($word);
if (defined $word && $word ne "") {
my @deleted = &delete_word($word, $max);
if (!@deleted && !defined $chat_words{$word}) {
&send_message($channel, "$nick: I don't remember ever seeing that word before. It will be hard to forget it.");
} elsif (!@deleted) {
&send_message($channel, "$nick: '$word' may not be deleted because I've seen it used more than $max times.");
} else {
&send_message($channel, "$nick: I've supressed any knowledge of the words: " . join(", ", @deleted));
}
} else {
&send_message($channel, "$nick: You need to tell me which word you want me to dropkick to oblivion.");
}
}
# ######### CONVERSATION LOGIC ###########
# BUILD_RECORDS: This creates new rules and adds them to the database.
sub build_records {
my $action = ($_[1] ? $_[1] : "");
my @sentence = split(/\s+/, $_[0]);
$items++;
my $tail = -1;
my $punc = "";
# Eat anything that looks like it might be a smiley at end of our line.
if (defined $sentence[$tail]) {
while ($sentence[$tail] =~ /^[:;=].*/) {
$tail--;
}
# Look for punctuation to be recorded.
$sentence[$tail] =~ /([\!\?])[^\!\?]*$/;
$punc = $1 if(defined $1);
}
# Define the start and end tags such that we reflect the punctuation
# we found.
my $startblock = "__" . $punc . "BEGIN";
my $endblock = "__END";
# Go through every word and sanitize the text so that we record as little
# junk as possible.
for(my $x=0; $x <= $#sentence; $x++) {
# Eat smileys. The second line tries to eat smileys with ='s for eyes.
$sentence[$x] =~ s/^[;:].*//;
$sentence[$x] =~ s/^=[^=]+//;
if($sentence[$x] =~ m/.>$/) {
while($x+1 > 0) {
shift(@sentence);
$x--;
}
}
goto skiptosave if(!@sentence); # Yipes, a goto!
# Remove all characters that we don't like. Right now we accept
# letters, numbers, international characters (ASCII), as well as:
# ', /, -, ., =, %, $, &, +, @
$sentence[$x] =~ s/[^\300-\377\w\'\/\-\.=\%\$&\+\@]*//g;
# Don't record dots that aren't inside a word.
$sentence[$x] =~ s#(^|\s)\.+|\.+(\s|$)##g;
# For the safety of everyone, we record in lowercase.
$sentence[$x] = lc($sentence[$x]);
# After all this, if we're short on letters, we can't record this.
if ("@sentence" !~ /[A-Za-z0-9\300-\377]/) {
&debug(DEBUG_INFO, "This line contained no discernable words: @sentence\n");
goto skiptosave; # Oh my, a goto!
}
# If we match any of the filters defined by the user's config file,
# we're not going to record this line.
foreach (option_list('filters')) {
if ($sentence[$x] =~ /$_/) {
&debug(DEBUG_INFO, "Not recording this line: @sentence\n");
goto skiptosave; # Oh my, a goto!
}
}
}
# Lines of nothing but whitespace aren't worth trying to record.
if ("@sentence" =~ /^\s*$/) {
&debug(DEBUG_INFO, "This line contained no discernable words: @sentence\n");
goto skiptosave; # Oh my, a goto!
}
# If this was an IRC action, we want to remember this in the database.
if ($action eq "ACTION") {
@sentence = ("__ACTION", @sentence);
}
# Assemble the sentence!
@sentence = ($startblock, @sentence, $endblock);
my $i = 0;
while ($i < $#sentence) {
if($sentence[$i+1] ne "") {
my $cur_word = $sentence[$i];
my $y = 0;
# Skip over any empty words in the array.
while ($cur_word eq "") {
$y++;
$cur_word = $sentence[$i-$y];
}
# If we've seen this word pairing before, simply increment the
# counter.
if ($chat_words{$cur_word}{$sentence[$i+1]}[1]) {
$chat_words{$cur_word}{$sentence[$i+1]}[1]++;
$chat_words{$sentence[$i+1]}{$cur_word}[0]++;
&debug(DEBUG_INFO, "Updating $cur_word-\>$sentence[$i+1] to " . $chat_words{$cur_word}{$sentence[$i+1]}[1] . "\n");
&debug(DEBUG_SPAM, "Updating $sentence[$i+1]-\>$cur_word to " . $chat_words{$sentence[$i+1]}{$cur_word}[0] . " (reverse)\n");
# Otherwise, add the word pairing as new to the database.
} else {
$chat_words{$cur_word}{$sentence[$i+1]}[1] = 1;
$chat_words{$sentence[$i+1]}{$cur_word}[0] = 1;
&debug(DEBUG_INFO, "Adding $cur_word-\>$sentence[$i+1]\n");
&debug(DEBUG_SPAM, "Adding $sentence[$i+1]-\>$cur_word (reverse)\n");
}
}
$i++;
}
skiptosave: # Oh my, a goto label!
# Check to see if it's time to save the data. Right now we do this
# every time we record 20 new items to the database.
if ($items >= 20) {
&save;
}
}
# BUILD_REPLY: This creates a random reply from the database.
sub build_reply {
# No reason to waste effort if the database is empty.
if (%chat_words) {
my @sentence = split(/ /, $_[0]);
# find an interesting word to base the sentence off
my $newword = &find_interesting_word(@sentence);
my $middleword = $newword;
my $return = ($newword ? "$newword " : "");
my $punc = "";
while ($newword !~ /^__[\!\?]?END$/) {
my $chcount = 0;
if (!$newword) {
my %choices = ("__BEGIN", 0,
"__!BEGIN", 0,
"__?BEGIN", 0,
);
foreach my $key (keys(%choices)) {
foreach (keys(%{$chat_words{$key}})) {
$choices{$key} = 0 if !$choices{$key};
$choices{$key} += $chat_words{$key}{$_}[1];
}
$chcount += $choices{$key};
}
my $try = int(rand()*($chcount))+1;
foreach(keys(%choices)) {
$try -= $choices{$_};
if ($try <= 0) {
$newword = $_;
m/^__([\!\?])?BEGIN$/;
if ($1) {
$punc = $1;
debug(DEBUG_INFO, "Using '$1' from __BEGIN\n");
}
last;
}
}
}
$chcount = 0;
if ($newword) {
foreach (keys(%{$chat_words{$newword}})) {
$chcount += $chat_words{$newword}{$_}[1] if defined $chat_words{$newword}{$_}[1];
}
debug(DEBUG_SPAM, "$chcount choices for next to $newword\n");
}
my $try = int(rand()*($chcount))+1;
foreach(keys(%{$chat_words{$newword}})) {
$try -= $chat_words{$newword}{$_}[1] if defined $chat_words{$newword}{$_}[1];
if ($try <= 0) {
debug(DEBUG_SPAM, "Selected $_ to follow $newword\n");
$newword = $_;
if($newword =~ /^__([\!\?])?END$/) {
if ($1 && !$punc) {
$punc = $1;
debug(DEBUG_INFO, "Using '$1' from __END\n");
}
} else {
$return .= $newword . " ";
}
last;
}
}
if ($try > 0) {
$newword = "__END";
&debug(DEBUG_ERR, "Database problem! Hit a dead end in \"$return\"...\n");
}
} # ENDS while
# If we had an interesting "middleword", this segment of code will
# generate the first part of the sentence and tack it on before the
# end that we've already generated.
if($middleword) {
$newword = $middleword;
while ($newword !~ /^__[\!\?]?BEGIN$/) {
my $chcount = 0;
foreach (keys(%{$chat_words{$newword}})) {
$chcount += $chat_words{$newword}{$_}[0] if defined $chat_words{$newword}{$_}[0];
}
&debug(DEBUG_SPAM, "$chcount choices for next to $newword\n");
my $try = int(rand()*($chcount))+1;
foreach(keys(%{$chat_words{$newword}})) {
$try -= $chat_words{$newword}{$_}[0] if defined $chat_words{$newword}{$_}[0];
if ($try <= 0) {
debug(DEBUG_SPAM, "Selected $_ to follow $newword\n");
$newword = $_;
if($newword =~ /^__([\!\?])?BEGIN$/) {
if ($1) {
$punc = $1;
debug(DEBUG_INFO, "Using '$1' from __BEGIN\n");
}
} else {
$return = $newword . " " . $return;
}
last;
}
}
if ($try > 0) {
$newword = "__BEGIN";
&debug(DEBUG_ERR, "Database problem! Hit a dead beginning in \"$return\"...\n");
}
} # ENDS while
}
$return =~ s/\s+$//;
$return = uc(substr($return, 0,1)) . substr($return, 1) . ($punc ne "" ? $punc : ".");
$return =~ s/\bi(\b|\')/I$1/g; # '
my $chance = option('chat', 'new_sentence_chance');
if ($chance && int(rand()*(100/$chance)) == 0) {
&debug(DEBUG_INFO, "Adding another sentence...\n");
$return .= "__NEW__" . &build_reply("");
}
return $return;
} else {
&debug(DEBUG_ERR, "Could not form a reply.\n");
return "I'm speechless.";
}
}
# FIND_INTERESTING_WORD: Finds a word to base a sentence off
sub find_interesting_word {
my ($curWordScore, $highestScoreWord, $highestScore, $curWord);
my $nickmatch = "^(" . $chosen_nick . "|" .
option('global', 'nickname') . "|" .
option('global', 'alt_tag') . ")\$";
# The point here is to pick a base score that adapts a bit to the size of
# the database
my $startScore = int((keys(%chat_words) ** 0.1) * 5000);
debug(DEBUG_INFO, "Word scores: ");
$highestScoreWord = ""; $highestScore=0;
foreach my $curWord (@_) {
$curWord = lc($curWord);
$curWord =~ s/[,\.\?\!\:]*$//;
if(!defined $chat_words{$curWord}
|| $curWord =~ /$nickmatch/i) {
next;
}
$curWordScore = $startScore;
foreach(keys(%query_word_score)) {
$curWordScore += &plugin_callback($_, $query_word_score{$_}, ($curWord), $startScore);
}
foreach my $nextWord (keys(%{$chat_words{$curWord}})) {
if($nextWord =~ /__[\.\?\!]?(END|BEGIN)$/) {
$curWordScore -= 1.8 * $chat_words{$curWord}{$nextWord}[1] if defined $chat_words{$curWord}{$nextWord}[1];
$curWordScore -= 1.8 * $chat_words{$curWord}{$nextWord}[0] if defined $chat_words{$curWord}{$nextWord}[0];
} else {
$curWordScore -= $chat_words{$curWord}{$nextWord}[1] if defined $chat_words{$curWord}{$nextWord}[1];
}
}
$curWordScore += .7 * length($curWord);
&debug(DEBUG_INFO, "$curWord:$curWordScore ", DEBUG_NO_PREFIX);
if($curWordScore > $highestScore) {
$highestScore = $curWordScore;
$highestScoreWord = $curWord;
}
}
&debug(DEBUG_INFO, "\n", DEBUG_NO_PREFIX);
&debug(DEBUG_INFO, "Using $highestScoreWord\n");
return $highestScoreWord;
}
# DELETE_WORD: Removes a word and any exclusive chains from that word
# from the database. The second argument is a number, which prevents