forked from NHTangles/beholder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtnntbot.py
More file actions
executable file
·2647 lines (2323 loc) · 120 KB
/
tnntbot.py
File metadata and controls
executable file
·2647 lines (2323 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- 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 and rate limiting
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
import resource # for memory usage in status command
import requests # for GitHub API
import xml.etree.ElementTree as ET # for parsing GitHub Atom feeds
# command trigger - this should be in tnntbotconf - 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
# GitHub configuration (optional)
try:
from tnntbotconf import ENABLE_GITHUB, GITHUB_REPOS
except ImportError:
ENABLE_GITHUB = False
GITHUB_REPOS = []
# TNNT API configuration
TNNT_API_BASE = "http://127.0.0.1:8000/api" # Use localhost for same server
TNNT_API_HEADERS = {"Host": "tnnt.org"} # Required for Django ALLOWED_HOSTS
try:
from tnntbotconf import SPAMCHANNELS
except ImportError:
SPAMCHANNELS = CHANNELS
try:
from tnntbotconf import DCBRIDGE
except ImportError:
DCBRIDGE = None
try:
from tnntbotconf import TEST
except ImportError:
TEST = False
try:
from tnntbotconf import GRACEDAYS
except ImportError:
GRACEDAYS = 5
try:
from tnntbotconf import ANNOUNCE_AFTER_DB_REBUILD
except ImportError:
ANNOUNCE_AFTER_DB_REBUILD = True # Default to announcing for backwards compatibility
try:
from tnntbotconf import REMOTES
except ImportError:
SLAVE = True
REMOTES = {}
try:
from tnntbotconf import MASTERS
except ImportError:
SLAVE = False
MASTERS = []
try:
#from tnntbotconf import LOGBASE, IRCLOGS
from tnntbotconf import IRCLOGS
except ImportError:
#LOGBASE = BOTDIR + "/tnntbot.log"
IRCLOGS = LOGROOT
# JSON configuration files are deprecated - trophy/achievement tracking removed
if not SLAVE:
# Hardcoded game data for NetHack roles, races, aligns, genders
NETHACK_ROLES = ["Arc", "Bar", "Cav", "Hea", "Kni", "Mon", "Pri", "Ran", "Rog", "Sam", "Tou", "Val", "Wiz"]
NETHACK_RACES = ["Dwa", "Elf", "Gno", "Hum", "Orc"]
NETHACK_ALIGNS = ["Cha", "Law", "Neu"]
NETHACK_GENDERS = ["Mal", "Fem"]
CLANTAGJSON = BOTDIR + "/clantag.json"
# Rate limiting constants
RATE_LIMIT_WINDOW = 60 # Rate limiting time window in seconds
RATE_LIMIT_COMMANDS = 60 # Commands per minute for all operations (1/second)
BURST_WINDOW = 1 # Burst protection: only 1 command per second window
ABUSE_THRESHOLD = 10 # Consecutive commands before abuse penalty
ABUSE_WINDOW = 30 # Time window for abuse detection (seconds)
ABUSE_PENALTY = 900 # Abuse penalty duration in seconds (15 minutes)
RESPONSE_RATE_LIMIT = 1 # Max penalty messages per 2 minutes to prevent spam
RESPONSE_RATE_WINDOW = 120 # Penalty message rate limit window (2 minutes)
# Time constants
SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 3600
SECONDS_PER_DAY = 86400
LOG_POLL_INTERVAL = 3 # seconds between log file checks
NICK_CHECK_INTERVAL = 30 # seconds between nick checks
SUMMARY_UPDATE_INTERVAL = 300 # seconds between summary updates (5 minutes)
STALE_BURST_TIMEOUT = 3600 # 1 hour before removing burst protection data
# Game thresholds
# Startscum definition: quit/escaped with <= 100 turns (no dumplog generated)
SHORT_GAME_TURNS = 100 # turns below which games are batched
SHORT_GAME_BATCH_SIZE = 100 # report every N short games
# Pre-compiled regex patterns for better performance
RE_COLOR_FG_BG = re.compile(r'\x03\d\d,\d\d') # fg,bg pair
RE_COLOR_FG = re.compile(r'\x03\d\d') # fg only
RE_COLOR_END = re.compile(r'[\x1D\x03\x0f]') # end of colour and italics
RE_DICE_CMD = re.compile(r'^\d*d\d*$') # dice command pattern
RE_SPACE_COLOR = re.compile(r'^ [\x1D\x03\x0f]*') # space and color codes
# Logging helper with timestamps
def tlog(message):
"""Print a log message with timestamp in format [YYYY-MM-DD HH:MM:SS]"""
timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
print(f"{timestamp} {message}")
# Timestamped stderr wrapper for error logging
class TimestampedStderr:
"""Wrapper for sys.stderr that prepends timestamps to each line.
Twisted's exception handling writes to stderr without timestamps.
This wrapper ensures error.log entries have the same timestamp format
as access.log entries from tlog().
"""
def __init__(self, stream):
self._stream = stream
self._line_start = True
def write(self, text):
if not text:
return
# Process text character by character to handle partial lines
output = []
for char in text:
if self._line_start and char != '\n':
timestamp = datetime.now().strftime("[%Y-%m-%d %H:%M:%S] ")
output.append(timestamp)
self._line_start = False
output.append(char)
if char == '\n':
self._line_start = True
self._stream.write(''.join(output))
def flush(self):
self._stream.flush()
# Pass through other attributes to the underlying stream
def __getattr__(self, name):
return getattr(self._stream, name)
# Install timestamped stderr wrapper
import sys
sys.stderr = TimestampedStderr(sys.stderr)
# Custom dict class for shelve fallback
class DictWithSync(dict):
"""Dict subclass that supports sync() method for shelve compatibility.
When the shelve database fails to open, we fall back to an in-memory
dict. This class provides a no-op sync() method so the same code can
work with both shelve objects and the in-memory fallback.
"""
def sync(self):
"""No-op sync method for in-memory dict fallback."""
pass
# 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 safe_int_parse(s):
"""Safely parse integers, including hex values like 0x1234"""
try:
# Try to parse as int, supports base 10, hex (0x), octal (0o), binary (0b)
return int(s, 0)
except ValueError:
# If that fails, try without base detection
try:
return int(s)
except ValueError:
return 0 # Default to 0 for invalid values
def sanitize_format_string(text):
"""Sanitize text to prevent format string injection attacks.
Escapes curly braces that could be used in format string attacks.
"""
if not isinstance(text, str):
return text
return text.replace('{', '{{').replace('}', '}}')
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"), safe_int_parse))
def parse_xlogfile_line(line, delim):
record = {}
# User-controlled fields that need sanitization
user_controlled_fields = {"name", "charname", "death", "role", "race",
"gender", "align", "bones_killed", "bones_rank",
"killed_uniq", "wish", "shout", "genocided_monster",
"shop", "shopkeeper"}
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)
# Sanitize user-controlled fields to prevent format string injection
elif key in user_controlled_fields:
value = sanitize_format_string(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:
with open(PWFILE, "r") as f:
password = f.read().strip()
except (IOError, OSError) as e:
tlog(f"Warning: Could not read password file {PWFILE}: {e}")
password = "NotTHEPassword"
sourceURL = "https://github.com/tnnt-devteam/tnntbot"
versionName = "tnntbot.py"
versionNum = "0.1"
# bot_start_time will be set in signedOn() for accurate uptime tracking
# Croesus reaction messages (bot speaks AS Croesus)
croesus_player_wins = [
"{player} has defeated me! How dare you!",
"{player} strikes me down. I'll remember this...",
"Well done, {player}. You've bested me!",
"{player} has proven stronger than me!",
"I fall before {player}!",
"Impressive, {player}. I didn't stand a chance.",
"{player} loots my vault and walks away victorious!",
"I have been slain by {player}. Brutal!",
]
croesus_croesus_wins = [
"I claim {player}! Muahahaha!",
"I have been avenged! RIP {player}.",
"{player} learned not to mess with me the hard way.",
"{player} underestimated me. Fatal mistake.",
"I defend my vault from {player}!",
"{player} won't be stealing from me today... or ever.",
"Another greedy adventurer falls to me. RIP {player}.",
"I add {player} to my collection of failed thieves.",
]
dump_url_prefix = f"{WEBROOT}userdata/{{name[0]}}/{{name}}/"
dump_file_prefix = f"{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 = f"{WEBROOT}nethack/ttyrecs"
dumplogURL = f"{WEBROOT}nethack/dumplogs"
irclogURL = f"{WEBROOT}nethack/irclogs/tnnt"
rceditURL = f"{WEBROOT}nethack/rcedit"
helpURL = f"{sourceURL}/blob/main/botuse.md"
logday = time.strftime("%d")
for c in CHANNELS:
activity[c] = 0
if IRCLOGS:
chanLogName[c] = f"{IRCLOGS}/{c}{time.strftime('-%Y-%m-%d.log')}"
try:
chanLog[c] = open(chanLogName[c],'a')
except (IOError, OSError) as e:
tlog(f"Warning: Could not open log file {chanLogName[c]}: {e}")
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 removed - JSON files deprecated
try:
with open(CLANTAGJSON) as f:
clanTag = json.load(f)
except (IOError, OSError) as e:
# File doesn't exist or can't be read - normal for fresh install
clanTag = {}
except json.JSONDecodeError as e:
tlog(f"Error: Invalid JSON in {CLANTAGJSON}: {e}")
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 f'[{self.displaystring.get(thing,thing)}]'
# for !who or !players or whatever we end up calling it
# Reduce the repetitive crap
DGLD = f"{FILEROOT}dgldir/"
INPR = f"{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,
}
def _initializeStats(self):
"""Initialize statistics tracking for hourly/daily/full periods."""
self.stats = {}
self.initStats("hour")
self.initStats("day")
self.initStats("full")
def _scheduleMasterTasks(self):
"""Schedule master-specific periodic tasks."""
# 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)
def _scheduleAPIPolling(self):
"""Schedule API polling to run every 5 minutes at :00:30, :05:30, :10:30, :15:30, etc."""
# Do an initial fetch after 30 seconds to populate data quickly
reactor.callLater(30, self._initialAPIFetch)
nowtime = datetime.now()
# Calculate next 5-minute mark
current_minute = nowtime.minute
minutes_to_next_5 = (5 - (current_minute % 5)) % 5
if minutes_to_next_5 == 0 and nowtime.second >= 30:
# If we're already past :X5:30, go to next 5-minute mark
minutes_to_next_5 = 5
# Calculate time until next :X5:30
next_poll = nowtime + timedelta(minutes=minutes_to_next_5)
next_poll = next_poll.replace(second=30, microsecond=0)
next_poll -= timedelta(minutes=next_poll.minute % 5) # Ensure we're at :00, :05, :10, :15, etc.
seconds_until_next = (next_poll - nowtime).total_seconds()
if seconds_until_next <= 0:
seconds_until_next += 300 # Add 5 minutes if somehow negative
tlog(f"TNNT API: Scheduling regular polling to start in {seconds_until_next:.1f} seconds (at {next_poll.strftime('%H:%M:%S')})")
reactor.callLater(seconds_until_next, self.startAPIPolling)
def _initialAPIFetch(self):
"""Do an initial API fetch to populate data quickly after startup"""
tlog("TNNT API: Performing initial data fetch...")
self.checkTNNTAPI()
def _initializeMilestones(self):
"""Initialize milestone tracking for tournament announcements."""
# 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]}
def _initializeGameTracking(self):
"""Initialize game tracking data structures."""
# lastgame tracking
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(f"{BOTDIR}/tellmsg.db", writeback=True)
except Exception as e:
# Fallback to older format if .db fails
try:
self.tellbuf = shelve.open(f"{BOTDIR}/tellmsg", writeback=True, protocol=2)
except Exception as e2:
tlog(f"Error: Could not open tell message database: {e2}")
# Create an in-memory fallback so bot doesn't crash
self.tellbuf = DictWithSync()
def _initializeGitHub(self):
"""Initialize GitHub monitoring data structures."""
# For GitHub monitoring
self.seen_github_commits = {} # repo -> set of commit IDs
self.github_initialized = False
self.github_repos = []
if ENABLE_GITHUB and GITHUB_REPOS:
self.github_repos = GITHUB_REPOS
# Initialize seen commits for each repo
for repo_config in self.github_repos:
repo_key = repo_config["repo"]
self.seen_github_commits[repo_key] = set()
# TNNT API monitoring for achievements/trophies/rankings
self.api_initialized = False
self.player_achievements = {} # player -> set of achievement names
self.player_trophies = {} # player -> set of trophy names
self.clan_trophies = {} # clan -> set of trophy names
self.clan_rankings = {} # clan -> rank position
self.player_scores = {} # player -> {wins, total_games, ratio}
self.clan_scores = {} # clan -> {wins, total_games, ratio}
self.recently_cleared_players = set() # Players cleared due to database wipe
def _initializeRateLimiting(self):
"""Initialize rate limiting data structures."""
self.rate_limits = {} # user -> list of command timestamps
self.abuse_penalties = {} # user -> penalty end timestamp
self.consecutive_commands = {} # user -> [command_time, command_time, ...]
self.penalty_responses = {} # user -> [timestamp, timestamp, ...]
self.last_command_time = {} # user -> timestamp of last command
def _initializeCommands(self):
"""Initialize command handlers and callbacks."""
# 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,
"dumplog" : self.doDumplog,
"irclog" : self.doIRClog,
"rcedit" : self.doRCedit,
"commands" : self.doCommands,
"help" : self.doHelp,
"score" : self.doScore,
"clanscore": self.doClanScore,
"clantag" : self.doClanTag,
"status" : self.doStatus,
"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}
def _initializeLogReading(self):
"""Initialize log file reading and seek to appropriate positions."""
# seek to end of livelogs
for filepath in self.livelogs:
try:
with filepath.open("r") as handle:
handle.seek(0, 2)
self.logs_seek[filepath] = handle.tell()
except (IOError, OSError) as e:
tlog(f"Warning: Could not seek to end of livelog {filepath}: {e}")
self.logs_seek[filepath] = 0
# sequentially read xlogfiles from beginning to pre-populate lastgame data.
for filepath in self.xlogfiles:
try:
with filepath.open("r") as handle:
for line in handle:
try:
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
except Exception as e:
tlog("Warning: Error processing xlogfile line during startup: {e}")
continue
self.logs_seek[filepath] = handle.tell()
except (IOError, OSError) as e:
tlog(f"Warning: Could not read xlogfile {filepath}: {e}")
self.logs_seek[filepath] = 0
def _startMonitoringTasks(self):
"""Start periodic monitoring tasks."""
# poll logs for updates
for filepath in self.logs:
self.looping_calls[filepath] = task.LoopingCall(self.logReport, filepath)
self.looping_calls[filepath].start(LOG_POLL_INTERVAL)
# 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(NICK_CHECK_INTERVAL)
# Check GitHub for new commits (every minute)
if not SLAVE and ENABLE_GITHUB and self.github_repos:
self.looping_calls["github"] = task.LoopingCall(self.checkGitHub)
# Add initial delay to ensure bot is fully connected before first check
self.looping_calls["github"].start(60, now=False) # 1 minute interval, don't run immediately
# Schedule TNNT API polling for every 5 minutes at :00:30, :05:30, :10:30, :15:30, etc.
if not SLAVE:
self._scheduleAPIPolling()
# Update local milestone summary to master every 5 minutes
self.looping_calls["summary"] = task.LoopingCall(self.updateSummary)
self.looping_calls["summary"].start(SUMMARY_UPDATE_INTERVAL)
# 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']:
tlog('sasl not available')
self.quit('')
sasl_string = f'{self.nickname}\0{self.nickname}\0{self.password}'
sasl_b64_bytes = base64.b64encode(sasl_string.encode(encoding='UTF-8',errors='strict'))
self.sendLine('AUTHENTICATE PLAIN')
self.sendLine(f'AUTHENTICATE {sasl_b64_bytes.decode("UTF-8")}')
def irc_903(self, prefix, params):
self.sendLine('CAP END')
def irc_904(self, prefix, params):
tlog('sasl auth failed', params)
self.quit('')
irc_905 = irc_904
def _initializeConnection(self):
"""Initialize connection-related settings after signing on."""
self.factory.resetDelay()
self.startHeartbeat()
if not SLAVE:
for c in CHANNELS:
self.join(c)
random.seed()
# Track bot start time for uptime calculation
self.starttime = time.time()
def _initializeLogs(self):
"""Initialize log monitoring configuration."""
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 = {}
def signedOn(self):
self._initializeConnection()
self._initializeLogs()
self._initializeStats()
if not SLAVE:
self._scheduleMasterTasks()
self._initializeMilestones()
self._initializeGameTracking()
self._initializeGitHub()
self._initializeRateLimiting()
self._initializeCommands()
self._initializeLogReading()
self._startMonitoringTasks()
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", f"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] = f"{IRCLOGS}/{c}{time.strftime('-%Y-%m-%d.log')}"
try:
self.chanLog[c] = open(self.chanLogName[c],'a') # 'w' is probably fine here
except (IOError, OSError) as e:
tlog(f"Warning: Could not rotate log file {self.chanLogName[c]}: {e}")
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
# Use pre-compiled regex patterns for better performance
message = RE_COLOR_FG_BG.sub('', msg) # fg,bg pair
message = RE_COLOR_FG.sub('', message) # fg only
message = RE_COLOR_END.sub('', 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(f"{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, f"<{self.nickname}> {message}")
self.msg(replyto, message)
# Similar wrapper for describe
def describeLog(self,replyto, message):
if replyto in CHANNELS:
self.log(f"* {self.nickname} {message}")
self.describe(replyto, message)
# Tournament announcements typically go to the channel
# ...and to the channel log
# spam flag allows more verbosity in some channels
def announce(self, message, spam = False, strict_tournament_time = False, early_start_hours = 0):
if not TEST:
# Check if we should announce based on tournament timing
nowtime = datetime.now()
# Calculate effective start time (may be earlier for clan registrations)
effective_start = self.ttime["start"] - timedelta(hours=early_start_hours)
if strict_tournament_time:
# Strict mode: only during official tournament (no grace period)
# Used for API announcements (achievements, trophies, clan rankings)
# Can start early if early_start_hours is specified (for clan registrations)
game_on = (nowtime > effective_start) and (nowtime < self.ttime["end"])
else:
# Normal mode: tournament plus grace period
# Used for game events (deaths, ascensions)
game_on = (nowtime > effective_start) and (nowtime < (self.ttime["end"] + timedelta(days=GRACEDAYS)))
if not game_on: return
chanlist = CHANNELS
if spam:
chanlist = SPAMCHANNELS #only
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):
try:
if (replyto.lower() == sender.lower()): #private
self.msg(replyto, message)
else: #channel - prepend "Nick: " to message
self.msgLog(replyto, sender + ": " + message)
except Exception as e:
tlog(f"Error sending response to {replyto}: {e}")
def _checkRateLimit(self, sender, command):
"""
Check if user is rate limited for this command.
Returns True if command should be allowed, False if rate limited.
"""
try:
now = time.time()
# Check if user is currently under abuse penalty
if sender in self.abuse_penalties:
if now < self.abuse_penalties[sender]:
return False # Still under penalty
else:
# Penalty expired, clean up
del self.abuse_penalties[sender]
if sender in self.consecutive_commands:
del self.consecutive_commands[sender]
# Clean up old rate limit entries (older than 60 seconds)
if sender in self.rate_limits:
self.rate_limits[sender] = [
timestamp for timestamp in self.rate_limits[sender]
if now - timestamp < RATE_LIMIT_WINDOW
]
# Remove empty entries
if not self.rate_limits[sender]:
del self.rate_limits[sender]
# Initialize user's rate limit tracking if needed
if sender not in self.rate_limits:
self.rate_limits[sender] = []
# Check if user has exceeded rate limit
if len(self.rate_limits[sender]) >= RATE_LIMIT_COMMANDS:
return False # Rate limited
# Record this command attempt
self.rate_limits[sender].append(now)
# Track consecutive commands for abuse detection
if sender not in self.consecutive_commands:
self.consecutive_commands[sender] = []
# Clean up old consecutive command entries
self.consecutive_commands[sender] = [
timestamp for timestamp in self.consecutive_commands[sender]
if now - timestamp < ABUSE_WINDOW
]
# Add this command to consecutive tracking
self.consecutive_commands[sender].append(now)
# Check for abuse pattern
if len(self.consecutive_commands[sender]) >= ABUSE_THRESHOLD:
# Apply abuse penalty
self.abuse_penalties[sender] = now + ABUSE_PENALTY
# Clear rate limits to prevent further commands
if sender in self.rate_limits:
del self.rate_limits[sender]
return False # Apply penalty
return True # Command allowed
except Exception as e:
tlog(f"Rate limiting error for {sender}: {e}")
# Fail-safe: allow command if rate limiting breaks
return True
def _shouldSendPenaltyMessage(self, sender):
"""Check if we should send a rate limit penalty message."""
try:
now = time.time()
# Initialize penalty response tracking if needed
if sender not in self.penalty_responses:
self.penalty_responses[sender] = []
# Clean up old penalty response entries
self.penalty_responses[sender] = [
timestamp for timestamp in self.penalty_responses[sender]
if now - timestamp < RESPONSE_RATE_WINDOW
]
# Check if user has exceeded penalty message rate limit
if len(self.penalty_responses[sender]) >= RESPONSE_RATE_LIMIT:
return False # Don't send penalty message
# Record this penalty response
self.penalty_responses[sender].append(now)
return True # Send penalty message
except Exception as e:
tlog(f"Penalty response rate limiting error for {sender}: {e}")
return True # Fail-safe: allow message
def _checkBurstProtection(self, sender, command):
"""
Check if user is sending commands too rapidly (burst protection).
Returns True if command should be allowed, False if it should be silently ignored.
"""
try:
now = time.time()
# Check last command time
if sender in self.last_command_time:
time_since_last = now - self.last_command_time[sender]
if time_since_last < BURST_WINDOW:
# Too fast - silently ignore
return False
# Update last command time
self.last_command_time[sender] = now
return True
except Exception as e:
tlog(f"Burst protection error for {sender}: {e}")
return True # Fail-safe: allow command
def generate_dumplog_url(self, game, dumpfile):
"""Generate dumplog URL, checking local storage first, then S3.
Returns the URL if file exists in either location, or a sorry message otherwise.
"""
# First check if file exists locally
if os.path.exists(dumpfile):
# File exists locally, use regular URL
dumpurl = urllib.parse.quote(game["dumpfmt"].format(**game))
return self.dump_url_prefix.format(**game) + dumpurl
# File doesn't exist locally - generate S3 URL
# S3 URL structure differs by server