-
Notifications
You must be signed in to change notification settings - Fork 63
/
wolfgame.py
9925 lines (8837 loc) · 420 KB
/
wolfgame.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
# Copyright (c) 2011, Jimmy Cao All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer. 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.
import copy
import fnmatch
import itertools
import math
import os
import platform
import random
import re
import signal
import socket
import sqlite3
import string
import subprocess
import sys
import threading
import time
import traceback
import urllib.request
from collections import defaultdict
from datetime import datetime, timedelta
from oyoyo.parse import parse_nick
import botconfig
import src.settings as var
from src.utilities import *
from src import db, decorators, events, logger, proxy, debuglog, errlog, plog
from src.messages import messages
# done this way so that events is accessible in !eval (useful for debugging)
Event = events.Event
cmd = decorators.cmd
hook = decorators.hook
handle_error = decorators.handle_error
COMMANDS = decorators.COMMANDS
# Game Logic Begins:
var.LAST_STATS = None
var.LAST_VOTES = None
var.LAST_ADMINS = None
var.LAST_GSTATS = None
var.LAST_PSTATS = None
var.LAST_TIME = None
var.LAST_START = {}
var.LAST_WAIT = {}
var.USERS = {}
var.ADMIN_PINGING = False
var.SPECIAL_ROLES = {}
var.ORIGINAL_ROLES = {}
var.PLAYERS = {}
var.DCED_PLAYERS = {}
var.ADMIN_TO_PING = None
var.AFTER_FLASTGAME = None
var.PINGING_IFS = False
var.TIMERS = {}
var.ORIGINAL_SETTINGS = {}
var.CURRENT_GAMEMODE = var.GAME_MODES["default"][0]()
var.LAST_SAID_TIME = {}
var.GAME_START_TIME = datetime.now() # for idle checker only
var.CAN_START_TIME = 0
var.STARTED_DAY_PLAYERS = 0
var.DISCONNECTED = {} # players who got disconnected
var.RESTARTING = False
var.OPPED = False # Keeps track of whether the bot is opped
var.BITTEN_ROLES = {}
var.LYCAN_ROLES = {}
var.VENGEFUL_GHOSTS = {}
var.CHARMED = set()
if botconfig.DEBUG_MODE and var.DISABLE_DEBUG_MODE_TIMERS:
var.NIGHT_TIME_LIMIT = 0 # 120
var.NIGHT_TIME_WARN = 0 # 90
var.DAY_TIME_LIMIT = 0 # 720
var.DAY_TIME_WARN = 0 # 600
var.SHORT_DAY_LIMIT = 0 # 520
var.SHORT_DAY_WARN = 0 # 400
if botconfig.DEBUG_MODE and var.DISABLE_DEBUG_MODE_REAPER:
var.KILL_IDLE_TIME = 0 # 300
var.WARN_IDLE_TIME = 0 # 180
var.PM_WARN_IDLE_TIME = 0 # 240
var.JOIN_TIME_LIMIT = 0 # 3600
if botconfig.DEBUG_MODE and var.DISABLE_DEBUG_MODE_STASIS:
var.LEAVE_PENALTY = 0
var.IDLE_PENALTY = 0
var.PART_PENALTY = 0
var.ACC_PENALTY = 0
if botconfig.DEBUG_MODE and var.DISABLE_DEBUG_MODE_TIME_LORD:
var.TIME_LORD_DAY_LIMIT = 0 # 60
var.TIME_LORD_DAY_WARN = 0 # 45
var.TIME_LORD_NIGHT_LIMIT = 0 # 30
var.TIME_LORD_NIGHT_WARN = 0 # 20
plog("Loading Werewolf IRC bot")
def connect_callback(cli):
db.init_vars()
SIGUSR1 = getattr(signal, "SIGUSR1", None)
SIGUSR2 = getattr(signal, "SIGUSR2", None)
def sighandler(signum, frame):
if signum == signal.SIGINT:
# Exit immediately if Ctrl-C is pressed twice
signal.signal(signal.SIGINT, signal.SIG_DFL)
if signum in (signal.SIGINT, signal.SIGTERM):
forced_exit.func(cli, "<console>", botconfig.CHANNEL, "")
elif signum == SIGUSR1:
restart_program.func(cli, "<console>", botconfig.CHANNEL, "")
elif signum == SIGUSR2:
plog("Scheduling aftergame restart")
aftergame.func(cli, "<console>", botconfig.CHANNEL, "frestart")
signal.signal(signal.SIGINT, sighandler)
signal.signal(signal.SIGTERM, sighandler)
if SIGUSR1:
signal.signal(SIGUSR1, sighandler)
if SIGUSR2:
signal.signal(SIGUSR2, sighandler)
to_be_devoiced = []
cmodes = []
@hook("quietlist", hookid=294)
def on_quietlist(cli, server, botnick, channel, q, quieted, by, something):
if re.search(r"^{0}.+\!\*@\*$".format(var.QUIET_PREFIX), quieted): # only unquiet people quieted by bot
cmodes.append(("-{0}".format(var.QUIET_MODE), quieted))
@hook("banlist", hookid=294)
def on_banlist(cli, server, botnick, channel, ban, by, timestamp):
if re.search(r"^{0}.+\!\*@\*$".format(var.QUIET_PREFIX), ban):
cmodes.append(("-{0}".format(var.QUIET_MODE), ban))
@hook("whoreply", hookid=295)
def on_whoreply(cli, svr, botnick, chan, user, host, server, nick, status, rest):
if not var.DISABLE_ACCOUNTS:
plog("IRCd does not support accounts, disabling account-related features.")
var.DISABLE_ACCOUNTS = True
var.ACCOUNTS_ONLY = False
if nick in var.USERS:
return
if nick == botconfig.NICK:
cli.nickname = nick
cli.ident = user
cli.hostmask = host
if "+" in status:
to_be_devoiced.append(user)
newstat = ""
for stat in status:
if not stat in var.MODES_PREFIXES:
continue
newstat += var.MODES_PREFIXES[stat]
var.USERS[nick] = dict(ident=user,host=host,account="*",inchan=True,modes=set(newstat),moded=set())
@hook("whospcrpl", hookid=295)
def on_whoreply(cli, server, nick, ident, host, _, user, status, acc):
if user in var.USERS: return # Don't add someone who is already there
if user == botconfig.NICK:
cli.nickname = user
cli.ident = ident
cli.hostmask = host
if acc == "0":
acc = "*"
if "+" in status:
to_be_devoiced.append(user)
newstat = ""
for stat in status:
if not stat in var.MODES_PREFIXES:
continue
newstat += var.MODES_PREFIXES[stat]
var.USERS[user] = dict(ident=ident,host=host,account=acc,inchan=True,modes=set(newstat),moded=set())
@hook("endofwho", hookid=295)
def afterwho(*args):
# Devoice all on connect
for nick in to_be_devoiced:
cmodes.append(("-v", nick))
# If the bot was restarted in the middle of the join phase, ping players that were joined.
players = db.get_pre_restart_state()
if players:
msg = "PING! " + break_long_message(players).replace("\n", "\nPING! ")
cli.msg(botconfig.CHANNEL, msg)
# Unhook the WHO hooks
hook.unhook(295)
#bot can be tricked into thinking it's still opped by doing multiple modes at once
@hook("mode", hookid=296)
def on_give_me_ops(cli, nick, chan, modeaction, target="", *other):
if chan != botconfig.CHANNEL:
return
if modeaction == "+o" and target == botconfig.NICK:
var.OPPED = True
if botconfig.NICK in var.USERS:
var.USERS[botconfig.NICK]["modes"].add("o")
if var.PHASE == "none":
@hook("quietlistend", hookid=297)
def on_quietlist_end(cli, svr, nick, chan, *etc):
if chan == botconfig.CHANNEL:
mass_mode(cli, cmodes, ["-m"])
@hook("endofbanlist", hookid=297)
def on_banlist_end(cli, svr, nick, chan, *etc):
if chan == botconfig.CHANNEL:
mass_mode(cli, cmodes, ["-m"])
cli.mode(botconfig.CHANNEL, var.QUIET_MODE) # unquiet all
elif modeaction == "-o" and target == botconfig.NICK:
var.OPPED = False
if var.CHANSERV_OP_COMMAND:
cli.msg(var.CHANSERV, var.CHANSERV_OP_COMMAND.format(channel=botconfig.CHANNEL))
if var.DISABLE_ACCOUNTS:
cli.who(botconfig.CHANNEL)
else:
cli.who(botconfig.CHANNEL, "%uhsnfa")
@hook("mode")
def check_for_modes(cli, rnick, chan, modeaction, *target):
nick = parse_nick(rnick)[0]
if chan != botconfig.CHANNEL:
return
oldpref = ""
trgt = ""
keeptrg = False
target = list(target)
if target and target != [botconfig.NICK]:
while modeaction:
if len(modeaction) > 1:
prefix = modeaction[0]
change = modeaction[1]
else:
prefix = oldpref
change = modeaction[0]
if not keeptrg:
if target:
trgt = target.pop(0)
else:
trgt = "" # Last item, no target
keeptrg = False
if not prefix in ("-", "+"):
change = prefix
prefix = oldpref
else:
oldpref = prefix
modeaction = modeaction[modeaction.index(change)+1:]
if change in var.MODES_NOSET:
keeptrg = True
if prefix == "-" and change in var.MODES_ONLYSET:
keeptrg = True
if change not in var.MODES_PREFIXES.values():
continue
if trgt in var.USERS:
if prefix == "+":
var.USERS[trgt]["modes"].add(change)
if change in var.USERS[trgt]["moded"]:
var.USERS[trgt]["moded"].remove(change)
elif change in var.USERS[trgt]["modes"]:
var.USERS[trgt]["modes"].remove(change)
# Only sync modes if a server changed modes because
# 1) human ops probably know better
# 2) other bots might start a fight over modes
# 3) recursion; we see our own mode changes.
if "!" not in rnick:
sync_modes(cli)
#completes a partial nickname or string from a list
def complete_match(string, matches):
num_matches = 0
bestmatch = string
for possible in matches:
if string == possible:
return string, 1
if possible.startswith(string) or possible.lstrip("[{\\^_`|}]").startswith(string):
bestmatch = possible
num_matches += 1
if num_matches != 1:
return None, num_matches
else:
return bestmatch, 1
#wrapper around complete_match() used for roles
def get_victim(cli, nick, victim, in_chan, self_in_list=False, bot_in_list=False):
chan = botconfig.CHANNEL if in_chan else nick
if not victim:
reply(cli, nick, chan, messages["not_enough_parameters"], private=True)
return
pl = [x for x in list_players() if x != nick or self_in_list]
pll = [x.lower() for x in pl]
if bot_in_list: # for villagergame
pl.append(botconfig.NICK)
pll.append(botconfig.NICK.lower())
tempvictim, num_matches = complete_match(victim.lower(), pll)
if not tempvictim:
#ensure messages about not being able to act on yourself work
if num_matches == 0 and nick.lower().startswith(victim.lower()):
return nick
reply(cli, nick, chan, messages["not_playing"].format(victim), private=True)
return
return pl[pll.index(tempvictim)] #convert back to normal casing
# wrapper around complete_match() used for any nick on the channel
def get_nick(cli, nick):
ul = [x for x in var.USERS]
ull = [x.lower() for x in var.USERS]
lnick, num_matches = complete_match(nick.lower(), ull)
if not lnick:
return None
return ul[ull.index(lnick)]
def get_roles(*roles):
all_roles = []
for role in roles:
all_roles.append(var.ROLES[role])
return list(itertools.chain(*all_roles))
def reset_settings():
var.CURRENT_GAMEMODE.teardown()
var.CURRENT_GAMEMODE = var.GAME_MODES["default"][0]()
for attr in list(var.ORIGINAL_SETTINGS.keys()):
setattr(var, attr, var.ORIGINAL_SETTINGS[attr])
var.ORIGINAL_SETTINGS.clear()
def reset_modes_timers(cli):
# Reset game timers
with var.WARNING_LOCK: # make sure it isn't being used by the ping join handler
for x, timr in var.TIMERS.items():
timr[0].cancel()
var.TIMERS = {}
# Reset modes
cmodes = []
for plr in list_players():
cmodes.append(("-v", plr))
if var.AUTO_TOGGLE_MODES:
for plr in var.USERS:
if not "moded" in var.USERS[plr]:
continue
for mode in var.USERS[plr]["moded"]:
cmodes.append(("+"+mode, plr))
var.USERS[plr]["modes"].update(var.USERS[plr]["moded"])
var.USERS[plr]["moded"] = set()
if var.QUIET_DEAD_PLAYERS:
for deadguy in var.DEAD:
if not is_fake_nick(deadguy):
cmodes.append(("-{0}".format(var.QUIET_MODE), var.QUIET_PREFIX+deadguy+"!*@*"))
mass_mode(cli, cmodes, ["-m"])
def reset():
var.PHASE = "none" # "join", "day", or "night"
var.GAME_ID = 0
var.RESTART_TRIES = 0
var.DEAD = set()
var.ROLES = {"person" : set()}
var.ALL_PLAYERS = []
var.JOINED_THIS_GAME = set() # keeps track of who already joined this game at least once (hostmasks)
var.JOINED_THIS_GAME_ACCS = set() # same, except accounts
var.PINGED_ALREADY = set()
var.PINGED_ALREADY_ACCS = set()
var.NO_LYNCH = set()
var.FGAMED = False
var.GAMEMODE_VOTES = {} #list of players who have used !game
var.START_VOTES = set() # list of players who have voted to !start
var.LOVERS = {} # need to be here for purposes of random
var.ENTRANCED = set()
var.WILD_CHILDREN = set()
reset_settings()
var.LAST_SAID_TIME.clear()
var.PLAYERS.clear()
var.DCED_PLAYERS.clear()
var.DISCONNECTED.clear()
var.SPECTATING_WOLFCHAT = set()
var.SPECTATING_DEADCHAT = set()
reset()
@cmd("fsync", flag="m", pm=True)
def fsync(cli, nick, chan, rest):
"""Makes the bot apply the currently appropriate channel modes."""
sync_modes(cli)
def sync_modes(cli):
voices = []
pl = list_players()
for nick, u in var.USERS.items():
if nick in pl and "v" not in u.get("modes", set()):
voices.append(("+v", nick))
elif nick not in pl and "v" in u.get("modes", set()):
voices.append(("-v", nick))
if var.PHASE in var.GAME_PHASES:
other = ["+m"]
else:
other = ["-m"]
mass_mode(cli, voices, other)
@cmd("refreshdb", flag="m", pm=True)
def refreshdb(cli, nick, chan, rest):
"""Updates our tracking vars to the current db state."""
db.init_vars()
reply(cli, nick, chan, "Done.")
@cmd("fdie", "fbye", flag="D", pm=True)
def forced_exit(cli, nick, chan, rest):
"""Forces the bot to close."""
args = rest.split()
if args and args[0] == "-dirty":
# use as a last resort
os.abort()
elif botconfig.DEBUG_MODE or (args and args[0] == "-force"):
force = True
rest = " ".join(args[1:])
else:
force = False
if var.PHASE in var.GAME_PHASES:
if var.PHASE == "join" or force or nick == "<console>":
stop_game(cli, log=False)
else:
reply(cli, nick, chan, messages["stop_bot_ingame_safeguard"].format(
what="stop", cmd="fdie", prefix=botconfig.CMD_CHAR), private=True)
return
reset_modes_timers(cli)
reset()
msg = "{0} quit from {1}"
if rest.strip():
msg += " ({2})"
try:
cli.quit(msg.format("Scheduled" if forced_exit.aftergame else "Forced",
nick,
rest.strip()))
except Exception:
# bot may have quit by this point, so can't use regular handler
# the operator should see this on console anyway even though it isn't logged
traceback.print_exc()
sys.exit()
finally:
cli.socket.close() # in case it didn't close, force it to
def _restart_program(cli, mode=None):
plog("RESTARTING")
python = sys.executable
if mode:
assert mode in ("normal", "verbose", "debug")
os.execl(python, python, sys.argv[0], "--{0}".format(mode))
else:
os.execl(python, python, *sys.argv)
@cmd("frestart", flag="D", pm=True)
def restart_program(cli, nick, chan, rest):
"""Restarts the bot."""
args = rest.split()
if botconfig.DEBUG_MODE or (args and args[0] == "-force"):
force = True
rest = " ".join(args[1:])
else:
force = False
if var.PHASE in var.GAME_PHASES:
if var.PHASE == "join" or force:
stop_game(cli, log=False)
else:
reply(cli, nick, chan, messages["stop_bot_ingame_safeguard"].format(
what="restart", cmd="frestart", prefix=botconfig.CMD_CHAR), private=True)
return
reset_modes_timers(cli)
db.set_pre_restart_state(list_players())
reset()
msg = "{0} restart from {1}".format(
"Scheduled" if restart_program.aftergame else "Forced", nick)
rest = rest.strip()
mode = None
if rest:
args = rest.split()
first_arg = args[0].lower()
if first_arg.endswith("mode") and first_arg != "mode":
mode = first_arg.replace("mode", "")
VALID_MODES = ("normal", "verbose", "debug")
if mode not in VALID_MODES:
err_msg = messages["invalid_mode"].format(mode, ", ".join(VALID_MODES))
reply(cli, nick, chan, err_msg, private=True)
return
msg += " in {0} mode".format(mode)
rest = " ".join(args[1:])
if rest:
msg += " ({0})".format(rest)
cli.quit(msg.format(nick, rest.strip()))
@hook("quit")
def restart_buffer(cli, raw_nick, reason):
nick, _, __, host = parse_nick(raw_nick)
# restart the bot once our quit message goes though to ensure entire IRC queue is sent
# if the bot is using a nick that isn't botconfig.NICK, then stop breaking things and fdie
try:
if nick == botconfig.NICK:
_restart_program(cli, mode)
finally:
cli.socket.close()
# This is checked in the on_error handler. Some IRCds, such as InspIRCd, don't send the bot
# its own QUIT message, so we need to use ERROR. Ideally, we shouldn't even need the above
# handler now, but I'm keeping it for now just in case.
var.RESTARTING = True
@cmd("ping", pm=True)
def pinger(cli, nick, chan, rest):
"""Check if you or the bot is still connected."""
reply(cli, nick, chan, random.choice(messages["ping"]).format(
nick=nick,
bot_nick=botconfig.NICK,
cmd_char=botconfig.CMD_CHAR,
goat_action=random.choice(messages["goat_actions"])))
@cmd("simple", raw_nick=True, pm=True)
def mark_simple_notify(cli, nick, chan, rest):
"""Makes the bot give you simple role instructions, in case you are familiar with the roles."""
nick, _, ident, host = parse_nick(nick)
if nick in var.USERS:
ident = irc_lower(var.USERS[nick]["ident"])
host = var.USERS[nick]["host"].lower()
acc = irc_lower(var.USERS[nick]["account"])
else:
acc = None
if not acc or acc == "*":
acc = None
if acc: # Prioritize account
if acc in var.SIMPLE_NOTIFY_ACCS:
var.SIMPLE_NOTIFY_ACCS.remove(acc)
db.toggle_simple(acc, None)
if host in var.SIMPLE_NOTIFY:
var.SIMPLE_NOTIFY.remove(host)
db.toggle_simple(None, host)
fullmask = ident + "@" + host
if fullmask in var.SIMPLE_NOTIFY:
var.SIMPLE_NOTIFY.remove(fullmask)
db.toggle_simple(None, fullmask)
reply(cli, nick, chan, messages["simple_off"], private=True)
return
var.SIMPLE_NOTIFY_ACCS.add(acc)
db.toggle_simple(acc, None)
elif var.ACCOUNTS_ONLY:
reply(cli, nick, chan, messages["not_logged_in"], private=True)
return
else: # Not logged in, fall back to ident@hostmask
if host in var.SIMPLE_NOTIFY:
var.SIMPLE_NOTIFY.remove(host)
db.toggle_simple(None, host)
reply(cli, nick, chan, messages["simple_off"], private=True)
return
fullmask = ident + "@" + host
if fullmask in var.SIMPLE_NOTIFY:
var.SIMPLE_NOTIFY.remove(fullmask)
db.toggle_simple(None, fullmask)
reply(cli, nick, chan, messages["simple_off"], private=True)
return
var.SIMPLE_NOTIFY.add(fullmask)
db.toggle_simple(None, fullmask)
reply(cli, nick, chan, messages["simple_on"], private=True)
@cmd("notice", raw_nick=True, pm=True)
def mark_prefer_notice(cli, nick, chan, rest):
"""Makes the bot NOTICE you for every interaction."""
nick, _, ident, host = parse_nick(nick)
if chan == nick and rest:
# Ignore if called in PM with parameters, likely a message to wolfchat
# and not an intentional invocation of this command
return
if nick in var.USERS:
ident = irc_lower(var.USERS[nick]["ident"])
host = var.USERS[nick]["host"].lower()
acc = irc_lower(var.USERS[nick]["account"])
else:
acc = None
if not acc or acc == "*":
acc = None
if acc and not var.DISABLE_ACCOUNTS: # Do things by account if logged in
if acc in var.PREFER_NOTICE_ACCS:
var.PREFER_NOTICE_ACCS.remove(acc)
db.toggle_notice(acc, None)
if host in var.PREFER_NOTICE:
var.PREFER_NOTICE.remove(host)
db.toggle_notice(None, host)
fullmask = ident + "@" + host
if fullmask in var.PREFER_NOTICE:
var.PREFER_NOTICE.remove(fullmask)
db.toggle_notice(None, fullmask)
reply(cli, nick, chan, messages["notice_off"], private=True)
return
var.PREFER_NOTICE_ACCS.add(acc)
db.toggle_notice(acc, None)
elif var.ACCOUNTS_ONLY:
reply(cli, nick, chan, messages["not_logged_in"], private=True)
return
else: # Not logged in
if host in var.PREFER_NOTICE:
var.PREFER_NOTICE.remove(host)
db.toggle_notice(None, host)
reply(cli, nick, chan, messages["notice_off"], private=True)
return
fullmask = ident + "@" + host
if fullmask in var.PREFER_NOTICE:
var.PREFER_NOTICE.remove(fullmask)
db.toggle_notice(None, fullmask)
reply(cli, nick, chan, messages["notice_off"], private=True)
return
var.PREFER_NOTICE.add(fullmask)
db.toggle_notice(None, fullmask)
reply(cli, nick, chan, messages["notice_on"], private=True)
@cmd("swap", "replace", pm=True, phases=("join", "day", "night"))
def replace(cli, nick, chan, rest):
"""Swap out a player logged in to your account."""
if nick not in var.USERS or not var.USERS[nick]["inchan"]:
pm(cli, nick, messages["invalid_channel"].format(botconfig.CHANNEL))
return
if nick in list_players():
reply(cli, nick, chan, messages["already_playing"].format("You"), private=True)
return
account = irc_lower(var.USERS[nick]["account"])
if not account or account == "*":
reply(cli, nick, chan, messages["not_logged_in"], private=True)
return
rest = rest.split()
if not rest: # bare call
target = None
for user in var.USERS:
if irc_lower(var.USERS[user]["account"]) == account:
if user == nick or (user not in list_players() and user not in var.VENGEFUL_GHOSTS):
pass
elif target is None:
target = user
else:
reply(cli, nick, chan, messages["swap_notice"].format(botconfig.CMD_CHAR), private=True)
return
if target is None:
msg = messages["account_not_playing"]
reply(cli, nick, chan, msg, private=True)
return
else:
pl = list_players() + list(var.VENGEFUL_GHOSTS.keys())
pll = [irc_lower(i) for i in pl]
target, _ = complete_match(irc_lower(rest[0]), pll)
if target is not None:
target = pl[pll.index(target)]
if (target not in list_players() and target not in var.VENGEFUL_GHOSTS) or target not in var.USERS:
msg = messages["target_not_playing"].format(" longer" if target in var.DEAD else "t")
reply(cli, nick, chan, msg, private=True)
return
if var.USERS[target]["account"] == "*":
reply(cli, nick, chan, messages["target_not_logged_in"], private=True)
return
if irc_lower(var.USERS[target]["account"]) == account and nick != target:
rename_player(cli, target, nick)
# Make sure to remove player from var.DISCONNECTED if they were in there
if var.PHASE in var.GAME_PHASES:
return_to_village(cli, chan, target, False)
mass_mode(cli, [("-v", target), ("+v", nick)], [])
cli.msg(botconfig.CHANNEL, messages["player_swap"].format(nick, target))
myrole.caller(cli, nick, chan, "")
@cmd("pingif", "pingme", "pingat", "pingpref", pm=True)
def altpinger(cli, nick, chan, rest):
"""Pings you when the number of players reaches your preference. Usage: "pingif <players>". https://github.com/lykoss/lykos/wiki/Pingif"""
players = is_user_altpinged(nick)
rest = rest.split()
if nick in var.USERS:
acc = irc_lower(var.USERS[nick]["account"])
else:
reply(cli, nick, chan, messages["invalid_channel"].format(botconfig.CHANNEL), private=True)
return
if (not acc or acc == "*") and var.ACCOUNTS_ONLY:
reply(cli, nick, chan, messages["not_logged_in"], private=True)
return
msg = []
if not rest:
if players:
msg.append(messages["get_pingif"].format(players))
else:
msg.append(messages["no_pingif"])
elif any((rest[0] in ("off", "never"),
rest[0].isdigit() and int(rest[0]) == 0,
len(rest) > 1 and rest[1].isdigit() and int(rest[1]) == 0)):
if players:
msg.append(messages["unset_pingif"].format(players))
toggle_altpinged_status(nick, 0, players)
else:
msg.append(messages["no_pingif"])
elif rest[0].isdigit() or (len(rest) > 1 and rest[1].isdigit()):
if rest[0].isdigit():
num = int(rest[0])
else:
num = int(rest[1])
if num > 999:
msg.append(messages["pingif_too_large"])
elif players == num:
msg.append(messages["pingif_already_set"].format(num))
elif players:
msg.append(messages["pingif_change"].format(players, num))
toggle_altpinged_status(nick, num, players)
else:
msg.append(messages["set_pingif"].format(num))
toggle_altpinged_status(nick, num)
else:
msg.append(messages["pingif_invalid"])
reply(cli, nick, chan, "\n".join(msg), private=True)
def is_user_altpinged(nick):
if nick in var.USERS.keys():
ident = irc_lower(var.USERS[nick]["ident"])
host = var.USERS[nick]["host"].lower()
acc = irc_lower(var.USERS[nick]["account"])
else:
return 0
if not var.DISABLE_ACCOUNTS and acc and acc != "*":
if acc in var.PING_IF_PREFS_ACCS.keys():
return var.PING_IF_PREFS_ACCS[acc]
elif not var.ACCOUNTS_ONLY:
for hostmask, pref in var.PING_IF_PREFS.items():
if match_hostmask(hostmask, nick, ident, host):
return pref
return 0
def toggle_altpinged_status(nick, value, old=None):
# nick should be in var.USERS if not fake; if not, let the error propagate
ident = irc_lower(var.USERS[nick]["ident"])
host = var.USERS[nick]["host"].lower()
acc = irc_lower(var.USERS[nick]["account"])
if value == 0:
if not var.DISABLE_ACCOUNTS and acc and acc != "*":
if acc in var.PING_IF_PREFS_ACCS:
del var.PING_IF_PREFS_ACCS[acc]
db.set_pingif(0, acc, None)
if old is not None:
with var.WARNING_LOCK:
if old in var.PING_IF_NUMS_ACCS:
var.PING_IF_NUMS_ACCS[old].discard(acc)
if not var.ACCOUNTS_ONLY:
for hostmask in list(var.PING_IF_PREFS.keys()):
if match_hostmask(hostmask, nick, ident, host):
del var.PING_IF_PREFS[hostmask]
db.set_pingif(0, None, hostmask)
if old is not None:
with var.WARNING_LOCK:
if old in var.PING_IF_NUMS.keys():
var.PING_IF_NUMS[old].discard(host)
var.PING_IF_NUMS[old].discard(hostmask)
else:
if not var.DISABLE_ACCOUNTS and acc and acc != "*":
var.PING_IF_PREFS_ACCS[acc] = value
db.set_pingif(value, acc, None)
with var.WARNING_LOCK:
if value not in var.PING_IF_NUMS_ACCS:
var.PING_IF_NUMS_ACCS[value] = set()
var.PING_IF_NUMS_ACCS[value].add(acc)
if old is not None:
if old in var.PING_IF_NUMS_ACCS:
var.PING_IF_NUMS_ACCS[old].discard(acc)
elif not var.ACCOUNTS_ONLY:
hostmask = ident + "@" + host
var.PING_IF_PREFS[hostmask] = value
db.set_pingif(value, None, hostmask)
with var.WARNING_LOCK:
if value not in var.PING_IF_NUMS.keys():
var.PING_IF_NUMS[value] = set()
var.PING_IF_NUMS[value].add(hostmask)
if old is not None:
if old in var.PING_IF_NUMS.keys():
var.PING_IF_NUMS[old].discard(host)
var.PING_IF_NUMS[old].discard(hostmask)
@handle_error
def join_timer_handler(cli):
with var.WARNING_LOCK:
var.PINGING_IFS = True
to_ping = []
pl = list_players()
checker = set()
chk_acc = set()
# Add accounts/hosts to the list of possible players to ping
if not var.DISABLE_ACCOUNTS:
for num in var.PING_IF_NUMS_ACCS:
if num <= len(pl):
chk_acc.update(var.PING_IF_NUMS_ACCS[num])
if not var.ACCOUNTS_ONLY:
for num in var.PING_IF_NUMS:
if num <= len(pl):
checker.update(var.PING_IF_NUMS[num])
# Don't ping alt connections of users that have already joined
if not var.DISABLE_ACCOUNTS:
for acc in (var.USERS[player]["account"] for player in pl if player in var.USERS):
var.PINGED_ALREADY_ACCS.add(irc_lower(acc))
# Remove players who have already been pinged from the list of possible players to ping
for acc in frozenset(chk_acc):
if acc in var.PINGED_ALREADY_ACCS:
chk_acc.remove(acc)
for hostmask in frozenset(checker):
if hostmask in var.PINGED_ALREADY:
checker.remove(hostmask)
# If there is nobody to ping, do nothing
if not chk_acc and not checker:
var.PINGING_IFS = False
return
@hook("whoreply", hookid=387)
def ping_altpingers_noacc(cli, svr, botnick, chan, ident, host, server, nick, status, rest):
if ("G" in status or is_user_stasised(nick) or not var.PINGING_IFS or
nick == botnick or nick in pl):
return
ident = irc_lower(ident)
host = host.lower()
hostmask = ident + "@" + host
if hostmask in checker:
to_ping.append(nick)
var.PINGED_ALREADY.add(hostmask)
@hook("whospcrpl", hookid=387)
def ping_altpingers(cli, server, nick, ident, host, _, user, status, acc):
if ("G" in status or is_user_stasised(user) or not var.PINGING_IFS or
user == botconfig.NICK or user in pl):
return
# Create list of players to ping
acc = irc_lower(acc)
ident = irc_lower(ident)
host = host.lower()
if acc and acc != "*":
if acc in chk_acc:
to_ping.append(user)
var.PINGED_ALREADY_ACCS.add(acc)
elif not var.ACCOUNTS_ONLY:
hostmask = ident + "@" + host
to_ping.append(user)
var.PINGED_ALREADY.add(hostmask)
@hook("endofwho", hookid=387)
def fetch_altpingers(*stuff):
# fun fact: if someone joined 10 seconds after someone else, the bot would break.
# effectively, the join would delete join_pinger from var.TIMERS and this function
# here would be reached before it was created again, thus erroring and crashing.
# this is one of the multiple reasons we need unit testing
# I was lucky to catch this in testing, as it requires precise timing
# it only failed if a join happened while this outer func had started
var.PINGING_IFS = False
hook.unhook(387)
if to_ping:
to_ping.sort(key=lambda x: x.lower())
msg_prefix = messages["ping_player"].format(len(pl), "" if len(pl) == 1 else "s")
msg = msg_prefix + break_long_message(to_ping).replace("\n", "\n" + msg_prefix)
cli.msg(botconfig.CHANNEL, msg)
if not var.DISABLE_ACCOUNTS:
cli.who(botconfig.CHANNEL, "%uhsnfa")
else:
cli.who(botconfig.CHANNEL)
def get_deadchat_pref(nick):
if nick in var.USERS:
host = var.USERS[nick]["host"].lower()
acc = irc_lower(var.USERS[nick]["account"])
else:
return False
if acc in var.DEADCHAT_PREFS_ACCS:
return False
elif var.ACCOUNTS_ONLY:
return True
elif host in var.DEADCHAT_PREFS:
return False
return True
def join_deadchat(cli, *all_nicks):
if not var.ENABLE_DEADCHAT:
return
if var.PHASE not in ("day", "night"):