forked from NHTangles/beholder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtnntbot.py
executable file
·1655 lines (1483 loc) · 71.9 KB
/
tnntbot.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/python
# -*- coding: UTF-8 -*-
"""
*** THIS IS THE TNNT BOT ***
tnntbot.py - a game-reporting and general services IRC bot for
The November Nethack Tournament
Copyright (c) 2018 A. Thomson, K. Simpson
Based loosely on original code from:
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
from datetime import datetime, timedelta
import site # to help find botconf
import base64
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.request, urllib.parse, urllib.error # 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
import json # for tournament scoreboard things
# command trigger - this should be in botconf - next time.
TRIGGER = '$'
site.addsitedir('.')
from tnntbotconf import HOST, PORT, CHANNELS, NICK, USERNAME, REALNAME, BOTDIR
from tnntbotconf import PWFILE, FILEROOT, WEBROOT, LOGROOT, ADMIN, YEAR
from tnntbotconf import SERVERTAG
try:
from tnntbotconf import SPAMCHANNELS
except:
SPAMCHANNELS = CHANNELS
try: from tnntbotconf import DCBRIDGE
except:
DCBRIDGE = None
try:
from tnntbotconf import TEST
except:
TEST = False
try:
from tnntbotconf import GRACEDAYS
except:
GRACEDAYS = 5
try:
from tnntbotconf import REMOTES
except:
SLAVE = True
REMOTES = {}
try:
from tnntbotconf import MASTERS
except:
SLAVE = False
MASTERS = []
try:
#from tnntbotconf import LOGBASE, IRCLOGS
from tnntbotconf import IRCLOGS
except:
#LOGBASE = BOTDIR + "/tnntbot.log"
IRCLOGS = LOGROOT
# config.json is where all the tournament trophies, achievements, other stuff are defined.
# it's mainly used for driving the official scoreboard but we use it here too.
#TWIT = False
if not SLAVE:
try:
from tnntbotconf import CONFIGJSON
except:
CONFIGJSON = "config.json" # assume current directory
# slurp the whole shebang into a big-arse dict.
# need to parse out the comments. Thses must start with '# ' or '#-'
# because my regexp is dumb
config = json.loads(re.sub('#[ -].*','',open(CONFIGJSON).read()))
# scoreboard.json is the output from the scoreboard script that tracks achievements and trophies
try:
from tnntbotconf import SCOREBOARDJSON
except:
SCOREBOARDJSON = "scoreboard.json" # assume current directory
# twitter - minimalist twitter api: http://mike.verdone.ca/twitter/
# pip install twitter
# set TWIT to false to prevent tweeting
#TWIT = True
#try:
# from tnntbotconf import TWITAUTH
#except:
# print("no TWITAUTH - twitter disabled")
# TWIT = False
#try:
# from twitter import Twitter, OAuth
#except:
# print("Unable to import from twitter module")
# TWIT = False
CLANTAGJSON = BOTDIR + "/clantag.json"
# some lookup tables for formatting messages
# these are not yet in conig.json
role = { "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"
}
race = { "Dwa": "Dwarf",
"Elf": "Elf",
"Gno": "Gnome",
"Hum": "Human",
"Orc": "Orc"
}
align = { "Cha": "Chaotic",
"Law": "Lawful",
"Neu": "Neutral"
}
gender = { "Mal": "Male",
"Fem": "Female"
}
def fromtimestamp_int(s):
return datetime.fromtimestamp(int(s))
def timedelta_int(s):
return timedelta(seconds=int(s))
def isodate(s):
return datetime.strptime(s, "%Y%m%d").date()
def fixdump(s):
return s.replace("_",":")
xlogfile_parse = dict.fromkeys(
("points", "deathdnum", "deathlev", "maxlvl", "hp", "maxhp", "deaths",
"uid", "turns", "xplevel", "exp","depth","dnum","score","amulet"), int)
xlogfile_parse.update(dict.fromkeys(
("conduct", "event", "carried", "flags", "achieve"), ast.literal_eval))
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:
if NICK not in slaves: slaves[NICK] = [WEBROOT,NICK,FILEROOT]
#...and the masters list
if NICK not in MASTERS: MASTERS += [NICK]
try:
password = open(PWFILE, "r").read().strip()
except:
password = "NotTHEPassword"
#if TWIT:
# try:
# gibberish_that_makes_twitter_work = open(TWITAUTH,"r").read().strip().split("\n")
# twit = Twitter(auth=OAuth(*gibberish_that_makes_twitter_work))
# except Exception as e:
# print("Failed to auth to twitter")
# print(e)
# TWIT = False
sourceURL = "https://github.com/tnnt-devteam/tnntbot"
versionName = "tnntbot.py"
versionNum = "0.1"
dump_url_prefix = WEBROOT + "userdata/{name[0]}/{name}/"
dump_file_prefix = FILEROOT + "dgldir/userdata/{name[0]}/{name}/"
# tnnt runs on UTC
os.environ["TZ"] = "UTC"
time.tzset()
ttime = { "start": datetime(int(YEAR),11,1,0,0,0),
"end" : datetime(int(YEAR),12,1,0,0,0)
}
chanLog = {}
chanLogName = {}
activity = {}
if not SLAVE:
scoresURL = "https://tnnt.org/leaderboards or https://tnnt.org/trophies"
ttyrecURL = WEBROOT + "nethack/ttyrecs"
rceditURL = WEBROOT + "nethack/rcedit"
helpURL = sourceURL + "/blob/master/botuse.txt"
logday = time.strftime("%d")
for c in CHANNELS:
activity[c] = 0
if IRCLOGS:
chanLogName[c] = IRCLOGS + "/" + c + time.strftime("-%Y-%m-%d.log")
try:
chanLog[c] = open(chanLogName[c],'a')
except:
chanLog[c] = None
if chanLog[c]: os.chmod(chanLogName[c],stat.S_IRUSR|stat.S_IWUSR|stat.S_IRGRP|stat.S_IROTH)
xlogfiles = {filepath.FilePath(FILEROOT+"tnnt/var/xlogfile"): ("tnnt", "\t", "tnnt/dumplog/{starttime}.tnnt.html")}
livelogs = {filepath.FilePath(FILEROOT+"tnnt/var/livelog"): ("tnnt", "\t")}
scoreboard = {}
try:
clanTag = json.load(open(CLANTAGJSON))
except:
clanTag = {}
# for displaying variants and server tags in colour
displaystring = {"hdf-us" : "\x1D\x0304US\x03\x0F",
"hdf-au" : "\x1D\x0303AU\x03\x0F",
"hdf-eu" : "\x1D\x0312EU\x03\x0F",
"hdf-test": "\x1D\x0308TS\x03\x0F",
"trophy" : "\x1D\x0313Tr\x03\x0F",
"achieve" : "\x1D\x0305Ac\x03\x0F",
"clan" : "\x1D\x0312R\x03\x0F",
"died" : "\x02\x1D\x0304D\x03\x0F",
"quit" : "\x02\x1D\x0308Q\x03\x0F",
"ascended": "\x02\x1D\x0309A\x03\x0F",
"escaped" : "\x02\x1D\x0310E\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 = {"tnnt" : [INPR+"tnnt/"]}
# for !whereis
whereis = {"tnnt": [FILEROOT+"tnnt/var/whereis/"]}
dungeons = ["The Dungeons of Doom", "Gehennom", "The Gnomish Mines",
"The Quest", "Sokoban", "Fort Ludios", "DevTeam Office",
"Deathmatch Arena", "robotfindskitten", "Vlad's Tower",
"The Elemental Planes"]
looping_calls = None
commands = {}
def initStats(self, statset):
self.stats[statset] = { "race" : {},
"role" : {},
"gender" : {},
"align" : {},
"points" : 0,
"turns" : 0,
"realtime": 0,
"games" : 0,
"scum" : 0,
"ascend" : 0,
}
# 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()
if not SLAVE:
for c in CHANNELS:
self.join(c)
random.seed()
self.logs = {}
# boolean for whether announcements from the log are 'spam', after dumpfmt
# true for livelogs, false for xlogfiles
for xlogfile, (variant, delim, dumpfmt) in self.xlogfiles.items():
self.logs[xlogfile] = (self.xlogfileReport, variant, delim, dumpfmt, False)
for livelog, (variant, delim) in self.livelogs.items():
self.logs[livelog] = (self.livelogReport, variant, delim, "", True)
self.logs_seek = {}
self.looping_calls = {}
#stats for hourly/daily spam
self.stats = {}
self.initStats("hour")
self.initStats("day")
self.initStats("full")
if not SLAVE:
# work out how much hour is left
nowtime = datetime.now()
# add 1 hour, then subtract min, sec, usec to get exact time of next hour.
nexthour = nowtime + timedelta(hours=1)
nexthour -= timedelta(minutes=nexthour.minute,
seconds=nexthour.second,
microseconds=nexthour.microsecond)
hourleft = (nexthour - nowtime).total_seconds() + 0.5 # start at 0.5 seconds past the hour.
reactor.callLater(hourleft, self.startHourly)
# round up of basic stats for milestone reporting.
self.summaries = {}
for s in self.slaves:
# summary stats for each server
self.summaries[s] = { "games" : 0,
"points" : 0,
"turns" : 0,
"realtime": 0,
"ascend" : 0 }
# existing totals so we know when we pass a threshold
self.summary = { "games" : 0,
"points" : 0,
"turns" : 0,
"realtime": 0,
"ascend" : 0 }
self.milestones = { "games" : [500, 1000, 5000, 10000, 50000, 100000],
"points" : [50000000, 100000000, 500000000, 1000000000, 5000000000],
"turns" : [1000000, 5000000, 10000000, 50000000, 100000000],
"realtime": [50, 100, 500, 1000, 5000 ], # converted to 24h days (86400s)
"ascend" : [50, 100, 200, 300, 400, 500]}
#lastgame shite
self.lastgame = "No last game recorded"
self.lg = {}
self.lastasc = "No last ascension recorded"
self.la = {}
# streaks
self.curstreak = {}
self.longstreak = {}
# ascensions (for !asc)
# "!asc plr" will give asc stats for player.
# "!asc" will be as above, assuming requestor's nick.
# asc[player][role] = count;
# asc[player][race] = count;
# asc[player][align] = count;
# asc[player][gender] = count;
# assumes 3-char abbreviations for role/race/align/gender, and no overlaps.
# for asc ratio we need total games too
# allgames[player] = count;
self.asc = {}
self.allgames = {}
# for !tell
try:
self.tellbuf = shelve.open(BOTDIR + "/tellmsg.db", writeback=True)
except:
self.tellbuf = shelve.open(BOTDIR + "/tellmsg", writeback=True, protocol=2)
# Commands must be lowercase here.
self.commands = {"ping" : self.doPing,
"time" : self.doTime,
"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,
"score" : self.doScore,
"clanscore": self.doClanScore,
"clantag" : self.doClanTag,
"players" : self.multiServerCmd,
"who" : self.multiServerCmd,
"asc" : self.multiServerCmd,
"streak" : self.multiServerCmd,
"whereis" : self.multiServerCmd,
"stats" : self.multiServerCmd,
# these ones are for control messages between master and slaves
# sender is checked, so these can't be used by the public
# this one is a message from slave with current stats, for milestone reporting
"#s#" : self.checkMilestones,
# query from master to slave
"#q#" : self.doQuery,
# responses from slave to master
"#p#" : self.doResponse, # 'partial' for long responses
"#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,
"stats" : self.getStats, # user requests !stats
"hstats" : self.getStats, # scheduled hourly stats
"cstats" : self.getStats, # cumulative day stats (6-hourly)
"dstats" : self.getStats, # scheduled daily stats
"fstats" : self.getStats} # scheduled final stats
# 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,
"stats" : self.outStats,
"hstats" : self.outStats,
"cstats" : self.outStats,
"dstats" : self.outStats,
"fstats" : self.outStats}
# 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}
# 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:
delim = self.logs[filepath][2]
game = parse_xlogfile_line(line, delim)
game["variant"] = self.logs[filepath][1]
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)
# 1 minute looping call for trophies and achievements.
self.looping_calls["trophy"] = task.LoopingCall(self.checkScoreboard)
self.looping_calls["trophy"].start(30)
# Call it now to seed the trophy dict.
self.checkScoreboard()
# Update local milestone summary to master every 5 minutes
self.looping_calls["summary"] = task.LoopingCall(self.updateSummary)
self.looping_calls["summary"].start(300)
#def tweet(self, message):
# if TWIT:
# message = self.stripText(message)
# try:
# if TEST:
# message = "[TEST] " + message
# print("Not tweeting in test mode: " + message)
# return
# self.twit.statuses.update(status=message)
# except Exception as e:
# print("Bad tweet: " + message)
# print(e)
def nickCheck(self):
# also rejoin the channel here, in case we drop off for any reason
if not SLAVE:
for c in CHANNELS: self.join(c)
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)
def logRotate(self):
if not IRCLOGS: return
self.logday = time.strftime("%d")
for c in CHANNELS:
if self.chanLog[c]: self.chanLog[c].close()
self.chanLogName[c] = IRCLOGS + "/" + c + time.strftime("-%Y-%m-%d.log")
try: self.chanLog[c] = open(self.chanLogName[c],'a') # 'w' is probably fine here
except: self.chanLog[c] = None
if self.chanLog[c]: os.chmod(self.chanLogName[c],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, channel, message):
if not self.chanLog.get(channel,None): return
message = self.stripText(message)
if time.strftime("%d") != self.logday: self.logRotate()
self.chanLog[channel].write(time.strftime("%H:%M ") + message + "\n")
self.chanLog[channel].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 in CHANNELS:
self.log(replyto, "<" + self.nickname + "> " + message)
self.msg(replyto, message)
# Similar wrapper for describe
def describeLog(self,replyto, message):
if replyto in CHANNELS:
self.log("* " + self.nickname + " " + message)
self.describe(replyto, message)
# Tournament announcements typically go to the channel
# ...and to the channel log
# ...and to twitter. announce() does this.
# spam flag allows more verbosity in some channels
def announce(self, message, spam = False):
if not TEST:
# Only announce during tournament, or short grace period following
nowtime = datetime.now()
game_on = (nowtime > self.ttime["start"]) and (nowtime < (self.ttime["end"] + timedelta(days=GRACEDAYS)))
if not game_on: return
chanlist = CHANNELS
if spam:
chanlist = SPAMCHANNELS #only
#else: # only tweet non spam
#self.tweet(message)
for c in chanlist:
self.msgLog(c, 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
#Q#
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));
#R# / #P#
def doResponse(self, sender, replyto, msgwords):
# called when slave returns query response to master
# msgwords is [ #R#, <query_id>, [server-tag], command output, ...]
# for long resps ([ #P#, <query>, output ]) * n, finishing with #R# msg as above
# Assumes message fragments arrive in the same order as sent. Yeah, yeah I know...
if sender in self.slaves and msgwords[1] in self.queries:
self.queries[msgwords[1]]["resp"][sender] = self.queries[msgwords[1]]["resp"].get(sender,"") + " ".join(msgwords[2:])
if msgwords[0] == "#R#": self.queries[msgwords[1]]["finished"][sender] = True
if set(self.queries[msgwords[1]]["finished"].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));
# As above, but timed out receiving one or more responses
def doQueryTimeout(self, query):
# This gets called regardless, so only process if query still exists
if query not in self.queries: return
noResp = []
for i in self.slaves.keys():
if not self.queries[query]["finished"].get(i,False):
noResp.append(i)
if noResp:
print("WARNING: Query " + query + ": No response from " + self.listStuff(noResp))
self.queries[query]["callback"](self.queries.pop(query))
#S#
def checkMilestones(self, sender, replyto, msgwords):
numbers = { 1000000: "One million",
5000000: "Five million",
10000000: "Ten million",
50000000: "50 million",
100000000: "100 million",
500000000: "500 million",
1000000000: "One billion",
5000000000: "Five billion" }
statnames = { "games" : "games played",
"ascend" : "ascended games",
"points" : "nethack points scored",
"turns" : "turns played",
"realtime": "days spent playing nethack"}
if sender not in self.slaves:
return
# if this is the first time the slave has contacted us since we restarted
# we don't want to announce anything, because we risk repeating ourselves
FirstContact = False
if self.summaries[sender]["games"] == 0:
FirstContact = True
self.summaries[sender] = json.loads(" ".join(msgwords[1:]))
for k in list(self.milestones.keys()):
t = 0
for s in self.summaries:
t += self.summaries[s][k]
if k == "realtime": t /= 86400 # days, not seconds
if not FirstContact:
for m in self.milestones[k]:
if self.summary[k] and t >= m and self.summary[k] < m:
self.announce("\x02TOURNAMENT MILESTONE:\x0f {0} {1}.".format(numbers.get(m,m), statnames.get(k,k)))
self.summary[k] = t
# Hourly/daily/special stats
def spamStats(self, p, stats, replyto):
# formatting awkwardness
# do turns and points, or time.
stat1lst = [ "{turns} turns, {points} points. ",
"{d}d {h:02d}:{m:02d} gametime. "
]
stat2str = { "align" : "alignment" } # use get() to leave unchanged if not here
periodStr = { "hour" : "\x02Hourly Stats\x0f at %F %H:00 %Z: ",
"day" : "\x02DAILY STATS\x0f AT %F %H:00 %Z: ",
"news" : "\x02Current Day\x0f as of %F %H:%M %Z: ",
"full" : "\x02FINAL TOURNAMENT STATISTICS:\x0f "
}
# hourly, we report one of role/race/etc. Daily, and for news, we report them all
if p == "hour":
if stats["games"] - stats["scum"] < 10: return
stat1lst = [random.choice(stat1lst)]
# weighted. role is more interesting than gender
stat2lst = [random.choice(["role"] * 5 + ["race"] * 3 + ["align"] * 2 + ["gender"])]
else:
stat2lst = ["role", "race", "align", "gender"]
cd = self.countDown()
if cd["event"] == "start": cd["prep"] = "to go!"
else: cd["prep"] = "remaining."
if replyto:
chanlist = [replyto]
else:
chanlist = SPAMCHANNELS
if stats["games"] != 0:
# mash the realtime value into d,h,m,s
rt = int(stats["realtime"])
stats["s"] = int(rt%60)
rt //= 60
stats["m"] = int(rt%60)
rt //= 60
stats["h"] = int(rt%24)
rt //= 24
stats["d"] = int(rt)
statmsg = time.strftime(periodStr[p]) + "Games: {games}, Asc: {ascend}, Scum: {scum}. ".format(**stats)
if stats["games"] != 0:
for stat1 in stat1lst:
statmsg += stat1.format(**stats)
for stat2 in stat2lst:
# Find whatever thing from the list above had the most games, and how many games it had
maxStat2 = dict(list(zip(["name","number"],max(iter(stats[stat2].items()), key=lambda x:x[1]))))
# Expand the Rog->Rogue, Fem->Female, etc
#maxStat2["name"] = dict(role.items() + race.items() + gender.items() + align.items()).get(maxStat2["name"],maxStat2["name"])
# convert number to % of total (non-scum) games
maxStat2["number"] = int(round(maxStat2["number"] * 100 / (stats["games"] - stats["scum"])))
statmsg += "({number}%{name}), ".format(**maxStat2)
if p != "full":
statmsg += "{days}d {hours:02d}:{minutes:02d} {prep}".format(**cd)
for c in chanlist:
self.msgLog(c, statmsg)
else:
for c in chanlist:
self.msgLog(c, statmsg)
self.msgLog(c, "We hope you enjoyed The November Nethack Tournament.")
self.msgLog(c, "Thank you for playing.")
def startCountdown(self,event,time):
self.announce("The tournament {0}s in {1}...".format(event,time),True)
for delay in range (1,time):
reactor.callLater(delay,self.announce,"{0}...".format(time-delay),True)
# def testCountdown(self, sender, replyto, msgwords):
# self.startCountdown(msgwords[1],int(msgwords[2]))
def hourlyStats(self):
nowtime = datetime.now()
# special case handling for start/end
# we are running at the top of the hour
# so checking we are within 1 minute of start/end time is sufficient
if abs(nowtime - self.ttime["start"]) < timedelta(minutes=1):
self.announce("###### TNNT {0} IS OPEN! ######".format(YEAR))
elif abs(nowtime - self.ttime["end"]) < timedelta(minutes=1):
self.announce("###### TNNT {0} IS CLOSED! ######".format(YEAR))
self.multiServerCmd(NICK, NICK, ["fstats"])
return
elif abs(nowtime + timedelta(hours=1) - self.ttime["start"]) < timedelta(minutes=1):
reactor.callLater(3597, self.startCountdown,"start",3) # 3 seconds to the next hour
elif abs(nowtime + timedelta(hours=1) - self.ttime["end"]) < timedelta(minutes=1):
reactor.callLater(3597, self.startCountdown,"end",3) # 3 seconds to the next hour
game_on = (nowtime > self.ttime["start"]) and (nowtime < self.ttime["end"])
if TEST: game_on = True
if not game_on: return
if nowtime.hour == 0:
self.multiServerCmd(NICK, NICK, ["dstats"])
elif nowtime.hour % 6 == 0:
self.multiServerCmd(NICK, NICK, ["cstats"])
else:
self.multiServerCmd(NICK, NICK, ["hstats"])
def startHourly(self):
# this is scheduled to run at the first :00 after the bot starts
# makes a looping_call to run every hour from here on.
self.looping_calls["stats"] = task.LoopingCall(self.hourlyStats)
self.looping_calls["stats"].start(3600)
# Countdown timer
def countDown(self):
cd = {}
for event in ("start", "end"):
cd["event"] = event
# add half a second for rounding (we truncate at the decimal later)
td = (self.ttime[event] - datetime.now()) + timedelta(seconds=0.5)
sec = int(td.seconds)
cd["seconds"] = int(sec % 60)
cd["minutes"] = int((sec / 60) % 60)
cd["hours"] = int(sec / 3600)
cd["days"] = td.days
cd["countdown"] = td
if td > timedelta(0):
return cd
return cd
# Trohy/achievement reporting
def listStuff(self, theList):
# make a string from a list, like "this, that, and the other thing"
listStr = ""
for (i,n) in enumerate(theList):
# first item
if (i == 0):
listStr = str(n)
# last item
elif (i == len(theList)-1):
if (i > 1): listStr += "," # oxford
listStr += " and " + str(n)
# middle items
else:
listStr += ", " + str(n)
return listStr
def listTrophies(self,trophies):
tlist = []
for t in trophies:
tlist += [config["trophies"][str(t)]["title"].encode('utf-8')]
return self.listStuff(tlist)
def listAchievements(self, achievements, maxCount):
if len(achievements) > maxCount:
return str(len(achievements)) + " new achievements"
alist = []
for a in achievements:
alist += [config["achievements"][str(a)]["title"].encode('utf-8')]
return self.listStuff(alist)
def checkScoreboard(self):
if SLAVE: return
# this chokes down the whole json file output by the scoreboard system,
# Makes some comparisons,
# and reports anything interesting that has changed.
prevScoreboard = {}
if self.scoreboard: prevScoreboard = self.scoreboard
try:
self.scoreboard = json.load(open(SCOREBOARDJSON))
except:
print("Failed to load scoreboard from " + SCOREBOARDJSON)
self.scoreboard = prevScoreboard
return
if not prevScoreboard: return
if "all" not in self.scoreboard["players"]: return # scoreboard is empty at the start
prevGreatFoo = prevScoreboard["trophies"]["players"].get("greatfoo",{})
for player in self.scoreboard["players"]:
currTrophies = self.scoreboard["players"][player].get("trophies",[])
try: prevTrophies = prevScoreboard["players"][player].get("trophies",[])
except: prevTrophies = [] # Player won't be in prev, if it's their 1st game
newTrophies = []
for t in currTrophies:
if t not in prevTrophies and t["trophy"] != "noscum": # noscum trophy will be spammy
newTrophies += [t["trophy"]]
if newTrophies:
self.announce(self.displaytag("trophy") + " "
+ str(self.scoreboard["players"][player]["name"].encode('utf-8'))
+ " now has " + self.listTrophies(newTrophies) + "!")
currAch = self.scoreboard["players"][player].get("achievements",[])
try: prevAch = prevScoreboard["players"][player].get("achievements",[])
except: prevAch = []
newAch = []
for a in currAch:
if a not in prevAch:
newAch += [a]
if newAch:
alist = self.listAchievements(newAch, 4)
if alist == "Shafted":
alist = " just got " + alist
else:
alist = " just earned " + alist
self.announce(self.displaytag("achieve") + " "
+ str(self.scoreboard["players"][player]["name"].encode('utf-8'))
+ alist + ".", True)
# report clan ranking changes
# this assumes clan["n"] is the index to the clan list and it never changes
for clan in self.scoreboard["clans"]:
if len(prevScoreboard["clans"]) <= int(clan["n"]):
self.announce(self.displaytag("clan") + " New clan registered - "
+ str(clan["name"].encode('utf-8')) + "!")
elif "rank" in clan and prevScoreboard["clans"][int(clan["n"])].get("rank",0) > clan["rank"]:
self.announce(self.displaytag("clan") + " Clan "
+ str(clan["name"].encode('utf-8'))
+ " advances to rank "
+ str(clan["rank"]) + "!")
# implement commands here
def doPing(self, sender, replyto, msgwords):
self.respond(replyto, sender, "Pong! " + " ".join(msgwords[1:]))
def doTime(self, sender, replyto, msgwords):
timeMsg = time.strftime("%F %H:%M:%S %Z. ")
timeLeft = self.countDown()
if timeLeft["countdown"] <= timedelta(0):
timeMsg += "The " + YEAR + " tournament is OVER!"
self.respond(replyto, sender, timeMsg)
return
verbs = { "start" : "begins",
"end" : "closes"
}
timeMsg += YEAR + " Tournament " + verbs[timeLeft["event"]] + " in {days}d {hours:0>2}:{minutes:0>2}:{seconds:0>2}".format(**timeLeft)
self.respond(replyto, sender, timeMsg)
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 doScore(self, sender, replyto, msgwords):
if len(msgwords) > 2:
self.respond(replyto, sender, TRIGGER + msgwords[0]
+ " - get tournament score and ranking of yourself or another player")
return
if len(msgwords) == 2:
# accommodate the '\' clan tags that players add in irc.
PLR = msgwords[1].split("\\")[0]
else:
PLR = sender
plr = PLR.lower()
# case insensitive search
player = None
for p in list(self.scoreboard["players"].keys()):
if plr == p.lower():
player = p
break
if not player:
self.respond(replyto, sender, "Can't find player {0} on the scoreboard.".format(PLR))
return
score = int(self.scoreboard["players"][player]["score"])
rank = int(self.scoreboard["players"][player]["rank"])
self.respond(replyto, sender, str(player) + " - Score: {0} - Rank: {1}".format(score, rank))
def doClanTag(self, sender, replyto, msgwords):
# msgwords[1] is the desired tag, msgwords[the rest] is the clan name as it appears in the scoreboard
# case is ignored for searching, but correct case is stored in the table for faster lookup later.
if len(msgwords) < 3:
self.respond(replyto, sender, TRIGGER + msgwords[0] + " <tag> <clan name> - assigns a shorthand tag to a clan for use with " + TRIGGER + "clanscore")
return
if msgwords[1].lower() in [clan["name"].lower() for clan in self.scoreboard["clans"]["all"]]:
self.respond(replyto, sender, msgwords[1] + " is already the name of a clan.") # people will be smartarses
return
for clan in self.scoreboard["clans"]:
if clan["name"].lower() == " ".join(msgwords[2:]).lower():
self.clanTag[msgwords[1].lower()] = {"n": int(clan["n"]), "name": str(clan["name"])}
self.respond(replyto, sender, "Clan Tag {0} assigned to {1}".format(msgwords[1],str(clan["name"])))
with open(CLANTAGJSON, 'w') as f:
json.dump(self.clanTag, f)
return
self.respond(replyto, sender, "Can't find a clan named {0} on the scoreboard".format(" ".join(msgwords[2:])))
def doClanScore(self, sender, replyto, msgwords):
tryClan, name, score, rank = '', '', 0, 0
# the hard part is working out what clan we need to look up
if len(msgwords) > 1:
tryClan = " ".join(msgwords[1:])
else:
splitNick = sender.split("\\")
if len(splitNick) > 1:
tryClan = splitNick[1]
else:
# look up clan of player(sender)
for clan in self.scoreboard["clans"]:
# fugly case-insensitive search
if sender.lower() in " ".join(clan["players"]).lower().split(" "):
name, score, rank = [clan[x] for x in ["name","score","rank"]]
break
if not name:
if not tryClan:
self.respond(replyto, sender, "Could not get clan membership for " + sender + ".")
return
if tryClan.lower() in self.clanTag:
clan = self.scoreboard["clans"][self.clanTag[tryClan.lower()]["n"]]
name, score, rank = [clan[x] for x in ["name","score","rank"]]
else:
for clan in self.scoreboard["clans"]:
if clan["name"].lower() == tryClan.lower():
name, score, rank = [clan[x] for x in ["name","score","rank"]]
if name:
self.respond(replyto, sender, str(name) + " - Score: {0} - Rank: {1}".format(int(score),int(rank)))