This repository has been archived by the owner on Sep 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
megahal.c
4308 lines (3768 loc) · 111 KB
/
megahal.c
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
/*===========================================================================*/
/*
* Copyright (C) 2009 Zev Toledano
* Original Copyright (C) 1998/1999 Jason Hutchens
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* 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 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.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*===========================================================================*/
/*
* MegaHAL module for eggdrop v3.7
* By Zev ^Baron^ Toledano (megahal at thelastexit.net) and Jason Hutchens
* Artificially Intelligent conversation with learning capability and
* psychotic personality.
*
* Note: The original AI work and program was written by J. Hutchens in 1999.
* The eggdrop port was coded by Zev Toledano and it necessitated
* various major changes to the brain structure and code in order to keep the
* brain at a manageable size. Various commands and fun features were added as
* well.
* Important: Old brains (1.x/2.x *.brn files) will NOT work with this version (3.0)! You
* must start a new one.
*
* (all old comments were moved to the end of this file)
*
* Additions and changes by Nexor:
*
* Ver 3.7 Nov 2010
* - Fixed memory allocation bug in mystrdup
* - Megahal training resources and other read only files moved to separate directories: megahal_directory_resource
* - Megahal brains and generated files moved to separate directories: megahal_directory_cache
* - Removed compilation warnings with fread
* - Rewrited change_personality and load_personality
*
* Additions and changes by z0rc:
*
* Ver 3.6: Nov 2009
* - Support of multibyte text encodings based on locale settings
*
* Additions and changes by ^Baron^:
*
* Ver 3.5: Jul 2009
* - Made .forget detect smaller words
* - Fixed bug with newer eggdrops where it was responding twice
* - Chat now ignores pub channel commands
* - Fixed some buffer overruns
* - Removed more compilation warnings
* Ver 3.4: Apr 2006
* - Added .forgetword pub command - note that this deletes all phrases containing that word
* - Fixed a bug in trimdictionary that was messing up the index, thus making the find_words less functional every time the dictionary got trimmed
* - Fixed a bug where only irc client codes in the text made it crash
* - Improved speed of trimdictionary
* - Fixed bug loading phrases from the brain without a terminator, causing rare bugs when deleting phrases from small brains
* - Fixed bug with spaces at end of phrases
* - Fixed occasional crash when loading brain
* - Fixed bug where responsekeywords weren't removed from phrase before they were learned
*
* Ver 3.3: Nov 2003
* - Improved forget command fuzzy logic to find better matching phrases
* - Added learnfreq x setting to make bot learn every x amount of phrases said in channels
* - It now also learns phrases with the botnick in the beginning or end of the phrase
* i.e. no need for the botnick: trigger
* - Added responsekeywords setting to enable keywords that must be responded to
*
* Ver 3.22: May 2001
* - Cleaned up the code so that no warnings will be issued by the compiler
* - Fixed a bug that caused crashes in eggdrop 1.6.4 and fixed a memory leak
* - Fixed a crash problem when the botnick was mentioned without anything else on some bots
* - Fixed a bug where failed realloc complaints were being issued when using .forget
*
* Ver 3.21: Mar 2001
* - Improved the anti-repeat check so that it does fuzzy searches in the
* previous replies before responding.
* - Added mirc/pirc/etc code stripping!
*
* Ver 3.2: Mar 2001
* - Fixed bug in find_phrase for the forget command - it wasn't finding
* bigger phrases
* - Fixed make_keywords so that it also adds words that start with the
* special char31 character (nospace)
* - Added a check for reply repetitions so that it doesn't say the same thing
* in 5 consecutive replies.
* - Fixed bug that seems to have been there all along where the find_words
* function was wrongly used with all dictionaries and it treated index 0
* as an error! Replies should be much more appropriate now!
* - Added a maxreplywords setting to limit the output to smaller lines
* - Added a check for repeats in the replies so that it doesn't get stuck in
* a loop and output repetitive sentences.
* - Fixed treatment of hyphenated words
* - Fixed bug where last word was being replaced by a period if it was
* not preceded by a space.
* - Users text and AI output is now outputted to the channel log files as well.
* - Fixed bug in delete_all_phrases where multiples were found and index got
* moved down while deleting.
* - Removed copybrain function - use setmaxcontext or reloadphrases instead.
* - It now checks for spaces first before learning new phrases.
* - Added reloadphrases function for reloading the brain from the megahal.phr
* file.
* - Added learnfile function for adding new phrases to the brain from a file.
* - Added surprise setting for turning surprise mode on or off.
* - Added setmaxcontext function for changing the order value in the brain
* dynamically.
*
* Ver 3.11: Feb 2001
* - Added flood protection
* - Added tcl vars for various settings
* - Made each channel mantain its own counter for talkfrequency
* - Added strings for excluding specific channels from either the bot responses
* to its nickname or from the talkfrequency stuff
* - talkfrequency can now be set to 0 to turn it off
*
* Ver 3.1: Feb 2001
* - .forget command both in dcc and public. Searches for closest matches and
* deletes a phrase from the brain.
* - .megaver command in dcc and public for displaying the version information
* - actions are now detected in public as well.
* - copybrain tcl command for copying one model to another. It can be used to
* start a fresh brain with only valid phrases in case anything went wrong
* or to change the order setting for an existing brain.
* - setmegabotnick tcl command for setting the bot nickname dynamically. The
* bindings still have to be changed separately though - this is only for the
* detection of the bot nick in all public chatter.
* - expmem - now roughly estimates the mem used by this module. The report
* function (used by the .status command) now also displays more information.
*
* Ver 3.0: Feb 2001
* - Tricky bug in trimbrain required a major change in the brain structure
* again to keep track of phrases (a phrase field was added to the model and
* LOTS of code changed to work with this).
* - Added BIG trimdictionary function for trimming words that arent used anymore.
*
* Ver 2.0: Jan 2001
* - In order to be able to trim the brain, the format of the brain was changed
* (yes old ones will not work anymore). Every phrase now starts with a
* special <START> symbol so that we can find phrases more easily.
* - Added a complex trimbrain function to trim the brain down to a specified
* size.
* - Spaces were abolished from the brain thus saving at least 60% of the memory
* footprint! This meant:
* Detecting spaces and removing them from the text or simply skipping over
* them instead of including them as words.
* Every 'word' that is not preceded by a space is now saved
* with a preceding special character (#31). This character is used as a
* flag on whether to add a space or not.
* Making the 'order' variable smaller (2 or 3) so that the context isnt too
* big and some randomness creeps in.
* - Added realloc functions for resizing a dictionary or tree.
* - Added function definitions finally for all eggdrop stuff and moved all the
* defs to the header file.
* - Changed everything to static but it didnt seem to help the ram (?)
* - Cleaned up some code that stayed behind from the non-eggdrop version.
*
* Ver 1.6: Jan 2001
* - Improved the viewbranch tcl command to make it more robust and MUCH nicer
* on the eyes.
* - Added the learningmode TCL command for setting the mode on or off. When off,
* it can converse without making the brain grow.
* - Made the bot nickname more easily changeable by setting the preprocessor
* variable BOTNICK.
* - It now listens to all public chatter and detects when the bot nickname is
* typed anywhere in the text then uses only the REST of the text to generate a
* reply. It still only learns through BOTNICK: though.
* - talkfrequency - TCL and variable for replying at the specified frequency to
* whatever is said in the public channels regardless of the text.
*
* Ver 1.5: Dec 2000
* - Removed the useless private MSG commands and conversation.
* - Added the following TCL commands so that stuff can be automated or
* interacted with through TCL:
* - savebrain - for saving the brain to disk.
* - treesize - for viewing information on the model and branches like
* branch size, amount of nodes and usage counters.
* - reloadbrain - for reloading the brain from file. This can be used by
* scripts to start a new brain or to restore old ones for example.
* - viewbranch - just for curiosity or debugging. it will show a branch or
* subbranch with all its data and subbranches.
*/
/* change these to your bot name */
#define BOTNICK "Kuro-sama"
#define BOTNICK2 "Kuro-sama:"
#define BOTNICK3 "Kuro-sama,"
#define MAKING_MEGAHAL
#define MODULE_NAME "MegaHAL"
#define VER "3.7"
#define VER1 3
#define VER2 7
#define COOKIE "MegaHAL83"
#include <stdlib.h>
/* megahal preproc directives */
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#include <sys/types.h>
#include <locale.h>
#include <wctype.h>
#define __USE_UNIX98
#include <wchar.h>
#include "megahal.h"
/* End megahal preproc directives */
#include "../module.h"
#include "../irc.mod/irc.h"
#include "../server.mod/server.h"
#undef global
/* predefinitions for megahal*/
static int rnd(int);
static int order = 2;
static int timeout = 1;
static DICTIONARY *ban = NULL;
static DICTIONARY *aux = NULL;
static SWAP *swp = NULL;
static bool used_key;
static char directory_cache[513] = DIR_DEFAULT_CACHE;
static char directory_resources[513] = DIR_DEFAULT_RESOURCES;
/* predefinitions for eggdrop port */
static Function *global = NULL;
static Function *irc_funcs = NULL, *server_funcs = NULL;
static DICTIONARY *words = NULL;
static MODEL *model = NULL;
static int talkfrequency = 40;
static int learnfrequency = 40;
static bool learningmode = TRUE;
static wchar_t glob_str[15000];
static wchar_t glob_buffer[513];
static wchar_t mbotnick[32] = _T(BOTNICK);
static int maxlines = 10, maxtime = 60, curlines = 0, curtime = 0;
static char texcludechans[513] = "", rexcludechans[513] = "", responsekeywords[513] = "";
static int maxsize = 100000;
static int maxreplywords = 0;
static int surprise = 1;
static DICTIONARY *prev1, *prev2, *prev3, *prev4, *prev5;
static cmd_t mega_dcc[] =
{
{BOTNICK, "", dcc_megahal, NULL},
{"forget", "m", dcc_forget, NULL},
{"megaver", "", dcc_megaver, NULL},
{NULL, NULL, NULL, NULL}
};
static cmd_t mega_pub[] =
{
{BOTNICK2, "", pub_megahal, NULL},
{BOTNICK3, "", pub_megahal, NULL},
{"!megaver", "", pub_megaver, NULL},
{"!forget", "m", pub_forget, NULL},
{"!forgetword", "m", pub_forgetword, NULL},
{NULL, NULL, NULL, NULL}
};
static cmd_t mega_pubm[] =
{
{"*", "", pub_megahal2, "mega"},
{NULL, NULL, NULL, NULL}
};
static cmd_t mega_ctcp[] =
{
{"ACTION", "", pub_action, "mega"},
{NULL, NULL, NULL, NULL}
};
static tcl_cmds mytcls[] =
{
{"savebrain", tcl_savebrain},
{"reloadbrain", tcl_reloadbrain},
{"trimbrain", tcl_trimbrain},
{"treesize", tcl_treesize},
{"learningmode", tcl_learningmode},
{"talkfrequency", tcl_talkfrequency},
{"viewbranch", tcl_viewbranch},
{"setmaxcontext", tcl_setmaxcontext},
{"setmegabotnick", tcl_setmegabotnick},
{"reloadphrases", tcl_reloadphrases},
{"learnfile", tcl_learnfile},
{0, 0}
};
static tcl_ints my_tcl_ints[] =
{
{"talkfreq", &talkfrequency, 0},
{"learnfreq", &learnfrequency, 0},
{"maxsize", &maxsize, 0},
{"maxreplywords", &maxreplywords, 0},
{"surprise", &surprise, 0},
{0, 0, 0}
};
static tcl_strings my_tcl_strings[] =
{
{"talkexcludechans", texcludechans, 512, 0},
{"respondexcludechans", rexcludechans, 512, 0},
{"responsekeywords", responsekeywords, 512, 0},
{"megahal_directory_resources", directory_resources, 512, 0},
{"megahal_directory_cache", directory_cache, 512, 0},
{0, 0, 0, 0}
};
static tcl_coups my_tcl_coups[] =
{
{"floodmega", &maxlines, &maxtime},
{0, 0, 0}
};
static Function megahal_table[] =
{
(Function) megahal_start,
(Function) megahal_close,
(Function) megahal_expmem,
(Function) megahal_report,
};
/* end predefinitions */
static wchar_t *locale_to_wchar(char *str)
{
wchar_t *ptr;
size_t s;
Context;
/* first arg == NULL means 'calculate needed space' */
s = mbstowcs(NULL, str, 0);
/* a size of -1 is triggered by an error in encoding; never
happen in ISO-8859-* locales, but possible in UTF-8 */
if(s == -1)
return NULL;
/* malloc the necessary space */
if((ptr = (wchar_t *)nmalloc((s+1)*sizeof(wchar_t))) == NULL)
return NULL;
/* really do it */
mbstowcs(ptr, str, s);
/* ensure NULL-termination */
ptr[s] = L'\0';
/* remember to free() ptr when done */
return ptr;
}
static char *wchar_to_locale(wchar_t *str)
{
char *ptr;
size_t s;
Context;
/* first arg == NULL means 'calculate needed space' */
s = wcstombs(NULL, str, 0);
/* a size of -1 means there are characters that could not
be converted to current locale */
if(s == -1)
return NULL;
/* malloc the necessary space */
if((ptr = (char *)nmalloc(s+1)) == NULL)
return NULL;
/* really do it */
wcstombs(ptr, str, s);
/* ensure NULL-termination */
ptr[s] = '\0';
/* remember to free() ptr when done */
return ptr;
}
static wchar_t *mynewsplit(wchar_t **rest)
{
register wchar_t *o, *r;
Context;
if(!rest)
return *rest = L"";
o = *rest;
while(*o == L' ')
o++;
r = o;
while(*o && (*o != L' '))
o++;
if(*o)
*o++ = 0;
*rest = o;
return r;
}
// rough estimate here - if you want precise numbers do it yourself :-p
static int megahal_expmem()
{
register int i;
int size = 0, tmp;
Context;
size += sizeof(MODEL);
tmp = recurse_tree(model->forward);
size += tmp*sizeof(TREE);
size += tmp*sizeof(TREE *);
tmp = recurse_tree(model->backward);
size += tmp*sizeof(TREE);
size += tmp*sizeof(TREE *);
for(i=0; i<model->phrasecount; i++)
size += model->phrase[i][0]+1*sizeof(BYTE2);
size += model->phrasecount*sizeof(BYTE2 *);
size += dictionary_expmem(model->dictionary);
size += dictionary_expmem(ban);
size += dictionary_expmem(aux);
size += dictionary_expmem(words);
size += sizeof(SWAP);
for(i=0; i<swp->size; i++) {
size += swp->from[i].length*sizeof(wchar_t);
size += swp->to[i].length*sizeof(wchar_t);
}
size += swp->size*sizeof(STRING)*2;
return size;
}
static int dictionary_expmem(DICTIONARY *dictionary)
{
register int i;
int size = 0;
Context;
size += sizeof(DICTIONARY);
for (i=0; i<dictionary->size; i++)
size += dictionary->entry[i].length*sizeof(wchar_t);
size += dictionary->size*sizeof(STRING);
size += dictionary->size*sizeof(BYTE2);
return size;
}
static wchar_t *megahal_close()
{
p_tcl_bind_list H_temp;
Context;
save_model("megahal.brn", model);
rem_builtins(H_dcc, mega_dcc);
rem_builtins(H_pubm, mega_pubm);
rem_builtins(H_ctcp, mega_ctcp);
if((H_temp = find_bind_table("pub")))
rem_builtins(H_temp, mega_pub);
rem_tcl_ints(my_tcl_ints);
rem_tcl_coups(my_tcl_coups);
rem_tcl_strings(my_tcl_strings);
rem_tcl_commands(mytcls);
module_undepend(MODULE_NAME);
free_model(model);
free_words(ban);
free_dictionary(ban);
free_words(aux);
free_dictionary(aux);
free_swap(swp);
free_words(words);
free_dictionary(words);
free_words(prev1);
free_dictionary(prev1);
free_words(prev2);
free_dictionary(prev2);
free_words(prev3);
free_dictionary(prev3);
free_words(prev4);
free_dictionary(prev4);
free_words(prev5);
free_dictionary(prev5);
return NULL;
}
char *megahal_start(Function * global_funcs)
{
p_tcl_bind_list H_temp;
global = global_funcs;
Context;
module_register(MODULE_NAME, megahal_table, VER1, VER2);
if(!(irc_funcs = module_depend(MODULE_NAME, "irc", 1, 0)))
return "You need the irc module to use the megahal module.";
if(!(server_funcs = module_depend(MODULE_NAME, "server", 1, 0)))
return "You need the server module to use the megahal module.";
add_builtins(H_dcc, mega_dcc);
add_builtins(H_pubm, mega_pubm);
add_builtins(H_ctcp, mega_ctcp);
add_tcl_ints(my_tcl_ints);
add_tcl_coups(my_tcl_coups);
add_tcl_strings(my_tcl_strings);
add_tcl_commands(mytcls);
if((H_temp = find_bind_table("pub")))
add_builtins(H_temp, mega_pub);
words=new_dictionary();
prev1=new_dictionary();
prev2=new_dictionary();
prev3=new_dictionary();
prev4=new_dictionary();
prev5=new_dictionary();
/*
* Load the default personality.
*/
change_personality(&model, NULL, NULL);
putlog(LOG_MISC, "*", "MegaHAL v%s by z0rc loaded.", VER);
return NULL;
}
/* a report on the module status */
static void megahal_report(int idx, int details)
{
Context;
if(details) {
dprintf(idx, " by z0rc, Zev ^Baron^ Toledano and Jason Hutchens\n");
dprintf(idx, " words: %d, nodes: %d\n", model->forward->branch, (recurse_tree(model->backward) + recurse_tree(model->forward)));
dprintf(idx, " using %d bytes\n", megahal_expmem());
}
}
// Next, a hacked attempt at strdup(), since I can't use malloc() anywhere.
static wchar_t *mystrdup(const wchar_t *s)
{
wchar_t *mytmp = nmalloc((wcslen(s)+1)*sizeof(wchar_t));
Context;
if(mytmp == NULL)
return NULL;
else wcscpy(mytmp, s);
return mytmp;
}
static void mystrlwr(wchar_t *string)
{
size_t i;
Context;
for(i=0; i<wcslen(string); ++i)
string[i]=(wchar_t)towlower(string[i]);
}
// find pointer to sub inside s
static const wchar_t *mystrstr(const wchar_t *s, const wchar_t *sub)
{
Context;
if (!*sub)
return s;
for(; *s; ++s) {
if(*s == *sub) {
/*
* Matched starting char -- loop through remaining chars.
*/
const wchar_t *h, *n;
for(h = s, n = sub; *h && *n; ++h, ++n) {
if (*h != *n)
break;
}
if(!*n) /* matched all of 'sub' to null termination */
return s; /* return the start of the match */
}
}
return NULL;
}
static bool floodcheck()
{
Context;
if(!maxlines || !maxtime)
return TRUE;
if((now - curtime) > maxtime) {
curtime = now;
curlines = 0;
}
curlines++;
if(curlines > maxlines)
return FALSE;
return TRUE;
}
static char *istextinlist(char *text, char *list)
{
wchar_t *wtext, *wlist;
wchar_t *ch, *pbuf;
Context;
setlocale(LC_ALL, "");
wtext = locale_to_wchar(text);
wlist = locale_to_wchar(list);
wchar_t buf[wcslen(wlist)+1];
wcscpy(buf, wlist);
wcsncpy(glob_buffer, wtext, 512);
glob_buffer[512] = L'\0';
mystrlwr(buf);
mystrlwr(glob_buffer);
nfree(wtext);
nfree(wlist);
pbuf = buf;
while(wcslen(pbuf) > 0)
{
ch = mynewsplit(&pbuf);
if(!wcscmp(glob_buffer, ch))
return wchar_to_locale(glob_buffer);
}
return NULL;
}
static char *istextinlist2(STRING text, char *list)
{
wchar_t *ch, *pbuf, *wlist;
Context;
setlocale(LC_ALL, "");
wlist = locale_to_wchar(list);
wchar_t buf[wcslen(wlist)+1];
wcscpy(buf, wlist);
wcsncpy(glob_buffer, text.word, text.length);
glob_buffer[text.length] = L'\0'; // length = byte
mystrlwr(buf);
mystrlwr(glob_buffer);
nfree(wlist);
pbuf = buf;
while(wcslen(pbuf) > 0)
{
ch = mynewsplit(&pbuf);
if(!wcscmp(glob_buffer, ch))
return wchar_to_locale(glob_buffer);
}
return NULL;
}
static int countchans()
{
struct chanset_t *ch;
int c = 0;
Context;
for(ch = chanset; ch; ch = ch->next)
c++;
return c;
}
static int getchannum(char *chan)
{
struct chanset_t *ch;
int c = 0;
Context;
for(ch = chanset; ch; ch = ch->next)
{
if(!strcmp(chan, ch->dname))
break;
c++;
}
return c;
}
static void do_megahal(int idx, char *prefix, char *text, bool learnit, char *nick, char *chan)
{
char stuff[strlen(prefix) + 50], *lhalreply, *lmbotnick;
wchar_t *halreply, *wtext;
Context;
/* Is there anything to parse? */
if(!text[0]) {
sprintf(stuff, "%sSo tell me something already.\n", prefix);
dprintf(idx, stuff);
return;
}
setlocale(LC_ALL, "");
wtext = locale_to_wchar(text);
upper(wtext);
if(mystrstr(wtext, L"HTTP") != NULL) {
nfree(wtext);
return;
}
make_words(wtext, words);
Context;
if(learningmode && learnit)
learn(model, words);
halreply = generate_reply(model, words);
Context;
capitalize(halreply);
lhalreply = wchar_to_locale(halreply);
dprintf(idx, "%s%s\n", prefix, lhalreply);
lmbotnick = wchar_to_locale(mbotnick);
if(nick)
putlog(LOG_PUBLIC, chan, "<%s> %s, %s", lmbotnick, nick, lhalreply);
else if(chan)
putlog(LOG_PUBLIC, chan, "<%s> %s", lmbotnick, lhalreply);
nfree(lmbotnick);
nfree(lhalreply);
nfree(wtext);
}
static int pub_megahal(char *nick, char *host, char *hand, char *channel, char *text)
{
char prefix[strlen(channel) + strlen(nick) + 13];
struct chanset_t *chan = findchan(channel);
Context;
if(!floodcheck())
return 0;
if(istextinlist(channel, rexcludechans))
return 0;
if(chan != NULL) {
sprintf(prefix, "PRIVMSG %s :%s: ", channel, nick);
char *lmbotnick=wchar_to_locale(mbotnick);
putlog(LOG_PUBLIC, channel, "<%s> %s: %s", nick, lmbotnick, text);
nfree(lmbotnick);
do_megahal(DP_HELP, prefix, text, TRUE, nick, channel);
}
return 0;
}
static int pub_action(char *nick, char *host, char *hand, char *channel, char *key, char *text)
{
pub_megahal2(nick, host, hand, channel, text);
return 0;
}
static int pub_megahal2(char *nick, char *host, char *hand, char *channel, char *text)
{
// counters per channel for chatter/learning
static int *count = NULL, *learncount = NULL;
static int chancount = 0, learnchancount = 0;
char prefix[strlen(channel) + strlen(nick) + 13], *keyword = NULL;
wchar_t buffer[512] = L"";
wchar_t *wtext;
int i, pos;
struct chanset_t *chan = findchan(channel);
bool learnit = FALSE, flg = TRUE;
Context;
setlocale(LC_ALL, "");
wtext = locale_to_wchar(text);
wcscpy(buffer,wtext);
nfree(wtext);
mystrlwr(buffer);
if(mystrstr(buffer, L"http") != NULL) {
return 0;
}
// handle and respond to phrases with the botnick or keywords in it immediately and then exit
make_words(buffer, words); // dont make upper or it will mess things like mystrstr
if(words->size == 0) { // might have stripped all codes and returned empty
return 0;
}
if(words->size > 1) {
if((wordcmp2(words->entry[0], mbotnick)==0) && ((words->entry[1].word[1] == L':') || (words->entry[1].word[1] == L','))) { // let this be handled by pub_megahal otherwise we respond twice
return 0;
}
}
if((words->entry[0].word[0] == L'.') || (words->entry[0].word[0] == L'!')) { // pub command - ignore
return 0;
}
Context;
flg = (istextinlist(channel, rexcludechans)!=NULL); // dont respond/chat in channels that are excluded but learnfrequency is still enabled for now...
for (i=0; i<words->size; i++) // find whether one of the response keywords is in the text - find first only
if((keyword = istextinlist2(words->entry[i], responsekeywords)))
break;
if(chan != NULL && (mystrstr(buffer, mbotnick) || keyword) && !flg) { // either botnick or keyword said - respond immediately and exit
Context;
if(!floodcheck()) {
return 0;
}
if(!keyword)
keyword = wchar_to_locale(mbotnick);
// if keyword used in beginning or end of phrase, learn it
if(wordcmp2(words->entry[0], locale_to_wchar(keyword))==0 || wordcmp2(words->entry[(words->size)-2], locale_to_wchar(keyword))==0) { // -2 to exclude the period
learnit = TRUE;
sprintf(prefix, "PRIVMSG %s :%s: ", channel, nick);
} else {
sprintf(prefix, "PRIVMSG %s :%s, ", channel, nick);
}
// remove the botnick from the text
if(mystrstr(buffer, locale_to_wchar(keyword))) {
pos = (int)(mystrstr(buffer, locale_to_wchar(keyword)) - buffer);
for(i=pos; i<(wcslen(buffer)-wcslen(locale_to_wchar(keyword))); i++)
buffer[i] = buffer[i+wcslen(locale_to_wchar(keyword))];
buffer[i]=L'\0';
}
char *lbuffer=wchar_to_locale(buffer);
do_megahal(DP_HELP, prefix, lbuffer, learnit, nick, channel);
nfree(lbuffer);
return 0;
}
// Learn this phrase?
if(learningmode && learnfrequency>0) {
// initialize the count array - one int per chan (first time only)
Context;
if(countchans() && learncount == NULL) {
learncount = (int *)nmalloc(sizeof(int)*countchans());
for (i=0; i<countchans(); i++)
learncount[i] = 0;
learnchancount = countchans();
}
// if number of chans changed, realloc the array
if(countchans() && learnchancount != countchans()) {
learncount = (int *)nrealloc((int *)(learncount), sizeof(int)*countchans());
learnchancount = countchans();
}
// increment appropriate counter
if(learncount[getchannum(channel)] < learnfrequency) {
learncount[getchannum(channel)]++;
} else {
upper(buffer);
make_words(buffer, words);
if(words->size > (model->order)) { // only learn phrases with minimum amount of words
learn(model, words);
learncount[getchannum(channel)] = 0;
}
}
}
// From here, chatter stuff only
// check if chatter is turned off or if this chan is in the exclude list
Context;
if(istextinlist(channel, texcludechans) || talkfrequency == 0)
return 0;
// initialize the count array - one int per chan (first time only)
if(countchans() && count == NULL) {
count = (int *)nmalloc(sizeof(int)*countchans());
for (i=0; i<countchans(); i++)
count[i] = 0;
chancount = countchans();
}
// if number of chans changed, realloc the array
if(countchans() && chancount != countchans()) {
count = (int *)nrealloc((int *)(count), sizeof(int)*countchans());
chancount = countchans();
}
// increment appropriate counter
if(count[getchannum(channel)] < talkfrequency) {
count[getchannum(channel)]++;
return 0;
} else {
if (!floodcheck())
return 0;
count[getchannum(channel)] = 0;
}
if(chan != NULL) {
sprintf(prefix, "PRIVMSG %s :", channel);
do_megahal(DP_HELP, prefix, text, FALSE, NULL, channel);
}
if(keyword)
nfree(keyword);
return 0;
}
static int dcc_megahal(struct userrec *u, int idx, char *par)
{
Context;
if(!floodcheck())
return 0;
do_megahal(idx, "", par, TRUE, NULL, NULL);
return 0;
}
static int dcc_forget(struct userrec *u, int idx, char *text)
{
register int j;
int phrase;
bool fnd;
DICTIONARY *words;
wchar_t *output, *wtext;
Context;
setlocale(LC_ALL, "");
if(!text[0])
return 0;
words = new_dictionary();
wtext = locale_to_wchar(text);
phrase = find_phrase(wtext, &fnd);
if(fnd) {
words->size=model->phrase[phrase][0]-1;
if(realloc_dictionary(words)==NULL) {
error("dcc_forget", "Unable to reallocate dictionary");
return 0;
}
for(j=0; j<words->size; j++)
words->entry[j] = model->dictionary->entry[model->phrase[phrase][j+1]];
output = make_output(words);
capitalize(output);
char *loutput=wchar_to_locale(output);
dprintf(idx, "You mean \"%s\"? OK, I'll try...\n", loutput);
nfree(loutput);
del_all_phrases(phrase);
trimdictionary();
} else {
dprintf(idx, "There is no way that I am going to forget about that, sorry.\n");
}
nfree(wtext);
return 0;
}
static int pub_forget(char *nick, char *host, char *hand, char *channel, char *text)
{
register int j;
int phrase;
bool fnd;
DICTIONARY *words;
wchar_t *output, *wtext;
Context;
setlocale(LC_ALL, "");
putlog(LOG_MISC, "*", "forget %s by %s", text, hand);
if(!text[0])
return 0;
words = new_dictionary();
wtext = locale_to_wchar(text);
phrase = find_phrase(wtext, &fnd);
if(fnd) {
words->size=model->phrase[phrase][0]-1;
if(realloc_dictionary(words)==NULL) {
error("pub_forget", "Unable to reallocate dictionary");
return 0;
}
for(j=0; j<words->size; j++)
words->entry[j] = model->dictionary->entry[model->phrase[phrase][j+1]];
output = make_output(words);
capitalize(output);
char *loutput=wchar_to_locale(output);
dprintf(DP_HELP, "PRIVMSG %s :You mean \"%s\"? OK, I'll try...\n", channel, loutput);
nfree(loutput);
del_all_phrases(phrase);
trimdictionary();
} else {
dprintf(DP_HELP, "PRIVMSG %s :There is no way that I am going to forget about that, sorry.\n", channel);
}
nfree(wtext);
return 0;
}
// finds the closest matching phrase in the model to some text if (possible)
static int find_phrase(wchar_t *text, bool *found)
{
register int i, j, k;
int maxSize = 500;
BYTE2 symbols[maxSize];
BYTE2 symbol;
int size = 0, highmatch = 0, count = 0, phrase = 0;
bool flag = TRUE;
Context;
upper(text);
make_words(text, words);
if(words->size == 0)
return 0;
// create an array of unique symbols
// make sure the words exist in the main dictionary already and that they arent repeated