Skip to content
This repository has been archived by the owner on Mar 17, 2021. It is now read-only.

Commit

Permalink
Merge pull request #28 from mikojimnz/V2
Browse files Browse the repository at this point in the history
V2 Fix #26
  • Loading branch information
mikojimnz committed Sep 23, 2020
2 parents e2b1001 + 00fc4b0 commit 2fd6561
Show file tree
Hide file tree
Showing 4 changed files with 164 additions and 29 deletions.
91 changes: 72 additions & 19 deletions Mafia.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@
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:
Expand Down Expand Up @@ -61,7 +69,7 @@ def wrapper(*args, **kwargs):
utc = item.created_utc

result = func(*args, **kwargs)
pattern = re.search(r'^![\w]{1,}\s([\w\d_\-\s]+)', command)
pattern = re.search(r'^![\w]{1,}\s([\w\d_\-\s/]+)', command)
readable = time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(utc))
action = ''

Expand Down Expand Up @@ -133,14 +141,22 @@ def wrapper(*args, **kwargs):
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)
curCycle = sve['curCycle']
cycle(curCycle)

cycle()
print(f'Auto Cycle {curCycle}')

def scheduleJobs():
Expand All @@ -164,11 +180,14 @@ def scheduleJobs():
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(1).to(3).hours.do(makeComment)
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)
Expand Down Expand Up @@ -205,12 +224,14 @@ def addUser():
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'].format(1), flair_template_id=cfg['flairID']['alive'])
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)
Expand All @@ -219,6 +240,8 @@ def removeUser():
@log_commit
@game_command
def voteUser():
global curCycle

con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()

Expand Down Expand Up @@ -251,6 +274,8 @@ def voteUser():
@log_commit
@game_command
def burnUser():
global curCycle

con.execute(stm['preStm']['unlock'][0], (item.author.name,))
r = con.fetchall()

Expand Down Expand Up @@ -281,8 +306,8 @@ def burnUser():
item.reply(stm['err']['noBurnLeft'])
return -1

burned = toBurn[0][random.randint(0, len(toBurn) - 1)]
exposed = toReport[0][random.randint(0, len(toReport) - 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,))
Expand Down Expand Up @@ -326,7 +351,7 @@ def reviveUser():

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'].format(curCycle + 1, flair_template_id=cfg['flairID']['alive']))
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'])
Expand Down Expand Up @@ -355,7 +380,7 @@ def digupUser():
role = stm['teams'][0][random.randint(0,maxTeams)]
elif (tier == 1):
if (random.randint(0,5) == 0):
role = stm['teams'][1][r[0][0]][r[0][1]]
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):
Expand Down Expand Up @@ -524,6 +549,8 @@ def getList():

@log_commit
def getStats():
global curCycle

team = 'The Spectators'
tier = 'Spectator'
loc = 'Nowhere'
Expand Down Expand Up @@ -563,8 +590,13 @@ def 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()
Expand Down Expand Up @@ -603,6 +635,8 @@ def gameStart():

@log_commit
def gameEnd():
global curCycle

round = curCycle + 1
con.execute(stm['preStm']['cycle']['resetInactive'])
con.execute(stm['preStm']['cycle']['incrementInactive'])
Expand Down Expand Up @@ -656,14 +690,19 @@ def gameEnd():
comment.mod.distinguish(how='yes', sticky=True)

@log_commit
def cycle(curCycle):
def cycle():
global curCycle

if (state == 0):
item.reply(stm['err']['notStarted'])
return -1

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
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

Expand Down Expand Up @@ -747,15 +786,19 @@ def cycle(curCycle):
result = con.fetchall()

for row in result:
sub.flair.set(reddit.redditor(row[0]), text=stm['flairs']['alive'].format(curCycle + 2), flair_template_id=cfg['flairID']['alive'])
# 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 != None): item.reply(f'**Moved to Round {curCycle + 2}**')

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)
Expand Down Expand Up @@ -871,11 +914,16 @@ def sendMessage(name, message):
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')
con.execute('SHOW PROCESSLIST;')
conStat = con.fetchall()

scheduleJobs()
Expand All @@ -887,8 +935,7 @@ def sendMessage(name, message):
print('______')

while True:
if (state == 1):
schedule.run_pending()
schedule.run_pending()

try:
for comment in commentStream:
Expand Down Expand Up @@ -919,6 +966,12 @@ def sendMessage(name, message):
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)):
Expand Down Expand Up @@ -952,7 +1005,7 @@ def sendMessage(name, message):
elif (re.search(r'^!GAMESTATE', item.body)):
state = gameState(state)
elif (re.search(r'^!CYCLE', item.body)):
curCycle = cycle(curCycle)
curCycle = cycle()
elif (re.search(r'^!BROADCAST', item.body)):
broadcast()
elif (re.search(r'^!RESTART', item.body)):
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ Play against other members to find out who amongst each other you can trust and

|Team|Role|Tier|Description|
|:-|:-|:-|:-|
|The Twelve|Trainee|1|Access to digup (low accuracy), vote, and max 3 requests.|
|The Twelve|Assassin|2|Digup accuracy increased.|
|The Twelve|Trainee|1|Access to digup (low accuracy) and max 3 requests.|
|The Twelve|Assassin|2|Vote unlocked, Digup accuracy increased.|
|The Twelve|Handler|3|Digup accuracy increased. Unlocked locate and burn command (Tier 3 or lower). 3 Additional requests. Can escape hits.|
|The Twelve|Keeper|4|Revive and convert unlocked. Burn does not announce who you are.|
|MI6|Recruit|1|Access to digup (low accuracy), vote, and max 3 requests.|
|MI6|Analyst|2|Digup accuracy increased.|
|MI6|Recruit|1|Access to digup (low accuracy) and max 3 requests.|
|MI6|Analyst|2|Vote unlocked, Digup accuracy increased.|
|MI6|Operative|3|Digup accuracy increased. Unlocked locate and burn command (Tier 3 or lower). 3 Additional requests. Can escape hits.|
|MI6|Supervisor|4|Revive and convert unlocked. Burn does not announce who you are.|

Expand All @@ -54,7 +54,7 @@ All commands must be sent privately to u/DozenIncBOT. To use investigative comma
|!vote USERNAME|Vote on who to eliminate. Can not be changed once voted per round.|2|
|!digup USERNAME|Investigate the roles of other users. Has varying degree of reliability based on your tier|1|
|!locate USERNAME|Shows the user's location. May give a clue as to what side they are on.|3|
|!convert USERNAME|Invite a user to switch to your team.|3|
|!convert USERNAME|Invite a user to switch to your team.|4|
|!accept|Accept an invitation to switch teams.|1|
|!unlock CODE|Enter a secret code in order to level up to the next tier.|1|
|!stats|Gets the current stats for the game.|1|
Expand Down
60 changes: 60 additions & 0 deletions init/praw.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True

# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
trophy_kind=t6

# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com

# The amount of seconds to ratelimit
ratelimit_seconds=5

# The URL prefix for regular requests.
reddit_url=https://www.reddit.com

# The URL prefix for short URLs.
short_url=https://redd.it

# The timeout for requests to Reddit in number of seconds
timeout=16

[DEFAULT]
# A boolean to indicate whether or not to check for package updates.
check_for_updates=True

# Object to kind mappings
comment_kind=t1
message_kind=t4
redditor_kind=t2
submission_kind=t3
subreddit_kind=t5
trophy_kind=t6

# The URL prefix for OAuth-related requests.
oauth_url=https://oauth.reddit.com

# The amount of seconds to ratelimit
ratelimit_seconds=5

# The URL prefix for regular requests.
reddit_url=https://www.reddit.com

# The URL prefix for short URLs.
short_url=https://redd.it

# The timeout for requests to Reddit in number of seconds
timeout=16

[Default]
client_id=
client_secret=
password=
username=
user_agent="OS:NAME:VERSION (by u/USERNAME)"
Loading

0 comments on commit 2fd6561

Please sign in to comment.