This repository has been archived by the owner on Mar 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Mafia.py
1082 lines (866 loc) · 38.7 KB
/
Mafia.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/pyton3
import datetime
import functools
import json
import os
import math
import mysql.connector
import mysql.connector.pooling
import pickle
import praw
import random
import re
import schedule
import signal
import sys
import time
import traceback
from mysql.connector import errorcode
from mysql.connector.cursor import MySQLCursorPrepared
from random import randrange
from time import sleep
exceptCnt = 0
state = None
curCycle = None
def main():
global exceptCnt
global state
global curCycle
with open('init/statements.json') as jsonFile1:
stm = json.load(jsonFile1)
with open('data/save.json') as jsonFile2:
sve = json.load(jsonFile2)
with open('data/settings.json') as jsonFile3:
cfg = json.load(jsonFile3)
exceptCnt = 0
state = sve['state']
curCycle = sve['curCycle']
reddit = praw.Reddit(cfg['reddit']['praw'])
sub = reddit.subreddit(cfg['reddit']['sub'])
commentStream = sub.stream.comments(skip_existing=True,pause_after=-1)
inboxStream = reddit.inbox.stream(pause_after=-1)
db = mysql.connector.pooling.MySQLConnectionPool(pool_name=None, raise_on_warnings=True, connection_timeout=3600, **cfg['sql'])
pool = db.get_connection()
con = pool.cursor(prepared=True)
idCache = []
itemCache = {}
lastCmd = ''
def log_commit(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
username = '*SELF*'
command = '!CYCLE'
utc = time.time();
try:
if (item != None):
username = item.author.name
command = item.body
utc = item.created_utc
result = func(*args, **kwargs)
pattern = re.search(r'^![\w]{1,}\s([\w\d_\-\s/]+)', command)
readable = time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(utc))
action = ''
if (result == -1):
action += 'FAILED '
if pattern:
action += f'{func.__name__} - {pattern.group(1)}'
else:
action += f'{func.__name__}'
con.execute(stm['preStm']['log'], (utc, username, action))
con.execute('COMMIT;')
print(f'[{readable}] {username}: {action}')
except mysql.connector.Error as e:
print(f'SQL EXCEPTION @ {func.__name__} : {args} - {kwargs}\n{e}')
con.close()
os._exit(-1)
return result
return wrapper
def game_command(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
pattern = re.search(r'^!([a-z]{4,})\s(?:u/)?([\w\d_\-]+)\s?$', item.body)
search = ''
if (state == 0):
item.reply(stm['err']['notStarted'])
return -1
if (func.__name__ != 'burnUser'):
if pattern:
search = pattern.group(2)
else:
item.reply(stm['err']['impFmt'])
return -1
try:
con.execute(stm['preStm']['chkUsr'], (item.author.name,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['spec'])
return -1
con.execute(stm['preStm']['chkCmt'], (item.author.name, cfg['commands']['useThreshold']))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['noParticipate'])
return -1
if ((func.__name__ != 'unlockTier') and (func.__name__ != 'burnUser')):
con.execute(stm['preStm']['digupUser'], (search,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['notFound'])
return -1
result = func(*args, **kwargs)
except mysql.connector.Error as e:
print(f'SQL EXCEPTION @ {func.__name__} : {args} - {kwargs}\n{e}')
con.close()
os._exit(-1)
return result
return wrapper
def schdWarn(min=00):
if (state != 1):
return -1
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['schdWarn'].format(min))
print(f'Cycle Warning {min}')
def autoCycle():
global curCycle
if (state != 1):
return -1
with open('data/save.json') as jsonFile2:
sve = json.load(jsonFile2)
cycle()
print(f'Auto Cycle {curCycle}')
def scheduleJobs():
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] - 1).zfill(2)}:30').do(schdWarn,min=30)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] - 1).zfill(2)}:45').do(schdWarn,min=15)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] - 1).zfill(2)}:55').do(schdWarn,min=5)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"]).zfill(2)}:00').do(autoCycle)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] - 1).zfill(2)}:30').do(schdWarn,min=30)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] - 1).zfill(2)}:45').do(schdWarn,min=15)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] - 1).zfill(2)}:55').do(schdWarn,min=5)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"]).zfill(2)}:00').do(autoCycle)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] - 1 + 12).zfill(2)}:30').do(schdWarn,min=30)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] - 1 + 12).zfill(2)}:45').do(schdWarn,min=15)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] - 1 + 12).zfill(2)}:55').do(schdWarn,min=5)
schedule.every().day.at(f'{str(cfg["clock"]["hour1"] + 12).zfill(2)}:00').do(autoCycle)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] - 1 + 12).zfill(2)}:30').do(schdWarn,min=30)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] - 1 + 12).zfill(2)}:45').do(schdWarn,min=15)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] - 1 + 12).zfill(2)}:55').do(schdWarn,min=5)
schedule.every().day.at(f'{str(cfg["clock"]["hour2"] + 12).zfill(2)}:00').do(autoCycle)
schedule.every(2).to(5).hours.do(makeComment)
schedule.every(4).hours.do(refreshConnection)
print("Jobs Scheduled")
@log_commit
def gameState(state):
global curCycle
pattern = re.search(r'^!GAMESTATE\s([0-9]{1,1})(\s-[sS])?', item.body)
setState = int(pattern.group(1))
silent = pattern.group(2)
if (item.author.name not in cfg['adminUsr']):
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'ATTEMPTED ADMIN COMMAND: gameState'))
return -1
else:
if ((setState == 0) and (silent == None)):
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['pause'])
comment.mod.distinguish(how='yes', sticky=True)
elif ((setState == 1) and (silent == None)):
gameStart()
elif ((setState == 2) and (silent == None)):
gameEnd()
if (item.author.name != '*SELF*'): item.reply(f'**gamestate changed to {setState}**')
save(setState, curCycle)
return setState
@log_commit
def addUser():
if (state == 1):
item.reply(stm['err']['alreadyStarted'])
return -1
con.execute(stm['preStm']['chkUsrState'],(item.author.name,))
r = con.fetchall()
if(len(r) > 0):
con.execute(stm['preStm']['addExistingUser'], (cfg['commands']['maxRequests'], item.author.name))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['addExistingUser'].format(item.author.name))
else:
con.execute(stm['preStm']['addUser'], (item.created_utc, item.author.name))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['addUser'].format(item.author.name))
sub.flair.set(item.author, text=stm['flairs']['alive'], flair_template_id=cfg['flairID']['alive'])
item.reply(stm['reply']['addUser'].format(item.author.name))
setItems(item.author.name, item)
@log_commit
def removeUser():
global curCycle
con.execute(stm['preStm']['removeUser'], (curCycle, item.author.name))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['removeUser'].format(item.author.name))
sub.flair.delete(item.author)
setItems(item.author.name, None)
@log_commit
@game_command
def voteUser():
global curCycle
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
if (r[0][0] < cfg['commands']['unlockVote']):
item.reply(stm['err']['notUnlocked'])
return -1
pattern = re.search(r'^!vote\s(?:u/)?([A-Za-z0-9_]{1,20})', item.body)
target = pattern.group(1)
con.execute(stm['preStm']['digupUser'], (target,))
r = con.fetchall()
if ((len(r) <= 0) or (r[0][2]) != 1):
item.reply(stm['err']['notAlive'])
return -1
con.execute(stm['preStm']['voteUser'], (item.author.name, target))
success = con.rowcount
if ((r[0][1] > cfg['commands']['escapeHit']) and (success > 0)):
sendMessage(target, stm['reply']['hitAlertEsc'].format(target, curCycle + 1))
item.reply(stm['reply']['voteUser'])
elif (success > 0):
sendMessage(target, stm['reply']['hitAlert'].format(target, curCycle + 1))
item.reply(stm['reply']['voteUser'])
else:
item.reply(stm['err']['voteUser'])
return -1
@log_commit
@game_command
def burnUser():
global curCycle
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
if (r[0][0] < cfg['commands']['unlockBurn']):
item.reply(stm['err']['notUnlocked'])
return -1
if (curCycle < cfg['commands']['burnAfter']):
item.reply(stm['err']['noBurnYet'])
return -1
con.execute(stm['preStm']['chkBurn'], (item.author.name,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['burnUsed'])
return -1
tier = r[0][2]
selfTeam = r[0][1]
oppTeam = selfTeam + 2
con.execute(stm['preStm']['burn'][selfTeam], (item.author.name,))
toBurn = con.fetchall()
con.execute(stm['preStm']['burn'][oppTeam])
toReport = con.fetchall()
if ((len(toBurn) <= 0) or (len(toReport) <= 0)):
item.reply(stm['err']['noBurnLeft'])
return -1
burned = toBurn[random.randint(0, len(toBurn) - 1)][0]
exposed = toReport[random.randint(0, len(toReport) - 1)][0]
deathMsg = random.randint(0,len(stm['deathMsg']) - 1)
con.execute(stm['preStm']['burn'][4], (item.author.name,))
con.execute(stm['preStm']['burn'][5], (burned,))
con.execute(stm['preStm']['log'], (time.time(), burned, 'Betrayed'))
con.execute(stm['preStm']['log'], (time.time(), exposed, 'Exposed'))
sub.flair.set(reddit.redditor(burned), text=stm['flairs']['dead'].format(stm['deathMsg'][deathMsg], curCycle + 1), flair_template_id=cfg['flairID']['dead'])
item.reply(stm['reply']['burnUser'].format(burned, exposed, stm['teams'][0][(selfTeam + 1) % 2]))
if (tier >= cfg['commands']['burnQuietly']):
sendMessage(burned, stm['reply']['burnedUserQuietly'].format(stm['deathMsg'][deathMsg], curCycle + 1))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['burnUserQuietly'].format(burned, stm['deathMsg'][deathMsg]))
else:
sendMessage(burned, stm['reply']['burnedUser'].format(stm['deathMsg'][deathMsg], item.author.name, curCycle + 1))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['burnUser'].format(burned, stm['deathMsg'][deathMsg], item.author.name,))
@log_commit
@game_command
def reviveUser():
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
if (r[0][0] < cfg['commands']['unlockRevive']):
item.reply(stm['err']['notUnlocked'])
return -1
con.execute(stm['preStm']['revive'][0], (item.author.name,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['reviveUsed'])
return -1
pattern = re.search(r'^!revive\s(?:u/)?([A-Za-z0-9_]{1,20})', item.body)
target = pattern.group(1)
con.execute(stm['preStm']['revive'][1], (target,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['alive'])
return -1
con.execute(stm['preStm']['revive'][2], (item.author.name,))
con.execute(stm['preStm']['revive'][3], (target,))
sub.flair.set(reddit.redditor(target), text=stm['flairs']['alive'], flair_template_id=cfg['flairID']['alive'])
sendMessage(target, stm['reply']['revivedUser'].format(item.author.name))
item.reply(stm['reply']['reviveUser'].format(target))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['revive'])
@log_commit
@game_command
def digupUser():
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
tier = r[0][0]
pattern = re.search(r'^!digup\s(?:u/)?([A-Za-z0-9_]{1,20})', item.body)
con.execute(stm['preStm']['digupUser'], (pattern.group(1),))
r = con.fetchall()
random.seed(time.time())
role = ''
maxTeams = len(stm['teams'][0]) - 1
maxRoles = len(stm['teams'][1][0]) - 1
cred = ((tier + 1) * 25) - random.randint(0,25)
if (tier == 0):
if (random.randint(0,7) == 0):
role = stm['teams'][0][r[0][0]]
else:
role = stm['teams'][0][random.randint(0,maxTeams)]
elif (tier == 1):
if (random.randint(0,5) == 0):
role = stm['teams'][2][r[0][0]][r[0][1]]
else:
role = stm['teams'][2][random.randint(0,maxTeams)][random.randint(0,maxRoles)]
elif (tier >= 2):
if (random.randint(0,3) == 0):
role = stm['teams'][2][r[0][0]][r[0][1]]
else:
role = stm['teams'][2][random.randint(0,maxTeams)][random.randint(0,maxRoles)]
item.reply(stm['reply']['digupUser'][0][0].format(pattern.group(1), role, stm['reply']['digupUser'][1][r[0][2]], cred))
@log_commit
@game_command
def locateUser():
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
if (r[0][0] < cfg['commands']['unlockLocate']):
item.reply(stm['err']['notUnlocked'])
return -1
pattern = re.search(r'^!locate\s(?:u/)?([A-Za-z0-9_]{1,20})', item.body)
name = pattern.group(1)
con.execute(stm['preStm']['locateUser'], (name,))
r = con.fetchall()
item.reply(stm['reply']['locateUser'].format(name, r[0][0]))
@log_commit
@game_command
def requestUser():
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
if (r[0][0] < cfg['commands']['unlockRequest']):
item.reply(stm['err']['notUnlocked'])
return -1
con.execute(stm['preStm']['request'][0], (item.author.name,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['noRequestLeft'])
return -1
pattern = re.search(r'^!request\s(?:u/)?([A-Za-z0-9_]{1,20})', item.body)
item.reply(stm['reply']['requestUser'])
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['requestUser'].format(pattern.group(1), stm['teams'][0][r[0][1]]))
con.execute(stm['preStm']['request'][1], (item.author.name,))
@log_commit
@game_command
def unlockTier():
pattern = re.search(r'^![a-z]{4,}\s(?:u/)?([\w\d\-]+)\s?$', item.body)
code = ''
if pattern:
code = pattern.group(1)
else:
item.reply(stm['err']['impFmt'])
return -1
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
tier = r[0][0]
team = r[0][1]
if (tier > len(cfg['codes']) - 1):
item.reply(stm['err']['maxTier'])
return -1
if (cfg['codes'][tier] == code):
con.execute(stm['preStm']['unlock'][1], (item.author.name,))
if (tier == cfg['commands']['addRequestsOn']):
con.execute(stm['preStm']['unlock'][2], (cfg['commands']['addRequests'], item.author.name))
item.reply(stm['reply']['addRequests'].format(cfg['commands']['addRequests']))
item.reply(stm['reply']['promote'].format(stm['teams'][1][team][tier + 1]))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['promote'].format(tier + 2))
else:
item.reply(stm['err']['wrongCode'])
return -1
@log_commit
@game_command
def switchTeam():
if (cfg['commands']['allowSwitchTeam'] == 0):
item.reply(stm['err']['switchTeamDisabled'])
return -1
con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()
if (r[0][0] < cfg['commands']['unlockInviteSwitch']):
item.reply(stm['err']['notUnlocked'])
return -1
pattern = re.search(r'^!convert\s(?:u/)?([A-Za-z0-9_]{1,20})', item.body)
target = pattern.group(1)
con.execute(stm['preStm']['digupUser'], (target,))
r = con.fetchall()
if ((len(r) <= 0) or (r[0][2]) != 1):
item.reply(stm['err']['notAlive'])
return -1
con.execute(stm['preStm']['switchTeam'][0], (target,))
r = con.fetchall()
if (len(r) > 1):
item.reply(stm['err']['switchTeamBlocked'])
return -1
con.execute(stm['preStm']['switchTeam'][1], (item.author.name, target))
success = con.rowcount
if (success > 0):
sendMessage(target, stm['reply']['switchTeamMsg'].format(item.author.name, curCycle + 1))
item.reply(stm['reply']['switchTeam'])
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['switchTeamInvite'])
else:
item.reply(stm['err']['switchTeam'])
return -1
@log_commit
def acceptInvite():
if (cfg['commands']['allowSwitchTeam'] == 0):
item.reply(stm['err']['switchTeamDisabled'])
return -1
con.execute(stm['preStm']['switchTeam'][2], (item.author.name,))
r = con.fetchall()
if (len(r) <= 0):
item.reply(stm['err']['switchTeamNone'])
return -1
con.execute(stm['preStm']['switchTeam'][3], (r[0][0], r[0][1]))
con.execute(stm['preStm']['switchTeam'][4], (r[0][1],))
item.reply(stm['reply']['switchTeamAccept'])
sendMessage(r[0][0], stm['reply']['switchTeamAccepted'].format(r[0][1]))
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['actions']['switchTeam'])
@log_commit
def getList():
dead = ''
alive = ''
deadNum = 0
aliveNum = 0
con.execute(stm['preStm']['getList'][0])
r = con.fetchall()
for row in r:
dead += f'\n* u/{row[0]}'
deadNum += 1
con.execute(stm['preStm']['getList'][1])
r = con.fetchall()
for row in r:
alive += f'\n* u/{row[0]}'
aliveNum += 1
item.reply(stm['reply']['getList'].format(deadNum + aliveNum, deadNum, dead, aliveNum, alive))
@log_commit
def getStats():
global curCycle
team = 'The Spectators'
tier = 'Spectator'
loc = 'Nowhere'
status = 'not playing'
con.execute(stm['preStm']['chkUsrState'], (item.author.name,))
r = con.fetchall()
if (len(r) == 1):
team = stm['teams'][0][r[0][0]]
tier = stm['teams'][2][r[0][0]][r[0][1]]
loc = r[0][2]
status = stm['alive'][r[0][3]]
con.execute(stm['preStm']['cycle']['getAliveCnt'])
result = con.fetchall()
alive = result[0][0]
killed = result[0][1]
con.execute(stm['preStm']['cycle']['getTeamCnt'])
result = con.fetchall()
bad = result[0][0]
good = result[0][1]
item.reply(stm['reply']['getSts'][0][0].format(stm['reply']['getSts'][1][state], \
curCycle + 1, tier, team, loc, status, alive, good, bad, killed, alive + killed, \
cfg['commands']['burnAfter'], cfg['commands']['voteThreshold'], \
cfg['commands']['voteOneAfter'], cfg['commands']['maxRequests'], cfg['kickAfter']))
@log_commit
def showHelp():
item.reply(stm['reply']['showHelp'])
@log_commit
def showRules():
item.reply(stm['reply']['showRules'])
@log_commit
def makeComment():
random.seed(time.time())
if (state == 0):
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['idle'][random.randint(0, len(stm['comment']['idle']) - 1)])
return
if (random.randint(0, 2) == 0):
con.execute(stm['preStm']['cycle']['getVotes'])
r = con.fetchall()
if (len(r) <= 0):
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['warn']['noVotes'][random.randint(0, len(stm['comment']['warn']['noVotes']) - 1)])
return
else:
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['warn']['votes'][random.randint(0, len(stm['comment']['warn']['votes']) - 1)])
return
reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['comment']['spook'][random.randint(0, len(stm['comment']['spook']) - 1)])
@log_commit
def gameStart():
con.execute(stm['preStm']['getPlaying'])
r = con.fetchall()
players = len(r)
curPos = 0
random.seed(time.time())
random.shuffle(r)
for row in r:
team = curPos % 2
random.seed(time.time())
loc = stm['location'][team][random.randint(0, len(stm['location'][team]) - 1)]
con.execute(stm['preStm']['joinTeam'], (team, loc, row[0]))
sendMessage(row[0], stm['reply']['gameStart'].format(stm['teams'][0][team], loc, players, cfg['reddit']['sub'], cfg['reddit']['targetPost']))
curPos += 1
sleep(0.2)
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['start'].format(players))
comment.mod.distinguish(how='yes', sticky=True)
@log_commit
def gameEnd():
global curCycle
round = curCycle + 1
con.execute(stm['preStm']['cycle']['resetInactive'])
con.execute(stm['preStm']['cycle']['incrementInactive'])
con.execute(stm['preStm']['cycle']['resetComment'])
con.execute(stm['preStm']['cycle']['getInactive'], (cfg['kickAfter'],))
r = con.fetchall()
for row in r:
sub.flair.delete(reddit.redditor(row[0]))
reddit.redditor(row[0]).message('You have been kicked!', stm['reply']['cycle'][2])
sleep(0.2)
con.execute(stm['preStm']['cycle']['getAliveCnt'])
r = con.fetchall()
alive = r[0][0]
killed = r[0][1]
print(f'\nAlive: {alive} | Killed {killed}')
if (cfg['commands']['allowBotBroadcast'] == 1):
con.execute(stm['preStm']['getDead'])
r = con.fetchall()
for row in r:
sendMessage(row[0], stm['reply']['gameEnd'].format(cfg['reddit']['sub'], cfg['reddit']['targetPost']))
sleep(0.2)
con.execute(stm['preStm']['cycle']['getAlive'])
r = con.fetchall()
for row in r:
if (cfg['commands']['allowBotBroadcast'] == 1):
sendMessage(row[0], stm['reply']['gameEnd'].format(cfg['reddit']['sub'], cfg['reddit']['targetPost']))
sub.flair.set(reddit.redditor(row[0]), text=stm['flairs']['survived'].format(stm['teams'][0][row[1]], round), flair_template_id=cfg['flairID']['alive'])
sleep(0.2)
con.execute(stm['preStm']['getWinner'])
r = con.fetchall()
bad = r[0][0]
good = r[0][1]
if (good == bad):
winner = 'NOBODY'
elif (good > bad):
winner = 'MI6'
else:
winner = 'The Twelve'
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['end'].format(winner, alive, killed))
comment.mod.distinguish(how='yes', sticky=True)
@log_commit
def cycle():
global curCycle
if (state == 0):
item.reply(stm['err']['notStarted'])
return -1
if (item is None):
pass
else:
if (item.author.name not in cfg['adminUsr']):
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'ATTEMPTED ADMIN COMMAND: cycle'))
return -1
threshold = 1
if (curCycle > cfg['commands']['voteOneAfter']):
threshold = 1
else:
threshold = cfg['commands']['voteThreshold']
con.execute(stm['preStm']['cycle']['resetInactive'])
con.execute(stm['preStm']['cycle']['incrementInactive'])
con.execute(stm['preStm']['cycle']['resetComment'])
con.execute(stm['preStm']['cycle']['getInactive'], (cfg['kickAfter'],))
result = con.fetchall()
for row in result:
con.execute(stm['preStm']['log'], (time.time(), row[0], 'Inactive Kick'))
sub.flair.delete(reddit.redditor(row[0]))
sendMessage(row[0], stm['reply']['cycle'][2])
sleep(0.2)
con.execute(stm['preStm']['cycle']['removeInactive'], (cfg['kickAfter'],))
con.execute(stm['preStm']['cycle']['getVotes'])
result = con.fetchall()
for row in result:
con.execute(stm['preStm']['chkUsr'], (row[0],))
r = con.fetchall()
tier = r[0][2]
if (tier <= cfg['commands']['escapeHit']):
continue
con.execute(stm['preStm']['cycle']['getVoteTarget'], (row[0],))
target = con.fetchall()
if (len(target) >= 1):
con.execute(stm['preStm']['cycle']['getVoters'], (row[0], row[0]))
list = con.fetchall()
for user in list:
if (target[0][0] == user[0]):
con.execute(stm['preStm']['log'], (time.time(), row[0], 'Escaped'))
con.execute(stm['preStm']['cycle']['voteEscaped'], (row[0],))
sendMessage(row[0], stm['reply']['cycle'][3])
print(f' > {row[0]} escaped')
con.execute(stm['preStm']['cycle']['killPlayer'], (curCycle, threshold))
con.execute(stm['preStm']['cycle']['getAliveCnt'])
result = con.fetchall()
alive = result[0][0]
killed = result[0][1]
print(f'\nAlive: {alive} | Killed {killed}')
con.execute(stm['preStm']['cycle']['getTeamCnt'])
result = con.fetchall()
bad = result[0][0]
good = result[0][1]
print(f'MI6: {good} | The Twelve: {bad}')
con.execute(stm['preStm']['cycle']['getDead'], (threshold,))
result = con.fetchall()
for row in result:
con.execute(stm['preStm']['cycle']['getKilledMe'], (row[0],))
r = con.fetchall()
killedMe = ''
for v in r:
killedMe += f'* u/{v[0]}\n'
random.seed(time.time())
n = random.randint(0,len(stm['deathMsg']) - 1)
sub.flair.set(reddit.redditor(row[0]), text=stm['flairs']['dead'].format(stm['deathMsg'][n], curCycle + 1), flair_template_id=cfg['flairID']['dead'])
sendMessage(row[0], stm['reply']['cycle'][0].format(stm['deathMsg'][n], curCycle + 1, killedMe, alive, good, bad, killed, alive + killed))
con.execute(stm['preStm']['log'], (time.time(), row[0], 'Killed'))
print(f' > {row[0]} killed')
sleep(0.2)
con.execute(stm['preStm']['cycle']['getAlive'])
result = con.fetchall()
for row in result:
# sendMessage(row[0], stm['reply']['cycle'][1].format(curCycle + 2, alive, good, bad, killed, alive + killed))
sleep(0.2)
con.execute('TRUNCATE TABLE VoteCall');
con.execute('TRUNCATE TABLE TeamInvite;');
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['cycle'].format(curCycle + 2, alive, good, bad, killed, alive + killed))
comment.mod.distinguish(how='yes', sticky=True)
if (item is None):
pass
else:
item.reply(f'**Moved to Round {curCycle + 2}**')
print(f'Moved to Round {curCycle + 1}')
curCycle += 1
save(state, curCycle)
return curCycle
@log_commit
def broadcast():
pattern = re.search(r'^!BROADCAST\s([\s\w\d!@#$%^&*()_+{}|:\'<>?\-=\[\]\;\',./’]+)', item.body)
msg = pattern.group(1)
if (item.author.name not in cfg['adminUsr']):
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'ATTEMPTED ADMIN COMMAND: broadcast'))
return -1
if (cfg['commands']['allowBotBroadcast'] == 0):
item.reply('Broadcast Disabled')
return -1
con.execute(stm['preStm']['getAll'])
r = con.fetchall()
for row in r:
sendMessage(row[0], msg)
sleep(0.2)
@log_commit
def restart():
item.mark_read()
if (item.author.name not in cfg['adminUsr']):
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'ATTEMPTED ADMIN COMMAND: restart'))
return -1
con.execute(stm['preStm']['restart'])
con.execute('TRUNCATE TABLE VoteCall;');
con.execute('TRUNCATE TABLE TeamInvite;');
con.execute('COMMIT;')
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['restart'])
comment.mod.distinguish(how='yes', sticky=True)
save(0, 0)
if (item.author.name != '*SELF*'): item.reply('**Restarting Game**')
print('REMOTE RESTART RECEIVED')
con.close()
os._exit(1)
@log_commit
def reset():
item.mark_read()
if (item.author.name not in cfg['adminUsr']):
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'ATTEMPTED ADMIN COMMAND: reset'))
return -1
con.execute('SELECT `username` FROM Mafia')
r = con.fetchall()
for row in r:
sub.flair.delete(row[0])
con.execute('TRUNCATE TABLE Mafia;');
con.execute('TRUNCATE TABLE VoteCall;');
con.execute('TRUNCATE TABLE TeamInvite;');
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'reset'))
con.execute('COMMIT;')
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['reset'])
comment.mod.distinguish(how='yes', sticky=True)
save(0, 0)
try:
os.remove('data/items.pickle')
except:
pass
if (item.author.name != '*SELF*'): item.reply('**Resetting Game**')
print('REMOTE RESET RECEIVED')
con.close()
os._exit(1)
@log_commit
def halt():
item.mark_read()
if (item.author.name not in cfg['adminUsr']):
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'ATTEMPTED ADMIN COMMAND: halt'))
return -1
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['halt'])
comment.mod.distinguish(how='yes', sticky=True)
con.execute(stm['preStm']['log'], (item.created_utc, item.author.name, 'halt'))
con.execute('COMMIT;')
if (item.author.name != '*SELF*'): item.reply('**Stopping Game**')
print('REMOTE HALT RECEIVED')
con.close()
os._exit(1)
def rateLimit():
limits = json.loads(str(reddit.auth.limits).replace("'", "\""))
if (limits['remaining'] < 10):
reset = (limits["reset_timestamp"] + 10) - time.time()
print(f'Sleeping for: {reset} seconds')
print(time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(limits["reset_timestamp"])))
comment = reddit.submission(id=cfg['reddit']['targetPost']).reply(stm['sticky']['rateLimit'].format(reset))
comment.mod.distinguish(how='yes', sticky=True)
sleep(reset)
def sendMessage(name, message):
if(getItems(name) != None):
getItems(name).reply(message)
rateLimit()
else:
print(f'WARNING. {name} not found in items.pickle. Falling back on alternate')
reddit.redditor(name).message('Mafia', message)
rateLimit()
def refreshConnection():
con.execute('SHOW PROCESSLIST;')
conStat = con.fetchall()
print(f'Refreshed SQL Connection. {len(conStat)}')
con.execute(stm['preStm']['main'][0])
con.execute(stm['preStm']['main'][1], (time.time(),))
con.execute(stm['preStm']['addDummy'])
con.execute('COMMIT;')
con.execute('SHOW PROCESSLIST;')
conStat = con.fetchall()
scheduleJobs()
print(f'Connected as {str(reddit.user.me())}')
print(f'Database Connections: {len(conStat)}')
print(f'state: {state}')
print(f'curCycle: {curCycle} (Cycle: {curCycle + 1})')
print('______')
while True:
schedule.run_pending()
try:
for comment in commentStream:
if comment is None:
break
if ((comment.submission.id == cfg['reddit']['targetPost']) and (comment.id not in idCache)):
if (len(idCache) > 1000):
idCache = []
if(re.search(r'^!(join|leave|vote|digup|rules|help|stats)', comment.body)):
comment.reply(stm['err']['notPM'])
idCache.append(comment.id)
con.execute(stm['preStm']['comment'], (comment.author.name,))
con.execute('COMMIT;')
for item in inboxStream:
if item is None:
break
if (item.was_comment == True):
continue
if (item.body.strip() == lastCmd):
try:
con.execute('RESET QUERY CACHE;')
except:
pass
with open('data/save.json') as jsonFile2:
sve = json.load(jsonFile2)
state = sve['state']
curCycle = sve['curCycle']
if (re.search(r'^!join', item.body)):
addUser()
elif (re.search(r'^!leave', item.body)):
removeUser()
elif (re.search(r'^!vote', item.body)):
voteUser()
elif (re.search(r'^!burn$', item.body)):
burnUser()
elif (re.search(r'^!revive', item.body)):
reviveUser()
elif (re.search(r'^!digup', item.body)):
digupUser()
elif (re.search(r'^!locate', item.body)):
locateUser()
elif (re.search(r'^!request', item.body)):
requestUser()
elif (re.search(r'^!unlock', item.body)):
unlockTier()
elif (re.search(r'^!convert', item.body)):
switchTeam()
elif (re.search(r'^!accept', item.body)):
acceptInvite()
elif ((re.search(r'^!list', item.body))):
getList()
elif (re.search(r'^!stats', item.body)):
getStats()