-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevilbot.py
executable file
·1624 lines (1462 loc) · 76.3 KB
/
evilbot.py
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/env python3
# -*- coding: UTF-8 -*-
"""
evilbot.py - a game-reporting and general services IRC bot for
EvilHack on the hardfought.org NetHack server.
Copyright (c) 2021 A. Thomson, K. Simpson
Based on original code from:
beholder.py - a game-reporting IRC bot for hardfought.org
Copyright (c) 2017 A. Thomson, K. Simpson
deathbot.py - a game-reporting IRC bot for AceHack
Copyright (c) 2011, Edoardo Spadolini
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from twisted.internet import reactor, protocol, ssl, task
from twisted.internet.protocol import Protocol, ReconnectingClientFactory
from twisted.words.protocols import irc
from twisted.python import filepath, log
from twisted.python.logfile import DailyLogFile
from twisted.application import internet, service
import site # to help find botconf
import base64 # for sasl login
import sys # for logging something4
import datetime # for timestamp stuff
import time # for !time
import ast # for conduct/achievement bitfields - not really used
import os # for check path exists (dumplogs), and chmod
import stat # for chmod mode bits
import re # for hello, and other things.
import urllib # for dealing with NH4 variants' #&$#@ spaces in filenames.
import shelve # for persistent !tell messages
import random # for !rng and friends
import glob # for matching in !whereis
site.addsitedir('.')
from evilbotconf import HOST, PORT, CHANNEL, NICK, USERNAME, REALNAME, BOTDIR
from evilbotconf import PWFILE, FILEROOT, WEBROOT, LOGROOT, PINOBOT, ADMIN
from evilbotconf import SERVERTAG
#try: from evilbotconf import LOGBASE
#except: LOGBASE = "/var/log/evilbot.log"
try: from botconf import LL_TURNCOUNTS
except: LL_TURNCOUNTS = {}
try: from evilbotconf import DCBRIDGE
except: DCBRIDGE = None
try: from evilbotconf import TEST
except: TEST = False
try:
from evilbotconf import REMOTES
except:
SLAVE = True #if we have no slaves, we (probably) are the slave
REMOTES = {}
try:
from evilbotconf import MASTERS
except:
SLAVE = False #if we have no master we (definitely) are the master
MASTERS = []
def fromtimestamp_int(s):
return datetime.datetime.fromtimestamp(int(s))
def timedelta_int(s):
return datetime.timedelta(seconds=int(s))
def isodate(s):
return datetime.datetime.strptime(s, "%Y%m%d").date()
def fixdump(s):
return s.replace("_",":")
xlogfile_parse = dict.fromkeys(
("points", "deathdnum", "deathlev", "maxlvl", "hp", "maxhp", "deaths",
"starttime", "curtime", "endtime", "user_seed",
"uid", "turns", "xplevel", "exp","depth","dnum","score","amulet", "lltype"), int)
xlogfile_parse.update(dict.fromkeys(
("conduct", "event", "carried", "flags", "achieve"), ast.literal_eval))
xlogfile_parse["realtime"] = timedelta_int
def parse_xlogfile_line(line, delim):
record = {}
for field in line.strip().decode(encoding='UTF-8', errors='ignore').split(delim):
key, _, value = field.partition("=")
if key in xlogfile_parse:
value = xlogfile_parse[key](value)
record[key] = value
return record
class DeathBotProtocol(irc.IRCClient):
nickname = NICK
username = USERNAME
realname = REALNAME
admin = ADMIN
slaves = {}
for r in REMOTES:
slaves[REMOTES[r][1]] = r
# if we're the master, include ourself on the slaves list
if not SLAVE:
slaves[NICK] = [WEBROOT,NICK,FILEROOT]
#...and the masters list
MASTERS += [NICK]
try:
password = open(PWFILE, "r").read().strip()
except:
password = "NotTHEPassword"
sourceURL = "https://github.com/k21971/EvilBot"
versionName = "evilbot.py"
versionNum = "0.1"
dump_url_prefix = WEBROOT + "userdata/{name[0]}/{name}/"
dump_file_prefix = FILEROOT + "dgldir/userdata/{name[0]}/{name}/"
if not SLAVE:
scoresURL = "https://nethackscoreboard.org/ascended.evil.html"
ttyrecURL = WEBROOT + "nethack/ttyrecs"
rceditURL = WEBROOT + "nethack/rcedit"
helpURL = WEBROOT + "nethack"
logday = time.strftime("%d")
chanLogName = LOGROOT + CHANNEL + time.strftime("-%Y-%m-%d.log")
chanLog = open(chanLogName,'a')
os.chmod(chanLogName,stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH)
xlogfiles = {filepath.FilePath(FILEROOT+"evilhack-0.9.0/var/xlogfile"): ("evil", "\t", "evilhack/dumplog/{starttime}.evil.html")}
livelogs = {filepath.FilePath(FILEROOT+"evilhack-0.9.0/var/livelog"): ("evil", "\t")}
# Forward events to other bots at the request of maintainers of other variant-specific channels
forwards = {"evil" : []}
# for displaying variants and server tags in colour
displaystring = {"evil" : "\x0304evil\x03",
"hdf-us" : "\x1D\x0304hdf-us\x03\x0F",
"hdf-au" : "\x1D\x0303hdf-au\x03\x0F",
"hdf-eu" : "\x1D\x0312hdf-eu\x03\x0F"}
# put the displaystring for a thing in square brackets
def displaytag(self, thing):
return '[' + self.displaystring.get(thing,thing) + ']'
# for !who or !players or whatever we end up calling it
# Reduce the repetitive crap
DGLD=FILEROOT+"dgldir/"
INPR=DGLD+"inprogress-"
inprog = { "evil" : [INPR+"evil040/", INPR+"evil041/",
INPR+"evil042/", INPR+"evil050/",
INPR+"evil060/", INPR+"evil070/",
INPR+"evil071/", INPR+"evil080/",
INPR+"evil081/", INPR+"evil082/",
INPR+"evil083/", INPR+"evil084/",
INPR+"evil090/"]}
# for !whereis
whereis = {"evil": [FILEROOT+"evilhack-0.4.0/var/whereis/",
FILEROOT+"evilhack-0.4.1/var/whereis/",
FILEROOT+"evilhack-0.4.2/var/whereis/",
FILEROOT+"evilhack-0.5.0/var/whereis/",
FILEROOT+"evilhack-0.6.0/var/whereis/",
FILEROOT+"evilhack-0.7.0/var/whereis/",
FILEROOT+"evilhack-0.7.1/var/whereis/",
FILEROOT+"evilhack-0.8.0/var/whereis/",
FILEROOT+"evilhack-0.8.1/var/whereis/",
FILEROOT+"evilhack-0.8.2/var/whereis/",
FILEROOT+"evilhack-0.8.3/var/whereis/",
FILEROOT+"evilhack-0.8.4/var/whereis/",
FILEROOT+"evilhack-0.9.0/var/whereis/"]}
dungeons = {"evil": ["The Dungeons of Doom","Gehennom","The Gnomish Mines","Goblin Town",
"The Quest","Sokoban","Fort Ludios","The Ice Queen's Realm","The Hidden Dungeon",
"Vecna's Domain","Vlad's Tower","Purgatory","The Wizards Tower",
"The Elemental Planes"]}
# variant related stuff that does not relate to xlogfile processing
rolename = {
"arc": "archeologist",
"bar": "barbarian",
"cav": "caveman",
"hea": "healer",
"kni": "knight",
"mon": "monk",
"pri": "priest",
"ran": "ranger",
"rog": "rogue",
"sam": "samurai",
"tou": "tourist",
"val": "valkyrie",
"wiz": "wizard",
"con": "convict",
"inf": "infidel",
"dru": "druid"
}
racename = {
"dwa": "dwarf",
"elf": "elf",
"gno": "gnome",
"hum": "human",
"orc": "orc",
"gia": "giant",
"cen": "centaur",
"hob": "hobbit",
"ill": "illithid",
"trt": "tortle",
"dro": "drow",
"dra": "draugr"
}
# save typing these out in multiple places
evil_roles = ["arc","bar","cav","hea","kni","mon","pri",
"ran","rog","sam","tou","val","wiz","con",
"inf", "dru"]
evil_races = ["dwa","elf","gno","hum","orc","gia","cen",
"hob","ill","trt","dro","dra"]
# varname: ([aliases],[roles],[races])
# first alias will be used for !variant
# note this breaks if a player has the same name as an alias
# so don't do that (I'm looking at you, FIQ)
variants = {"evil": (["evilhack", "evil", "evl"],
evil_roles, evil_races)}
# variants which support streaks - now tracking slex streaks, because that's totally possible.
streakvars = ["evil"]
# for !asc statistics - assume these are the same for all variants, or at least the sane ones.
aligns = ["Law", "Neu", "Cha", "Una"]
genders = ["Mal", "Fem"]
#who is making tea? - bots of the nethack community who have influenced this project.
brethren = ["Rodney", "Athame", "Arsinoe", "Izchak", "TheresaMayBot", "FCCBot", "Pinobot", "Announcy", "demogorgon", "the /dev/null/oracle", "NotTheOracle\\dnt", "Croesus", "Beholder", "Yendor"]
looping_calls = None
# SASL auth nonsense required if we run on AWS
# copied from https://github.com/habnabit/txsocksx/blob/master/examples/tor-irc.py
# irc_CAP and irc_9xx are UNDOCUMENTED.
def connectionMade(self):
self.sendLine('CAP REQ :sasl')
#self.deferred = Deferred()
irc.IRCClient.connectionMade(self)
def irc_CAP(self, prefix, params):
if params[1] != 'ACK' or params[2].split() != ['sasl']:
print('sasl not available')
self.quit('')
sasl_string = '{0}\0{0}\0{1}'.format(self.nickname, self.password)
sasl_b64_bytes = base64.b64encode(sasl_string.encode(encoding='UTF-8',errors='strict'))
self.sendLine('AUTHENTICATE PLAIN')
self.sendLine('AUTHENTICATE ' + sasl_b64_bytes.decode('UTF-8'))
def irc_903(self, prefix, params):
self.sendLine('CAP END')
def irc_904(self, prefix, params):
print('sasl auth failed', params)
self.quit('')
irc_905 = irc_904
def signedOn(self):
self.factory.resetDelay()
self.startHeartbeat()
self.sendLine('MODE {} -R'.format(self.nickname))
if not SLAVE: self.join(CHANNEL)
random.seed()
self.logs = {}
for xlogfile, (variant, delim, dumpfmt) in self.xlogfiles.items():
self.logs[xlogfile] = (self.xlogfileReport, variant, delim, dumpfmt)
for livelog, (variant, delim) in self.livelogs.items():
self.logs[livelog] = (self.livelogReport, variant, delim, "")
self.logs_seek = {}
self.looping_calls = {}
#lastgame shite
self.lastgame = "No last game recorded"
self.lg = {}
self.lastasc = "No last ascension recorded"
self.la = {}
# for populating lg/la per player at boot, we need to track game end times
# variant and variant:player don't need this if we assume the xlogfiles are
# ordered within variant.
self.lge = {}
self.tlastgame = 0
self.lae = {}
self.tlastasc = 0
# streaks
self.curstreak = {}
self.longstreak = {}
for v in self.streakvars:
# curstreak[var][player] = (start, end, length)
self.curstreak[v] = {}
# longstreak - as above
self.longstreak[v] = {}
# ascensions (for !asc)
# "!asc plr var" will give something like Rodney's output.
# "!asc plr" will give breakdown by variant.
# "!asc" or "!asc var" will be as above, assuming requestor's nick.
# asc[var][player][role] = count;
# asc[var][player][race] = count;
# asc[var][player][align] = count;
# asc[var][player][gender] = count;
# assumes 3-char abbreviations for role/race/align/gender, and no overlaps.
# for asc ratio we need total games too
# allgames[var][player] = count;
self.asc = {}
self.allgames = {}
for v in self.variants.keys():
self.asc[v] = {};
self.allgames[v] = {};
# for !tell
try:
self.tellbuf = shelve.open(BOTDIR + "/tellmsg.db", writeback=True)
except:
self.tellbuf = shelve.open(BOTDIR + "/tellmsg", writeback=True, protocol=2)
# for !setmintc
try:
self.plr_tc = shelve.open(BOTDIR + "/plrtc.db", writeback=True)
except:
self.plr_tc = shelve.open(BOTDIR + "/plrtc", writeback=True, protocol=2)
# Commands must be lowercase here.
self.commands = {"ping" : self.doPing,
"time" : self.doTime,
"pom" : self.doPom,
"porn" : self.doPom, #for Elronnd
"hello" : self.doHello,
"beer" : self.doBeer,
"tea" : self.doTea,
"coffee" : self.doTea,
"whiskey" : self.doTea,
"whisky" : self.doTea,
"vodka" : self.doTea,
"rum" : self.doTea,
"tequila" : self.doTea,
"scotch" : self.doTea,
"booze" : self.doTea,
"potion" : self.doTea,
"goat" : self.doGoat,
"lotg" : self.doLotg,
"rng" : self.doRng,
"role" : self.doRole,
"race" : self.doRace,
"variant" : self.doVariant,
"tell" : self.takeMessage,
"source" : self.doSource,
"lastgame" : self.multiServerCmd,
"lastasc" : self.multiServerCmd,
"scores" : self.doScoreboard,
"sb" : self.doScoreboard,
"ttyrec" : self.doTtyrec,
"rcedit" : self.doRCedit,
"commands" : self.doCommands,
"help" : self.doHelp,
"coltest" : self.doColTest,
"players" : self.multiServerCmd,
"who" : self.multiServerCmd,
"asc" : self.multiServerCmd,
"streak" : self.multiServerCmd,
"whereis" : self.multiServerCmd,
"8ball" : self.do8ball,
"setmintc" : self.multiServerCmd,
# these ones are for control messages between master and slaves
# sender is checked, so these can't be used by the public
"#q#" : self.doQuery,
"#r#" : self.doResponse}
# commands executed based on contents of #Q# message
self.qCommands = {"players" : self.getPlayers,
"who" : self.getPlayers,
"whereis" : self.getWhereIs,
"asc" : self.getAsc,
"streak" : self.getStreak,
"lastasc" : self.getLastAsc,
"lastgame": self.getLastGame,
"setmintc": self.setPlrTC}
# callbacks to run when all slaves have responded
self.callBacks = {"players" : self.outPlayers,
"who" : self.outPlayers,
"whereis" : self.outWhereIs,
"asc" : self.outAscStreak,
"streak" : self.outAscStreak,
# TODO: timestamp these so we can report the very last one
# For now, use the !asc/!streak callback as it's generic enough
"lastasc" : self.outAscStreak,
"lastgame": self.outAscStreak,
"setmintc": self.outPlrTC}
# checkUsage outputs a message and returns false if input is bad
# returns true if input is ok
self.checkUsage ={"whereis" : self.usageWhereIs,
"asc" : self.usageAsc,
"streak" : self.usageStreak,
#"lastgame": self.usageLastGame,
#"lastasc" : self.usageLastAsc,
"setmintc": self.usagePlrTC}
# seek to end of livelogs
for filepath in self.livelogs:
with filepath.open("r") as handle:
handle.seek(0, 2)
self.logs_seek[filepath] = handle.tell()
# sequentially read xlogfiles from beginning to pre-populate lastgame data.
for filepath in self.xlogfiles:
with filepath.open("r") as handle:
for line in handle.readlines():
delim = self.logs[filepath][2]
game = parse_xlogfile_line(line, delim)
game["variant"] = self.logs[filepath][1]
if game["variant"] == "fh":
game["dumplog"] = fixdump(game["dumplog"])
if game["variant"] == "nh4":
game["dumplog"] = fixdump(game["dumplog"])
game["dumpfmt"] = self.logs[filepath][3]
for line in self.logs[filepath][0](game,False):
pass
self.logs_seek[filepath] = handle.tell()
# poll logs for updates every 3 seconds
for filepath in self.logs:
self.looping_calls[filepath] = task.LoopingCall(self.logReport, filepath)
self.looping_calls[filepath].start(3)
# Additionally, keep an eye on our nick to make sure it's right.
# Perhaps we only need to set this up if the nick was originally
# in use when we signed on, but a 30-second looping call won't kill us
self.looping_calls["nick"] = task.LoopingCall(self.nickCheck)
self.looping_calls["nick"].start(30)
def nickCheck(self):
# also rejoin the channel here, in case we drop off for any reason
if not SLAVE: self.join(CHANNEL)
if (self.nickname != NICK):
self.setNick(NICK)
def nickChanged(self, nn):
# catch successful changing of nick from above and identify with nickserv
self.msg("NickServ", "identify " + nn + " " + self.password)
#helper functions
#lookup canonical variant id from alias
def varalias(self,alias):
alias = alias.lower()
if alias in self.variants.keys(): return alias
for v in self.variants.keys():
if alias in self.variants[v][0]: return v
# return original (lowercase) if not found.
# this is used for variant/player agnosticism in !lastgame
return alias
def logRotate(self):
self.chanLog.close()
self.logday = time.strftime("%d")
self.chanLogName = LOGROOT + CHANNEL + time.strftime("-%Y-%m-%d.log")
self.chanLog = open(self.chanLogName,'a') # 'w' is probably fine here
os.chmod(self.chanLogName,stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH)
def stripText(self, msg):
# strip the colour control stuff out
# This can probably all be done with a single RE but I have a headache.
message = re.sub(r'\x03\d\d,\d\d', '', msg) # fg,bg pair
message = re.sub(r'\x03\d\d', '', message) # fg only
message = re.sub(r'[\x1D\x03\x0f]', '', message) # end of colour and italics
return message
# Write log
def log(self, message):
if SLAVE: return
message = self.stripText(message)
if time.strftime("%d") != self.logday: self.logRotate()
self.chanLog.write(time.strftime("%H:%M ") + message + "\n")
self.chanLog.flush()
# wrapper for "msg" that logs if msg dest is channel
# Need to log our own actions separately as they don't trigger events
def msgLog(self, replyto, message):
if replyto == CHANNEL:
self.log("<" + self.nickname + "> " + message)
self.msg(replyto, message)
# Similar wrapper for describe
def describeLog(self,replyto, message):
if replyto == CHANNEL:
self.log("* " + self.nickname + " " + message)
self.describe(replyto, message)
# construct and send response.
# replyto is channel, or private nick
# sender is original sender of query
def respond(self, replyto, sender, message):
if (replyto.lower() == sender.lower()): #private
self.msg(replyto, message)
else: #channel - prepend "Nick: " to message
self.msgLog(replyto, sender + ": " + message)
# Query/Response handling
def doQuery(self, sender, replyto, msgwords):
# called when slave gets queried by master.
# msgwords is [ #Q#, <query_id>, <orig_sender>, <command>, ... ]
if (sender in MASTERS) and (msgwords[3] in self.qCommands):
# sender is passed to master; msgwords[2] is passed tp sender
self.qCommands[msgwords[3]](sender,msgwords[2],msgwords[1],msgwords[3:])
else:
print("Bogus slave query from " + sender + ": " + " ".join(msgwords));
def doResponse(self, sender, replyto, msgwords):
# called when slave returns query response to master
# msgwords is [ #R#, <query_id>, [server-tag], command output, ...]
if sender in self.slaves and msgwords[1] in self.queries:
self.queries[msgwords[1]]["resp"][sender] = " ".join(msgwords[2:])
if set(self.queries[msgwords[1]]["resp"].keys()) >= set(self.slaves.keys()):
#all slaves have responded
self.queries[msgwords[1]]["callback"](self.queries.pop(msgwords[1]))
else:
print("Bogus slave response from " + sender + ": " + " ".join(msgwords));
def timeoutQuery(self, query):
if query not in self.queries: return # query was completed before timeout
# probably should handle the 'no slaves responded' case better than this.
self.queries[query]["callback"](self.queries.pop(query))
# implement commands here
def doPing(self, sender, replyto, msgwords):
self.respond(replyto, sender, "Pong! " + " ".join(msgwords[1:]))
def doTime(self, sender, replyto, msgwords):
self.respond(replyto, sender, time.strftime("%c %Z"))
def doSource(self, sender, replyto, msgwords):
self.respond(replyto, sender, self.sourceURL )
def doScoreboard(self, sender, replyto, msgwords):
self.respond(replyto, sender, self.scoresURL )
def doTtyrec(self, sender, replyto, msgwords):
self.respond(replyto, sender, self.ttyrecURL )
def doRCedit(self, sender, replyto, msgwords):
self.respond(replyto, sender, self.rceditURL )
def doHelp(self, sender, replyto, msgwords):
self.respond(replyto, sender, self.helpURL )
def doColTest(self, sender, replyto, msgwords):
code = chr(3)
code += msgwords[1]
self.respond(replyto, sender, msgwords[1] + " " + code + "TEST!" )
def doCommands(self, sender, replyto, msgwords):
self.respond(replyto, sender, "available commands are !help !ping !time !pom !hello !booze !beer !potion !tea !coffee !whiskey !vodka !rum !tequila !scotch !goat !lotg !d(1-1000) !(1-50)d(1-1000) !8ball !rng !role !race !variant !tell !source !lastgame !lastasc !asc !streak !rcedit !scores !sb !setmintc !whereis !players !who !commands")
def getPom(self, dt):
# this is a direct translation of the NetHack method of working out pom.
# I'm SURE there's easier ways to do this, but they may not give perfectly
# consistent results with nh.
# Note that timetuple gives diy 1..366, C/Perl libs give 0..365,
# so need to adjust in final calculation.
(year,m,d,H,M,S,diw,diy,ds) = dt.timetuple()
goldn = (year % 19) + 1
epact = (11 * goldn + 18) % 30
if ((epact == 25 and goldn > 11) or epact == 24):
epact += 1
return ((((((diy-1 + epact) * 6) + 11) % 177) // 22) & 7)
def doPom(self, sender, replyto, msgwords):
# only info we have is that this yields 0..7, with 0 = new, 4 = full.
# the rest is assumption.
mp = ["new", "waxing crescent", "at first quarter", "waxing gibbous",
"full", "waning gibbous", "at last quarter", "waning crescent"]
dt = datetime.datetime.now()
nowphase = self.getPom(dt)
resp = "The moon is " + mp[nowphase]
aday = datetime.timedelta(days=1)
if nowphase in [0, 4]:
daysleft = 1 # counting today
dt += aday
while self.getPom(dt) == nowphase:
daysleft += 1
dt += aday
days = "days."
if daysleft == 1: days = "day."
resp += " for " + str(daysleft) + " more " + days
else:
daysuntil = 1 # again, we are counting today
dt += aday
while (self.getPom(dt)) not in [0, 4]:
daysuntil += 1
dt += aday
days = " days."
if daysuntil == 1: days = " day."
resp += "; " + mp[self.getPom(dt)] + " moon in " + str(daysuntil) + days
self.respond(replyto, sender, resp)
def doHello(self, sender, replyto, msgwords = 0):
self.msgLog(replyto, "Hello " + sender + ", Welcome to " + CHANNEL)
#def doRip(self, sender, replyto, msgwords = 0):
# self.msg(replyto, "rip")
def doLotg(self, sender, replyto, msgwords):
if len(msgwords) > 1: target = " ".join(msgwords[1:])
else: target = sender
self.msgLog(replyto, "May the Luck of the Grasshopper be with you always, " + target + "!")
def doGoat(self, sender, replyto, msgwords):
act = random.choice(['kicks', 'rams', 'headbutts'])
part = random.choice(['arse', 'nose', 'face', 'kneecap'])
if len(msgwords) > 1:
self.msgLog(replyto, sender + "'s goat runs up and " + act + " " + " ".join(msgwords[1:]) + " in the " + part + "! Baaaaaa!")
else:
self.msgLog(replyto, NICK + "'s goat runs up and " + act + " " + sender + " in the " + part + "! Baaaaaa!")
def doRng(self, sender, replyto, msgwords):
if len(msgwords) == 1:
if (sender[0:11].lower()) == "grasshopper": # always troll the grasshopper
self.msgLog(replyto, "The RNG only has eyes for you, " + sender)
elif random.randrange(20): # 95% of the time, print usage
self.respond(replyto, sender, "!rng thomas richard harold ; !rng do dishes|play nethack ; !rng 1-100")
elif not random.randrange(5): #otherwise, trololol
self.respond(replyto, sender, "How doth the RNG hate thee? Let me count the ways...")
else:
self.respond(replyto, sender, "The RNG " + random.choice(["hates you.",
"is thinking of Grasshopper <3",
"hates everyone (except you-know-who)",
"cares not for your whining.",
"is feeling generous (maybe).",
"doesn't care.",
"is indifferent to your plight."]))
return
multiword = [i.strip() for i in " ".join(msgwords[1:]).split('|')]
if len(multiword) > 1:
self.respond(replyto, sender, random.choice(multiword))
return
if len(msgwords) == 2:
rngrange = msgwords[1].split('-')
try:
self.respond(replyto, sender, str(random.randrange(int(rngrange[0]), int(rngrange[-1])+1)))
except ValueError:
try: # maybe some smart arse reversed the values
self.respond(replyto, sender, str(random.randrange(int(rngrange[-1]), int(rngrange[0])+1)))
except ValueError:
# Nonsense input. Recurse with no args for usage message.
self.doRng(sender, replyto, [msgwords[0]])
else:
self.respond(replyto, sender, random.choice(msgwords[1:]))
def rollDice(self, sender, replyto, msgwords):
if re.match(r'^\d*d$', msgwords[0]): # !d, !4d is rubbish input.
self.respond(replyto, sender, "No dice!")
return
dice = msgwords[0].split('d')
if dice[0] == "": dice[0] = "1" #d6 -> 1d6
(d0,d1) = (int(dice[0]),int(dice[1]))
if d0 > 50:
self.respond(replyto, sender, "Sorry, I don't have that many dice.")
return
if d1 > 1000:
self.respond(replyto, sender, "Those dice are too big!")
return
(s, tot) = (None, 0)
for i in range(0,d0):
d = random.randrange(1,d1+1)
if s: s += " + " + str(d)
else: s = str(d)
tot += d
if "+" in s: s += " = " + str(tot)
else: s = str(tot)
self.respond(replyto, sender, s)
def doRole(self, sender, replyto, msgwords):
if len(msgwords) > 1:
v = self.varalias(msgwords[1])
#error if variant not found
if not self.variants.get(v,False):
self.respond(replyto, sender, "EvilHack is the only variant option.")
return
self.respond(replyto, sender, self.rolename[random.choice(self.variants[v][1])])
else:
#pick variant first
v = random.choice(list(self.variants.keys()))
self.respond(replyto, sender, self.variants[v][0][0] + " " + self.rolename[random.choice(self.variants[v][1])])
def doRace(self, sender, replyto, msgwords):
if len(msgwords) > 1:
v = self.varalias(msgwords[1])
#error if variant not found
if not self.variants.get(v,False):
self.respond(replyto, sender, "EvilHack is the only variant option.")
self.respond(replyto, sender, self.racename[random.choice(self.variants[v][2])])
else:
v = random.choice(list(self.variants.keys()))
self.respond(replyto, sender, self.variants[v][0][0] + " " + self.racename[random.choice(self.variants[v][2])])
def doVariant(self, sender, replyto, msgwords):
self.respond(replyto, sender, self.variants[random.choice(list(self.variants.keys()))][0][0])
def doBeer(self, sender, replyto, msgwords):
self.respond(replyto, sender, random.choice(["It's your shout!", "I thought you'd never ask!",
"Burrrrp!", "We're not here to f#%k spiders, mate!",
"One Darwin stubby, coming up!"]))
def do8ball(self, sender, replyto, msgwords):
self.respond(replyto, sender, random.choice(["\x1DIt is certain\x0F", "\x1DIt is decidedly so\x0F", "\x1DWithout a doubt\x0F", "\x1DYes definitely\x0F", "\x1DYou may rely on it\x0F",
"\x1DAs I see it, yes\x0F", "\x1DMost likely\x0F", "\x1DOutlook good\x0F", "\x1DYes\x0F", "\x1DSigns point to yes\x0F", "\x1DReply hazy try again\x0F",
"\x1DAsk again later\x0F", "\x1DBetter not tell you now\x0F", "\x1DCannot predict now\x0F", "\x1DConcentrate and ask again\x0F",
"\x1DDon't count on it\x0F", "\x1DMy reply is no\x0F", "\x1DMy sources say no\x0F", "\x1DOutlook not so good\x0F", "\x1DVery doubtful\x0F"]))
# The following started as !tea resulting in the bot making a cup of tea.
# Now it does other stuff.
bev = { "serves": ["delivers", "tosses", "passes", "pours", "hands", "throws"],
# Attempt to make a sensible choice of vessel.
# pick from "all", and check against specific drink. Loop a few times for a match, then give up.
"vessel": {"all" : ["cup", "mug", "shot", "tall glass", "tumbler", "glass", "schooner", "pint", "fifth", "vial", "potion", "barrel", "droplet", "bucket", "esky"],
"tea" : ["cup", "mug", "saucer"],
"potion": ["potion", "vial", "droplet"],
"booze" : ["shot", "tall glass", "tumbler", "glass", "schooner", "pint", "fifth", "barrel", "flask"],
"coffee": ["cup", "mug"],
"vodka" : ["shot", "tall glass", "tumbler", "glass"],
"whiskey":["shot", "tall glass", "tumbler", "glass", "flask"],
"rum" : ["shot", "tall glass", "tumbler", "glass"],
"tequila":["shot", "tall glass", "tumbler", "glass"],
"scotch": ["shot", "tall glass", "tumbler", "glass", "flask"]
# others omitted - anything goes for them
},
"drink" : {"tea" : ["black", "white", "green", "polka-dot", "Earl Grey", "oolong", "darjeeling"],
"potion": ["water", "fruit juice", "see invisible", "sickness", "confusion", "extra healing", "hallucination", "healing", "holy water", "unholy water", "restore ability", "sleeping", "blindness", "gain energy", "invisibility", "monster detection", "object detection", "booze", "enlightenment", "full healing", "levitation", "polymorph", "speed", "acid", "oil", "gain ability", "gain level", "paralysis"],
"booze" : ["booze", "the hooch", "moonshine", "the sauce", "grog", "suds", "the hard stuff", "liquid courage", "grappa"],
"coffee": ["coffee", "espresso", "cafe latte", "Blend 43"],
"vodka" : ["Stolichnaya", "Absolut", "Grey Goose", "Ketel One", "Belvedere", "Luksusowa", "SKYY", "Finlandia", "Smirnoff"],
"whiskey":["Irish", "Jack Daniels", "Evan Williams", "Crown Royal", "Crown Royal Reserve", "Johnnie Walker Black", "Johnnie Walker Red", "Johnnie Walker Blue"],
"rum" : ["Bundy", "Jamaican", "white", "dark", "spiced", "pirate"],
"fictional": ["Romulan ale", "Blood wine", "Kanar", "Pan Galactic Gargle Blaster", "jynnan tonyx", "gee-N'N-T'N-ix", "jinond-o-nicks", "chinanto/mnigs", "tzjin-anthony-ks", "Moloko Plus", "Duff beer", "Panther Pilsner beer", "Screaming Viking", "Blue milk", "Fizzy Bubblech", "Butterbeer", "Ent-draught", "Nectar of the Gods", "Frobscottle"],
"tequila":["blanco", "oro", "reposado", "añejo", "extra añejo", "Patron Silver", "Jose Cuervo 1800"],
"scotch": ["single malt", "single grain", "blended malt", "blended grain", "blended", "Glenfiddich", "Glenlivet", "Dalwhinnie"],
"junk" : ["blended kale", "pickle juice", "poorly-distilled rocket fuel", "caustic gas", "liquid smoke", "protein shake", "wheatgrass nonsense", "olive oil", "saline solution", "napalm", "synovial fluid", "drool"]},
"prepared":["brewed", "distilled", "fermented", "decanted", "prayed over", "replicated", "conjured", "acquired", "brewed", "excreted"],
"degrees" :{"Kelvin": [0, 500], "degrees Celsius": [-20,95], "degrees Fahrenheit": [-20,200]}, #sane-ish ranges
"suppress": ["coffee", "junk", "booze", "potion", "fictional"] } # do not append these to the random description
def doTea(self, sender, replyto, msgwords):
if len(msgwords) > 1: target = msgwords[1]
else: target = sender
drink = random.choice([msgwords[0]] * 50 + list(self.bev["drink"].keys()))
for vchoice in range(10):
vessel = random.choice(self.bev["vessel"]["all"])
if drink not in self.bev["vessel"].keys(): break # anything goes for these
if vessel in self.bev["vessel"][drink]: break # match!
fulldrink = random.choice(self.bev["drink"][drink])
if drink not in self.bev["suppress"]: fulldrink += " " + drink
tempunit = random.choice(list(self.bev["degrees"].keys()))
[tmin,tmax] = self.bev["degrees"][tempunit]
temp = random.randrange(tmin,tmax)
self.describeLog(replyto, random.choice(self.bev["serves"]) + " " + target
+ " a " + vessel
+ " of " + fulldrink
+ ", " + random.choice(self.bev["prepared"])
+ " by " + random.choice(self.brethren)
+ " at " + str(temp)
+ " " + tempunit + ".")
def takeMessage(self, sender, replyto, msgwords):
if len(msgwords) < 3:
self.respond(replyto, sender, "!tell <recipient> <message> (leave a message for someone)")
return
willDo = [ "Will do, {0}!",
"I'm on it, {0}.",
"No worries, {0}, I've got this!",
"{1} shall be duly informed at the first opportunity, {0}." ]
rcpt = msgwords[1].split(":")[0] # remove any trailing colon - could check for other things here.
message = " ".join(msgwords[2:])
if (replyto == sender): #this was a privmsg
forwardto = rcpt # so we pass a privmsg
# and mark it so rcpt knows it was sent privately
message = "[private] " + message
else: # !tell on channel
forwardto = replyto # so pass to channel
if not self.tellbuf.get(rcpt.lower(),False):
self.tellbuf[rcpt.lower()] = []
self.tellbuf[rcpt.lower()].append((forwardto,sender,time.time(),message))
self.tellbuf.sync()
self.msgLog(replyto,random.choice(willDo).format(sender,rcpt))
def msgTime(self, stamp):
# Timezone handling is not great, but the following seems to work.
# assuming TZ has not changed between leaving & taking the message.
return datetime.datetime.fromtimestamp(stamp).strftime("%Y-%m-%d %H:%M") + time.strftime(" %Z")
def checkMessages(self, user):
# this runs every time someone speaks on the channel,
# so return quickly if there's nothing to do
# but first... deal with the "bonus" colours and leading @ symbols of discord users
if user[0] == '@':
plainuser = self.stripText(user).lower()
if not self.tellbuf.get(plainuser,None):
plainuser = plainuser[1:] # strip the leading @ and try again (below)
else:
plainuser = user.lower()
if not self.tellbuf.get(plainuser,None): return
nicksfrom = []
if len(self.tellbuf[plainuser]) > 2 and user[0] != '@':
for (forwardto,sender,ts,message) in self.tellbuf[plainuser]:
if forwardto.lower() != user.lower(): # don't add sender to list if message was private
if sender not in nicksfrom: nicksfrom += [sender]
self.respond(user,user, "Message from " + sender + " at " + self.msgTime(ts) + ": " + message)
# "tom" "tom and dick" "tom, dick, and harry"
fromstr = ""
for (i,n) in enumerate(nicksfrom):
# first item
if (i == 0):
fromstr = n
# last item
elif (i == len(nicksfrom)-1):
if (i > 1): fromstr += "," # oxford comma :P
fromstr += " and " + n
# middle items
else:
fromstr += ", " + n
if fromstr: # don't say anything if all messages were private
self.respond(CHANNEL, user, "Messages from " + fromstr + " have been forwarded to you privately.");
else:
for (forwardto,sender,ts,message) in self.tellbuf[plainuser]:
self.respond(forwardto, user, "Message from " + sender + " at " + self.msgTime(ts) + ": " + message)
del self.tellbuf[plainuser]
self.tellbuf.sync()
QUERY_ID = 0 # just use a sequence number for now
def newQueryId(self):
self.QUERY_ID += 1
return str(self.QUERY_ID)
queries = {}
def forwardQuery(self,sender,replyto,msgwords,callback):
# [Here]
# Store a query reference locally, indexed by a unique identifier
# Store a callback function for when everyone responds to the query.
# forward the query tagged with the ID to the slaves.
# [elsewhere]
# record query responses, and call callback when all received (or timeout)
# This all becomes easier if we just treat ourself (master) as one of the slaves
q = self.newQueryId()
self.queries[q] = {}
self.queries[q]["callback"] = callback
self.queries[q]["replyto"] = replyto
self.queries[q]["sender"] = sender
self.queries[q]["resp"] = {}
message = "#Q# " + " ".join([q,sender] + msgwords)
for sl in self.slaves.keys():
print("forwardQuery: " + sl)
self.msg(sl,message)
# set up the timeout in 5 seconds.
reactor.callLater(5, self.timeoutQuery, q)
# Multi-server command entry point (forwards query to slaves)
def multiServerCmd(self, sender, replyto, msgwords):
if msgwords[0] in self.checkUsage:
if not self.checkUsage[msgwords[0]](sender, replyto, msgwords):
return
if self.slaves:
self.forwardQuery(sender, replyto, msgwords, self.callBacks.get(msgwords[0],None))
# !players - respond to forwarded query and actually pull the info
def getPlayers(self, master, sender, query, msgwords):
plrvar = ""
for var in self.inprog.keys():
for inpdir in self.inprog[var]:
for inpfile in glob.iglob(inpdir + "*.ttyrec"):
# /stuff/crap/PLAYER:shit:garbage.ttyrec
# we want AFTER last '/', BEFORE 1st ':'
plrvar += inpfile.split("/")[-1].split(":")[0] + " " + self.displaytag(var) + " "
if len(plrvar) == 0:
plrvar = "No current players"
response = "#R# " + query + " " + self.displaytag(SERVERTAG) + " " + plrvar
self.msg(master, response)
# !players callback. Actually print the output.
def outPlayers(self,q):
outmsg = " :: ".join(q["resp"].values())
self.respond(q["replyto"],q["sender"],outmsg)
def usageWhereIs(self, sender, replyto, msgwords):
if (len(msgwords) != 2):
self.respond(replyto, sender, "!" + msgwords[0] + " <player> - finds a player in the dungeon." + replytag)
return False
return True
def getWhereIs(self, master, sender, query, msgwords):
ammy = ["", " (with Amulet)"]
# look for inrpogress file first, only report active games
for var in self.inprog.keys():
for inpdir in self.inprog[var]:
for inpfile in glob.iglob(inpdir + "*.ttyrec"):
plr = inpfile.split("/")[-1].split(":")[0]
if plr.lower() == msgwords[1].lower():
for widir in self.whereis[var]:
for wipath in glob.iglob(widir + "*.whereis"):
if wipath.split("/")[-1].lower() == (msgwords[1] + ".whereis").lower():
plr = wipath.split("/")[-1].split(".")[0] # Correct case
wirec = parse_xlogfile_line(open(wipath, "rb").read(),":")
self.msg(master, "#R# " + query
+ " " + self.displaytag(SERVERTAG) + " " + plr
+ " "+self.displaytag(var)
+ ": ({role} {race} {gender} {align}) T:{turns} ".format(**wirec)
+ self.dungeons[var][wirec["dnum"]]
+ " level: " + str(wirec["depth"])
+ ammy[wirec["amulet"]])
return
self.msg(master, "#R# " + query + " "
+ self.displaytag(SERVERTAG)
+ " " + plr + " "
+ self.displaytag(var)
+ ": No details available")
return
self.msg(master, "#R# " + query + " " + self.displaytag(SERVERTAG)
+ " " + msgwords[1]
+ " is not currently playing on this server.")
def outWhereIs(self,q):
player = ''
msgs = []
for server in q["resp"]:
if " is not currently playing" in q["resp"][server]:
player = q["resp"][server].split(" ")[1]
else:
msgs += [q["resp"][server]]
outmsg = " :: ".join(msgs)
if not outmsg: outmsg = player + " is not playing."
self.respond(q["replyto"],q["sender"],outmsg)
def plrVar(self, sender, replyto, msgwords):
# for !streak and !asc, work out what player and variant they want
if len(msgwords) > 3:
# !streak tom dick harry
if not SLAVE: self.respond(replyto,sender,"Usage: !" +msgwords[0] +" [variant] [player]")
return(None, None)
if len(msgwords) == 3:
vp = self.varalias(msgwords[1])
pv = self.varalias(msgwords[2])
if vp in self.variants.keys():
# !streak dnh Tangles
return (msgwords[2], vp)
if pv in self.variants.keys():
# !streak K2 UnNethHack
return (msgwords[1],pv)
# !streak bogus garbage
if not SLAVE: self.respond(replyto,sender,"Usage: !" +msgwords[0] +" [variant] [player]")
return (None, None)
if len(msgwords) == 2:
vp = self.varalias(msgwords[1])
if vp in self.variants.keys():
# !streak Grunthack
return (sender, vp)
# !streak Grasshopper
return (msgwords[1],None)
#!streak ...player is self, no variant
return(sender, None)
def usageAsc(self, sender, replyto, msgwords):
if self.plrVar(sender, replyto, msgwords)[0]:
return True
return False
def getAsc(self, master, sender, query, msgwords):
(PLR, var) = self.plrVar(sender, "", msgwords)
if not PLR: return # bogus input, should have been handled in usage check above
plr = PLR.lower()
stats = ""
totasc = 0