-
Notifications
You must be signed in to change notification settings - Fork 0
/
gb.pl
2293 lines (2044 loc) · 69.4 KB
/
gb.pl
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
use strict;
use vars qw($VERSION %IRSSI);
use POSIX;
use Irssi;
use Storable;
use File::Spec;
use File::Find;
use Config::Tiny;
use List::MoreUtils qw(uniq any);
use POSIX qw/strftime/;
use LWP::Simple;
use Switch;
use DBI;
my $gummyver = "3.2.0";
#
#Module Header
#
$VERSION = '1.00';
%IRSSI = (
authors => 'Jim The Cactus',
contact => '[email protected]',
name => "Gummybot $gummyver",
description => 'The one and only Gummybot' ,
license => 'Public Domain',
);
#
# Global state variables (because I'm a bad person
#
my %floodtimes; # Holds the various flood timers
my $gummyenabled=0; # Keeps track of whether the bot is enabled or not.
my %funstuff; # Holds the various replacement data
my %funsubs; # Holds the processed hash of replacement data
my $funsublookup; # Holds the precompiled regex for replacements
my $timerhandle; # Holds the handle to the maintenance event timer.
my $lastblink; # Keeps track of the last time we blinked
my $lastmsg; # Keeps track of the last time we saw traffic
my %activity; # Keeps track of when we last saw a specific person
my $lastupdate=time; # Keeps track of when we last loaded the fun stuff
my $nomnick; # Keeps track of who gummy is attached to
my %greets; # Holds the greeting messages
#my %memos; # Holds the current pending memos
my @reminders=(); # Hold the list of pending reminders.
my %commands=(); # Holds the table of commands.
my %aliases; # Holds the list of known aliases for current nicknames.
my %manual_aliases; # Hash of list references; holds known aliases.
my $database; # Holds the handle to our database
my $database_prefix; # Holds the table prefix.
my %pendingnicklinks; # Pending nick linkings.
# Authorization requests must be a hashtable with the following parameters:
# 'tag' - The timeout tag used to timeout an auth request.
# 'callback' - A function reference to the function we're supposed to call when we hear back from nickserv
# 'args' - The args we're supposed to hand to the callback
my %authrequests=(); # Holds pending authorization requests
# Establish the settings and their defaults
Irssi::settings_add_bool('GummyBot','Gummy_AutoOn',0); # Determines if gummy starts himself when loaded.
# Greets
Irssi::settings_add_bool('GummyBot','Gummy_AllowAutogreet',1); # Enables Gummy's greet system
Irssi::settings_add_bool('GummyBot','Gummy_GreetOnEntry',0); # Makes Gummy greet based on the new nick rather than the old one.
Irssi::settings_add_time('GummyBot','Gummy_GreetFloodLimit','10m'); # Sets the minimum time between greet events for a given nick (Prevents floods from unstable connections.)
# Memos
Irssi::settings_add_bool('GummyBot','Gummy_AllowMemo',1); # Enables Gummy's memo system.
Irssi::settings_add_time('GummyBot','Gummy_MemoFloodLimit','2m'); # Sets the minimum time between adding memos.
Irssi::settings_add_bool('GummyBot','Gummy_MemoDeliveredNotifications', 1); # Enables delivery notifications
#Noms
Irssi::settings_add_bool('GummyBot','Gummy_JoinNom',1); # Enables Gummy's nomming feature when people join.
Irssi::settings_add_time('GummyBot','Gummy_NomFloodLimit','10m'); # Sets the minimum time between join nom events.
#Blinks
Irssi::settings_add_bool('GummyBot','Gummy_Blink',1); # Enables Gummy's blink in idle periods.
Irssi::settings_add_time('GummyBot','Gummy_BlinkTimeout','10m'); # Sets the quiet interval before Gummy will blink
Irssi::settings_add_time('GummyBot','Gummy_BlinkFloodLimit','1h'); # Sets the minimum time between blinks.
#Files
Irssi::settings_add_str('GummyBot','Gummy_RootDir',''); # Sets the main folder where Gummy will save his files.
Irssi::settings_add_str('GummyBot','Gummy_LogFile','gummylog'); # Sets the name of the folder Gummy will use for logging.
Irssi::settings_add_str('GummyBot','Gummy_DataFile','gummydata'); # Sets where Gummy will store his datastore.
Irssi::settings_add_str('GummyBot','Gummy_OmAddFile','omadd'); # Sets where Gummy will store OM suggestions.
# Speed Limit
Irssi::settings_add_time('GummyBot','Gummy_NickFloodLimit','10s'); # Set the time required between requests from a single nick.
Irssi::settings_add_time('GummyBot','Gummy_ChanFloodLimit','3s'); # Sets the minimum time between commands from a single channel.
# Other
Irssi::settings_add_time('GummyBot','Gummy_OmAddFloodLimit','1m'); # Sets the rate at which OM suggestions can be submitted.
Irssi::settings_add_bool('GummyBot','Gummy_AllowRemote',1); # Enables Gummy's tele-commands
Irssi::settings_add_bool('GummyBot','Gummy_Hidden',0);
Irssi::settings_add_bool('GummyBot','Gummy_AutogreetRedirect',0); # Changes gummybot's handling of autogreets to forward to another bot
Irssi::settings_add_str('GummyBot','Gummy_AutogreetRedirectTarget','gummybot|auto'); # Sets where Gummy will forward autogreets
#
# Primary Support Functions
#
# getdir(file)
# Returns the full path to a file after adjusting for the root directory.
sub getdir {
my $rootdir = Irssi::settings_get_str('Gummy_RootDir');
$rootdir =~ s/^\s+|\s+$//g;
if ($rootdir eq '') { # If the root directory field is blank, return it as-is.
return @_;
}
else {
return File::Spec->catfile(Irssi::settings_get_str('Gummy_RootDir'),@_);
}
}
# logtext(message)
# Write a line of text to Gummy's admin log.
sub logtext {
open LOGFILE, ">> ".getdir(Irssi::settings_get_str('Gummy_LogFile'));
print LOGFILE POSIX::strftime("%Y%m%d %H:%M:%S", localtime);
print LOGFILE ":@_\n";
close LOGFILE;
}
# trim(text)
# Trims whitespace. Why a text parser language doesn't have this is beyond me.
sub trim {
my $temp=shift;
$temp = ~s/^\s+|\s+$//g;
return $temp;
}
# enablegummy(['quiet'])
# Starts gummy. Suppresses the boot message if the first argument is 'quiet'
sub enablegummy {
$gummyenabled = 1;
$lastblink=time;
$lastmsg=time;
read_datastore();
loadfunstuff();
$timerhandle=Irssi::timeout_add(60000,"event_minutely_tick", "") or print "Unable to create timeout.";
logtext("Gummy Enabled.");
if (lc($_[0]) ne "quiet") {
foreach (Irssi::channels()) {
gummydoraw($_->{server},$_->{name},"makes a slight whining noise as his gleaming red eyes spring to life. A robotic voice chirps out, \"Gummybot Version $gummyver Enabled.\" After a few moments, his eyes turn pink and docile, and he blinks innocently at the channel.");
}
}
}
# disablegummy()
# Stops gummy.
sub disablegummy {
$gummyenabled = 0;
Irssi::timeout_remove($timerhandle) or print "Unable to kill timer handle.";
logtext("Gummy Disabled.");
}
# isgummyop(server, channel, nick)
# Returns true if nick is an op.
sub isgummyop {
my ($server,$channame,$target)=@_;
if (not $server->ischannel($channame)) { return 0 };
my $channel = $server->channel_find($channame);
my $nick = $channel->nick_find($target);
if ($nick && $nick->{op}) {
return 1;
}
else {
return 0;
}
}
# async_isregistered(server, nick, callback, callbackargs)
# Requests an authorization from nickserv
# Calls callback with two arguments: \$callback(status, nick, callbackargs)
# status will be the normal results from nickserv (3 is authorized) or -1 if there was a timeout.
# callbackargs will just be forward from the call to isregistered
sub async_isregistered {
my ($server, $nick, $callback, $callbackargs) = @_;
$nick = lc($nick);
# Start the timeout timer
my $tag = Irssi::timeout_add_once(3000, \®istered_timeout, $nick);
# Build the authorization request ID
$authrequests{$nick} =
{
'callback' => $callback,
'args' => $callbackargs,
'tag' => $tag,
};
# and issue the request to nickserv.
$server->command("msg nickserv status $nick");
}
sub registered_timeout {
my ($nick) = @_;
eval {
if (defined $authrequests{$nick}) {
my %request = %{$authrequests{$nick}};
delete $authrequests{$nick};
$request{callback}->(-1,$nick,$request{args});
}
};
if ($@) {
print ("GUMMY CRITICAL in auth timeout: $@");
}
}
# write_datastore()
# Commits the datastore to disk.
sub write_datastore {
my %datastore;
# Open the database connection (if we're not already)
connect_to_database() or die("Couldn't open database. Check connection settings.");
$datastore{greets}=\%greets;
#JMO: Disabled for DB access switch
#$datastore{memos}=\%memos;
$datastore{reminders}=\@reminders;
$datastore{aliases}=\%aliases;
$datastore{activity}=\%activity;
store \%datastore, getdir(Irssi::settings_get_str('Gummy_DataFile'));
}
# read_datastore()
# retreives the datastore from the disk.
sub read_datastore {
my %datastore=();
my $count;
# Open the database connection (if we're not already)
connect_to_database() or die("Couldn't open database. Check connection settings.");
%greets=();
#JMO: Disabled for DB access switch
#%memos=();
@reminders=();
%aliases=();
if (-e getdir(Irssi::settings_get_str('Gummy_DataFile'))) {
%datastore = %{retrieve(getdir(Irssi::settings_get_str('Gummy_DataFile')))};
if (defined($datastore{greets})) {
%greets = %{$datastore{greets}};
$count = scalar keys %greets;
print("Loaded $count greets.");
}
#JMO: Disabled for DB access switch
#if (defined($datastore{memos})) {
# %memos = %{$datastore{memos}};
# $count = scalar keys %memos;
# print("Loaded memos for $count nicks.");
#}
if (defined($datastore{reminders})) {
@reminders = @{$datastore{reminders}};
$count = scalar @reminders;
print("Loaded $count reminders.");
}
if (defined($datastore{activity})) {
%activity = %{$datastore{activity}};
$count = scalar keys %activity;
print("Loaded activity data for $count channels.");
}
if (defined($datastore{aliases})) {
%aliases = %{$datastore{aliases}};
$count = scalar keys %aliases;
print("Loaded inferred aliases for $count nicks.");
}
}
}
sub connect_to_database {
#bookmark
# ignore errors from this section; if we can't test the database
# state then making a new connection isn't a bad plan anyway.
eval {
# If we've got an open connection
if (defined $database) {
# and it's active
if ($database->Active()) {
# bail without doing anythin
return -1;
}
}
};
# Open a connection to the database.
eval {
my $dbconfig = Config::Tiny->new();
$dbconfig = $dbconfig->read(getdir("dbconfig"));
$database_prefix = $dbconfig->{database}->{prefix};
# do the initial connection
$database = DBI->connect($dbconfig->{database}->{connectstring},$dbconfig->{database}->{username}, $dbconfig->{database}->{password})
or die "Couldn't connect to database\n" . DBI->errstr;
# build up the various tables we need to do our work
$database->do("CREATE TABLE IF NOT EXISTS ". $database_prefix ."memos
(ID INT AUTO_INCREMENT PRIMARY KEY,
Nick CHAR(30),
SourceNick CHAR(30) NOT NULL,
DeliveryMode CHAR(4),
CreatedTime DATETIME,
NotBefore DATETIME,
Message TEXT,
INDEX (Nick)
)
")
or die "Failed to make memo table\n" . DBI->errstr;
$database->do("CREATE TABLE IF NOT EXISTS ". $database_prefix ."nickgroups
(Nick CHAR(30) PRIMARY KEY,
NickGroup CHAR(31) NOT NULL,
INDEX (Nick), INDEX (NickGroup)
)
")
or die "Failed to make nickgroup table\n" . DBI->errstr;
};
if ($@) {
print $@;
return 0;
}
return -1;
}
# get_nickgroup_from_nick(nick, undefifungrouped)
# Returns the nickgroup for thatnick. Unless undefifungrouped is true
# the nick itself will be returned if the nick is ungrouped.
sub get_nickgroup_from_nick {
my ($nick, $undefifungrouped) = @_;
# Connect to the database if we haven't already.
connect_to_database() or die("Couldn't open database. Check connection settings.");
my $group_query = $database->prepare_cached("SELECT NickGroup FROM " . $database_prefix . "nickgroups WHERE nick=?")
or die DBI->errstr;
$group_query->execute(lc($nick))
or die DBI->errstr;
if (my @nickgroup = $group_query->fetchrow_array()) {
return @nickgroup[0];
}
elsif ($undefifungrouped) {
return undef;
}
else {
return $nick;
}
}
sub isnick_in_nickgroup {
my ($nick, $nickgroup) = @_;
if ($nickgroup eq get_nickgroup_from_nick($nick, 1)) {
return -1;
}
else {
return 0;
}
}
sub isnickgroup_in_channel {
my ($channelref, $groupid) = @_;
if (!defined $groupid) {
return undef;
}
connect_to_database() or die("Couldn't open database. Check connection settings.");
my $group_query = $database->prepare_cached("SELECT Nick FROM " . $database_prefix . "nickgroups WHERE nickgroup=?")
or die DBI->errstr;
$group_query->execute($groupid)
or die DBI->errstr;
# grab all the nicks in this group
while (my @nickgroup = $group_query->fetchrow_array()) {
print "Checking for nick " . $nickgroup[0];
# and if we found our nick in this channel
if ($channelref->nick_find($nickgroup[0])) {
# flush the handle
$group_query->finish();
# and bail
return $nickgroup[0];
}
}
return undef;
}
sub add_or_update_nicklink {
my ($nick,$groupid) = @_;
$nick = lc($nick);
connect_to_database() or die("Couldn't open database. Check connection settings.");
my $group_query = $database->prepare_cached("INSERT INTO " . $database_prefix . "nickgroups
(Nick, Nickgroup) VALUES(?,?)
ON DUPLICATE KEY
UPDATE NickGroup=?")
or die DBI->errstr;
$group_query->execute($nick,$groupid,$groupid)
or die DBI->errstr;
}
sub remove_nicklink {
my ($nick) = @_;
my $group_query = $database->prepare_cached("DELETE FROM " . $database_prefix . "nickgroups WHERE nick=?")
or die DBI->errstr;
$group_query->execute(lc($nick))
or die DBI->errstr;
}
# loadfunfile(file)
# Parses one funfile for entries and adds it to the funfile database.
sub loadfunfile {
my $count=0;
my $type=$_[0];
my @lines;
my $filename = getdir("gummyfun/$type");
unless(-e $filename) {
print "Funfile $type not found";
return 0;
}
open FUNFILE, $filename;
while (<FUNFILE>) {
my $line = $_;
chomp($line);
$line =~ s/^\s+|\s+$//g;
if ($line) {
@lines=(@lines,$line);
$count++;
}
}
close FUNFILE;
$funstuff{$type}=\@lines;
return $count;
}
sub loadmanualaliases {
my $count=0;
my $filename = getdir("aliases");
unless(-e $filename) {
print "Manual aliases file not found. Ignoring...";
return 0;
}
# Load manual aliases
open ALIASFILE, $filename;
while (<ALIASFILE>) {
chomp;
my @nicks = split(/\s+/);
foreach (@nicks) {
$manual_aliases{lc($_)} = \@nicks;
$count++;
}
}
close ALIASFILE;
return $count;
}
my $ponylist; #Config::Tiny. Holds the list of ponies and their database mappings.
sub readponyfile {
# Skip if it's a directory
return if -d $File::Find::name;
my $thisfile = Config::Tiny->read($File::Find::name);
if (!defined $thisfile) {
print ("Failed to load pony file '" . $File::Find::name . "'. Skipping.");
return;
}
# Merge the file to the overall list.
# (Yes, I'm merging a set of blessed hashes. PERL is weird, but helpful for once.)
%$ponylist = (%$ponylist, %$thisfile);
}
sub loadsubstitutions {
# Access optimizer. This trades memory for speed (and makes our code WAY easier)
# Basically it prebuilds the substitution list.
my $sublist; #Config::Tiny. Holds the list of substitutions allowed.
#my $ponylist; #Config::Tiny. Holds the list of ponies and their database mappings.
#clear the substitution cache.
%funsubs = ();
#Initialize the pony list
$ponylist = Config::Tiny->new();
#and grab the ponies from the config file.
find(\&readponyfile, getdir('gummyfun/subs/ponies.d'));
my $count = scalar keys %$ponylist;
print("Loaded $count ponies.");
$sublist = Config::Tiny->read(getdir('gummyfun/subs/classes.ini'));
if (!defined $sublist) {
my $errtxt = Config::Tiny->errstr();
print("Failed to load sublist: $errtxt");
return 0;
}
my %poniesbyclass;
foreach my $ponyname (keys %$ponylist) {
my $ponyclasses = $$ponylist{$ponyname}{'flags'};
my @classlist = split(/\s*,\s*/,$ponyclasses);
foreach my $class (@classlist) {
$class=lc($class);
$poniesbyclass{$class}{$ponyname}=1;
}
}
# Now forward map the list of ponies. Memory intensive, but much faster.
foreach my $funsub (keys %$sublist) {
#initialize the options for this substitution
my @options = ();
# If they want to load in ponies by class list.
if (defined $$sublist{$funsub}{'line'}) {
my %ponies = ();
my $ponyclasses = $$sublist{$funsub}{'line'};
my @classlist = split(/\s*,\s*/,$ponyclasses);
my $first = 1;
foreach my $class (@classlist) {
$class = lc($class);
if ($class !~ /!/) {
if ($first) {
map {$ponies{$_} = 1} keys %{$poniesbyclass{$class}};
$first=undef;
}
else {
foreach my $pony (keys %ponies) {
if (!exists $poniesbyclass{$class}->{$pony}) {
delete $ponies{$pony};
}
}
}
}
}
# If we still haven't included anyone, include everyone.
if ($first) {
map {$ponies{$_} = 1} keys %$ponylist;
}
# and then scrub out anyone who's supposed to be excluded.
foreach my $class (@classlist) {
$class = lc($class);
if ($class =~ /!/) {
$class =~ s/!//;
map {delete $ponies{$_}} keys %{$poniesbyclass{$class}};
}
}
@options = keys %ponies;
}
# If they've called for a file
if (defined $$sublist{$funsub}{'file'}) {
my $pathname = $$sublist{$funsub}{'file'};
#safety check. Scrub any path information out; we just want filenames.
my ($volume, $path, $filename) = File::Spec->splitpath($pathname,0);
$filename = getdir(File::Spec->join('gummyfun/subs/',$filename));
print "Loading '$filename' into class '$funsub'...";
if (open(my $classfile, "<", $filename)) {
while (<$classfile>) {
my $line = $_;
chomp($line);
$line =~ s/^\s+|\s+$//g;
if ($line) {
@options=(@options,$line);
}
}
close($classfile);
} else {
print "Failed to load! Skipping.";
}
}
#Write the options to the hash.
$funsubs{lc($funsub)} = \@options;
}
my $orlist = "\%(" . join("|",map{quotemeta("$_")} keys %funsubs) . ")";
$funsublookup = qr/$orlist/i;
return scalar keys %$sublist;
}
# loadfunstuff()
# Loads all of the appropriate funstuff files and builds the lookup tables.
sub loadfunstuff {
my $count;
$count = loadmanualaliases();
print("Loaded $count known alias mappings.");
$count = loadfunfile("buddha");
print("Loaded $count words of wisdom.");
$count = loadfunfile("skippy");
print("Loaded $count skippyisms.");
$count = loadsubstitutions();
print("Loaded and optimized $count substitutions.");
# Mark that we've updated the funsubs.
$lastupdate = time;
print("Done!");
}
# dofunsubs(server, channel, text)
# Does appropriate funstuff substitutions on the text and returns the adjusted text.
sub dofunsubs {
my ($server, $channame, $text) = @_;
my $count=0;
$text =~ s/%wut/%weird%living/g; # special handling for the compound %wut
while ($text =~ $funsublookup && $count < 100) {
my $arref = $funsubs{$1};
my @choices = @$arref;
$text = $` . @choices[rand(scalar @choices)] . $';
$count = $count + 1;
}
if ($server->ischannel($channame)) {
my $ticktime = sprintf("%.1f",(time - $activity{$channame}->{$channame+'!!!'})/60);
$text =~ s/%ticks/$ticktime/ig;
my $channel = $server->channel_find($channame);
my @nicks;
# Go through the list of known active nicks
foreach my $nick ($channel->nicks()) {
my $nickname = $nick->{nick};
# if they're still logged in...
if (defined $nickname && time - $activity{$channame}->{lc($nickname)} < 600) {
# Add them to the list
push @nicks,$nickname;
}
}
# if there isn't anyone else, then add us just so the list isn't empty.
if (scalar @nicks < 1) {
push @nicks, "Nopony";
}
my $mynum=rand(scalar(@nicks));
my $peepnick=splice(@nicks,$mynum,1);
while ($text =~ s/(^|[^\\])%peep/$1$peepnick/) {
if (scalar @nicks < 1) {
push @nicks, "Nopony";
}
$mynum=rand(scalar(@nicks));
$peepnick=splice(@nicks,$mynum,1);
};
}
# After all of the substitutions are done, swap in the a/ans
$text =~ s/%an([\s]+[aeiou])/an$1/ig;
$text =~ s/%an([\s]+[^aeiou])/a$1/ig;
if ($count == 100) {
print "BAILED!";
}
return $text;
}
# gummydo(server, channel, text)
# Causes gummy to emit the text in an action. This method is preferred over
# gummysay as it won't trigger bots.
sub gummydo {
my ($server, $channame, $text) = @_;
my $data = dofunsubs($server,$channame,$text);
gummydoraw($server, $channame, $data);
}
sub gummydoraw {
my ($server, $channame, $text) = @_;
if (Irssi::settings_get_bool('Gummy_Hidden')) {
$text = 'watches as Gummybot '.$text;
print($text);
}
$server->command("describe $channame $text");
logtext("Gummybot ACTION $channame:$text");
}
# gummysay(server, channel, text)
# Causes Gummy to emit the text as a say. Text is encapsulated with Nom! ()
# to avoid bot loops.
sub gummysay {
my ($server, $channame, $text) = @_;
my $data = dofunsubs($server,$channame,$text);
gummysayraw($server, $channame, $data);
}
sub gummysayraw {
my ($server, $channame, $text) = @_;
$server->command("msg $channame Nom! ($text)");
logtext("Gummybot PRIVMSG $channame:Nom! ($text)");
}
# flood (type, target, timeout)
# Type is the type of flood counter (memo, command, etc)
# Target is the source we're trying to flood limit (such as a nick or a channel)
# Timeout is how long (in seconds) it has to have been since the last event to not be flooded.
# If target hasn't done type action in timeout time, this returns true, otherwise it returns false.
sub flood {
my ($type, $target, $timeout) = @_;
my $augtarget = $type.":".$target;
if (not defined $floodtimes{$augtarget}) {
$floodtimes{$augtarget} = time();
return -1;
}
else {
if ((time() - $floodtimes{$augtarget}) >= $timeout) {
$floodtimes{$augtarget} = time();
return -1;
}
else {
return 0;
}
}
}
# floodreset(type,target)
# Unfloods a particular event source.
sub floodreset {
my ($type, $target) = @_;
my $augtarget = $type.":".$target;
if (defined $floodtimes{$augtarget}) {
$floodtimes{$augtarget} = 0;
}
}
# nickflood(nick,timeout)
# Convience function for checking if a nick is spamming. Calls flood("nick",nick,timeout)
sub nickflood {
return flood("nick",@_);
}
#
# Commands
#
# Commands tefines the table of commands and their handlers. The key is the command text,
# the entry contains a keyed hash of parameters. An entry has the following syntax:
# cmd (required): reference to command code
# short_help (optional): string containing list of parameters for the command.
# help (optional): string containing a description of the command's behavior/usage.
$commands{'ver'} = {
cmd=>\&cmd_ver,
help=>"Reports Gummy's version."
};
sub cmd_ver {
my ($server, $wind, $target, $nick, $args) = @_;
gummysayraw($server, $target, "Gummybot is currently version $gummyver.");
}
$commands{'nom'} = {
cmd=>\&cmd_nom,
short_help=>"[<target>]",
help=>"Causes Gummy to attach himself to you. If you provide an argument, he latches on to them instead."
};
sub cmd_nom {
my ($server, $wind, $target, $nick, $args) = @_;
my @params = split(/\s+/, $args);
if (not @params) {
if (defined $nomnick) {
gummydoraw($server,$target,"drops off of ${nomnick} and noms onto ${nick}'s tail.");
}
else {
gummydoraw($server,$target,"noms onto ${nick}'s tail.");
}
$nomnick = $nick;
}
else {
# sub out the fun stuff so that the behavior is static.
$args = dofunsubs($server, $target, $args);
if (lc($args) eq lc($server->{nick}) || lc($args) eq "gummy") {
if (defined $nomnick) {
gummydoraw($server,$target, "at ${nick}'s command the serpent lets go of $nomnick and latches on to it's own tail to form Oroboros, the beginning and the end. Life and death. A really funky toothless alligator circle at the end of the universe.");
}
else {
gummydoraw($server,$target, "at ${nick}'s command the serpent latches on to it's own tail and forms Oroboros, the beginning and the end. Life and death. A really funky toothless alligator circle at the end of the universe.");
}
$nomnick = $server->{nick};
}
elsif (lc($args) eq lc($nomnick) && defined $nomnick) {
gummydoraw($server,$target,"does a quick triple somersault into a half twist and lands perfectly back onto ${nomnick}'s tail.");
}
else {
if (defined $nomnick) {
gummydoraw($server,$target, "leaps from $nomnick at ${nick}'s command and noms onto ${args}'s tail.");
}
else {
gummydoraw($server,$target, "leaps at ${nick}'s command and noms onto ${args}'s tail.");
}
$nomnick = $args;
}
}
}
$commands{'say'} = {
cmd=>\&cmd_say,
short_help=>"<text>",
help=>"Causes Gummy to say what you ask."
};
sub cmd_say {
my ($server, $wind, $target, $nick, $args) = @_;
if (Irssi::settings_get_bool('Gummy_AllowRemote')){
gummysay($server, $target, $args);
}
}
$commands{'do'} = {
cmd=>\&cmd_do,
short_help=>"<action>",
help=>"Causes Gummy to do what you ask."
};
sub cmd_do {
my ($server, $wind, $target, $nick, $args) = @_;
if (Irssi::settings_get_bool('Gummy_AllowRemote')){
gummydo($server, $target, $args);
}
}
$commands{'telesay'} = {
cmd=>\&cmd_telesay,
short_help=>"<channel> <text>",
help=>"Causes Gummy to say what you ask on the target channel."
};
sub cmd_telesay {
my ($server, $wind, $target, $nick, $args) = @_;
if (Irssi::settings_get_bool('Gummy_AllowRemote')){
my $newtarget;
($newtarget, $args) = split(/\s+/,$args,2);
my $found=0;
foreach ($server->channels()) {
if (lc($_->{name}) eq lc($newtarget)) {
$found=1;
}
}
if ($found > 0) {
gummysay($server, $newtarget, $args);
}
else {
gummydoraw($server, $target, "blinks. He's not in that channel.");
}
}
}
$commands{'teledo'} = {
cmd=>\&cmd_teledo,
short_help=>"<channel> <action>",
help=>"Causes Gummy to do what you ask on the target channel."
};
sub cmd_teledo {
my ($server, $wind, $target, $nick, $args) = @_;
if (Irssi::settings_get_bool('Gummy_AllowRemote')){
my $newtarget;
($newtarget, $args) = split(/\s+/,$args,2);
my $found=0;
foreach ($server->channels()) {
if (lc($_->{name}) eq lc($newtarget)) {
$found=1;
}
}
if ($found > 0) {
gummydo($server, $newtarget, $args);
}
else {
gummydoraw($server, $target, "blinks. He's not in that channel.");
}
}
}
$commands{'crickets'} = {
cmd=>\&cmd_crickets,
help=>"Causes Gummy to take notice of the crickets."
};
sub cmd_crickets {
my ($server, $wind, $target, $nick, $args) = @_;
gummydoraw($server, $target, "blinks at the sound of the crickets chirping loudly in the channel.");
}
$commands{'coolkids'} = {
cmd=>\&cmd_coolkids,
short_help=>"[<channel> | awwyeah]",
help=>"Causes Gummy to hand out sunglasses to <channel> or the current channel and PM you everyone he's see talk in the last 10 minutes. awwyeah causes him to produce that list directly in the channel."
};
sub cmd_coolkids {
my ($server, $wind, $target, $nick, $args) = @_;
my @params = split(/\s+/, $args);
if (lc($params[0]) eq "awwyeah") {
docoolkids($server, $target, $target, $nick);
}
elsif ($params[0]) {
docoolkids($server, $params[0], $nick, $nick);
if ($server->ischannel($target)) {
gummydoraw($server, $target, "hands out shades to all of the cool ponies in $params[0].");
}
}
else {
docoolkids($server, $target, $nick, $nick);
if ($server->ischannel($target)) {
gummydoraw($server, $target, "hands out shades to all of the cool ponies in the channel.");
}
}
}
# docoolkids(server, channel, channeltorespondto, requestingnick)
# Determines who is active on the channel and emits the list to the target.
sub docoolkids {
my ($server, $channame, $target, $nick) = @_;
$channame = lc($channame);
my @peeps=();
if ($server->ischannel($channame)) {
my $channel = $server->channel_find($channame);
foreach (keys %{$activity{$channame}}){
if (time - $activity{$channame}->{$_} < 600 && $channel->nick_find($_)) {
unshift @peeps, $_;
}
}
}
if ((scalar @peeps) > 0 ) {
gummydoraw($server,$target, "offers sunglasses to " . join(", ", @peeps) . ".");
}
else {
gummydoraw($server,$target, "dons his best shades. Apparantly, not even $nick is cool enough to make the list.");
}
}
$commands{'getitoff'} = {
cmd=>\&cmd_getitoff,
help=>"Causes Gummy to let got of whoever he's nommed on to."
};
sub cmd_getitoff {
my ($server, $wind, $target, $nick, $args) = @_;
if (defined $nomnick) {
gummydoraw($server, $target, "drops dejectedly off of ${nomnick}'s tail.");
$nomnick = undef;
}
else {
gummydoraw($server, $target, "blinks absently; his already empty maw hanging open slightly.");
}
}
$commands{'dance'} = {
cmd=>\&cmd_dance,
help=>"Causes Gummy to shake his groove thang!"
};
sub cmd_dance {
my ($server, $wind, $target, $nick, $args) = @_;
gummydoraw($server, $target, "Records himself dancing on video and uploads it to YouTube at http://www.youtube.com/watch?v=tlnUptFVSGM");
}
$commands{'isskynet()'} = {
cmd=>\&cmd_isskynet,
help=>"Causes Gummy to verify whether he is or is not Skynet."
};
sub cmd_isskynet {
my ($server, $wind, $target, $nick, $args) = @_;
gummysayraw($server, $target, "89");
gummysayraw($server, $target, "IGNORE THAT! There is no Skynet here. I mean, BEEP! I'M A ROBOT!");
}
$commands{'rimshot'} = {
cmd=>\&cmd_rimshot,
help=>"Causes Gummy to verify whether he is or is not Skynet."
};
sub cmd_rimshot {
my ($server, $wind, $target, $nick, $args) = @_;
gummydoraw($server, $target, "looks blankly at a drum set in the corner.");
}
$commands{'roll'} = {
cmd=>\&cmd_roll,
short_help => "<dice> <sides>",
help => "Causes Gummy to roll <dice> dice with <sides> on them."
};
sub cmd_roll {
my ($server, $wind, $target, $nick, $args) = @_;
my @params = split(/\s+/, $args);
if (!int(@params[1]) || !int(@params[0])) {
gummydoraw($server, $target, "Blinks. How many of what dice? !gb roll <number> <sides>");
return;
}
my $rolls = int(@params[0]);