Logging
This commit is contained in:
76
Gwendolyn.py
76
Gwendolyn.py
@ -3,14 +3,10 @@
|
||||
import discord
|
||||
import asyncio
|
||||
import pickle
|
||||
import time
|
||||
import logging
|
||||
import codecs
|
||||
|
||||
import funcs
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
|
||||
# Gets secret bot token
|
||||
with open("token.txt","r") as f:
|
||||
token = f.read().replace("\n","")
|
||||
@ -20,13 +16,7 @@ client = discord.Client()
|
||||
# Logs in
|
||||
@client.event
|
||||
async def on_ready():
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print(localtime)
|
||||
print("Logged in as")
|
||||
print(client.user.name)
|
||||
print(client.user.id)
|
||||
print("-----------")
|
||||
logging.info("\n-----------\n"+localtime+"\nLogged in")
|
||||
funcs.logThis("Logged in as "+client.user.name+", "+str(client.user.id))
|
||||
game = discord.Game("Some weeb shit")
|
||||
await client.change_presence(activity=game)
|
||||
|
||||
@ -35,40 +25,30 @@ async def on_ready():
|
||||
async def on_message(message):
|
||||
# Sends the contents of "help.txt"
|
||||
if message.content.lower().startswith("!help"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !help")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !help")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
with codecs.open("resources/help.txt",encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
print(text)
|
||||
em = discord.Embed(title = "Help", description = text,colour = 0x59f442)
|
||||
await message.channel.send(embed = em)
|
||||
|
||||
# Stops the bot
|
||||
elif message.content.lower().startswith("!stop"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
if message.author.name == "Nikolaj":
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !stop")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !stop")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send("Logging out...")
|
||||
await client.logout()
|
||||
else:
|
||||
print("\n"+localtime+"\n"+message.author.name+" tried to run !stop")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" tried to run !stop")
|
||||
funcs.logThis(message.author.name+" tried to run "+message.content)
|
||||
await message.channel.send("I don't think I will, "+message.author.name)
|
||||
|
||||
# Does a hello with the helloFunc function from funcs/gwendolynFuncs.py
|
||||
elif message.content.lower().startswith("!hello"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !hello")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !hello")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send(funcs.helloFunc(message.author.name))
|
||||
|
||||
# Rolls dice with the roll_dice function from funcs/roll/dice.py
|
||||
elif message.content.lower().startswith("!roll"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !roll")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !roll")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
if message.content.lower() == "!roll" or message.content.lower() == "!roll ":
|
||||
await message.channel.send(funcs.roll_dice(message.author.name))
|
||||
else:
|
||||
@ -76,16 +56,12 @@ async def on_message(message):
|
||||
|
||||
# Looks up a spell with the spellFunc function from funcs/lookup/lookupFuncs.py
|
||||
elif message.content.lower().startswith("!spell "):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !spell")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !spell")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send(funcs.spellFunc(message.content))
|
||||
|
||||
# Looks up a monster with the monsterFuncs() from funcs/lookup/lookupFuncs.py
|
||||
elif message.content.lower().startswith("!monster "):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !monster")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !monster")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
title, text1, text2, text3, text4, text5 = funcs.monsterFunc(message.content)
|
||||
em1 = discord.Embed(title = title, description = text1, colour=0xDEADBF)
|
||||
|
||||
@ -131,25 +107,19 @@ async def on_message(message):
|
||||
|
||||
# Sends an image of the Senkulpa map
|
||||
elif message.content.lower().startswith("!map"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !map")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !map")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send("https://i.imgur.com/diMXXJs.jpg")
|
||||
|
||||
# Finds a random image on the internet with the imageFuncs function from
|
||||
# funcs/gwendolynFuncs.py
|
||||
elif message.content.lower().startswith("!image"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !image")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !image")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send(funcs.imageFunc())
|
||||
|
||||
# Sends information about a random movie with the movieFunc function from
|
||||
# funcs/other/movie.py
|
||||
elif message.content.lower().startswith("!movie"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !movie")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !movie")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
async with message.channel.typing():
|
||||
title, plot, cover, cast = funcs.movieFunc()
|
||||
if title == "error":
|
||||
@ -162,49 +132,37 @@ async def on_message(message):
|
||||
|
||||
# Generates a random name with the nameGen function from funcs/other/generators.py
|
||||
elif message.content.lower().startswith("!name"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !name")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !name")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send(funcs.nameGen())
|
||||
|
||||
# Generates a random tavern name with the tavernGen function from funcs/other/generators.py
|
||||
elif message.content.lower().startswith("!tavern"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !tavern")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !tavern")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
await message.channel.send(funcs.tavernGen())
|
||||
|
||||
# Changes the "Playing this game" thing in Discord
|
||||
elif message.content.lower().startswith("!game "):
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
gamePlaying = funcs.cap(message.content.lower().replace("!game ",""))
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !game, changing the game to '"+gamePlaying+"'")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !game, changing the game to '"+gamePlaying+"'")
|
||||
game = discord.Game(gamePlaying)
|
||||
await client.change_presence(activity=game)
|
||||
|
||||
# Rolls star wars dice with the parseRoll function from funcs/swfuncs/swroll.py
|
||||
elif message.content.lower().startswith("!swroll"):
|
||||
localtime = time.asctime( time.localtime(time.time()) )
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !swroll")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !swroll")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
command = funcs.cap(message.content.lower().replace("!swroll",""))
|
||||
await message.channel.send(funcs.parseRoll(message.author.name,command))
|
||||
|
||||
# Deals with Destiny Points and stuff
|
||||
elif message.content.lower().startswith("!swd"):
|
||||
localtime = time.asctime(time.localtime(time.time()))
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !swd")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !swd")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
command = message.content.lower().replace("!swd","")
|
||||
await message.channel.send(funcs.parseDestiny(message.author.name,command))
|
||||
|
||||
# Accesses and changes character sheet data with the parseChar function
|
||||
# from funcs/swfuncs/swchar.py
|
||||
elif message.content.lower().startswith("!swchar") or message.content.lower().startswith("!sw"):
|
||||
localtime = time.asctime(time.localtime(time.time()))
|
||||
print("\n"+localtime+"\n"+message.author.name+" ran !swchar")
|
||||
logging.info("\n"+localtime+"\n"+message.author.name+" ran !swchar")
|
||||
funcs.logThis(message.author.name+" ran \""+message.content+"\"")
|
||||
command = funcs.cap(message.content.lower().replace("!swchar","").replace("!sw","").replace("+","+ "))
|
||||
title, desc = funcs.parseChar(message.author.name,command)
|
||||
if title != "":
|
||||
|
@ -1,4 +1,4 @@
|
||||
from .gwendolynFuncs import helloFunc, roll_dice, cap, imageFunc
|
||||
from .gwendolynFuncs import helloFunc, roll_dice, cap, imageFunc, logThis
|
||||
|
||||
from .swfuncs import parseChar, parseRoll, parseDestiny
|
||||
|
||||
|
@ -1,16 +1,20 @@
|
||||
import lxml.etree #used by imageFunc
|
||||
import re #used by roll_dice
|
||||
import datetime #used by helloFunc
|
||||
import json #used by spellFunc
|
||||
import random #used by imageFunc
|
||||
import urllib #used by imageFunc
|
||||
import imdb #used by movieFunc
|
||||
import lxml.etree # Used by imageFunc
|
||||
import re # Used by roll_dice
|
||||
import datetime # Used by helloFunc
|
||||
import json # Used by spellFunc
|
||||
import random # Used by imageFunc
|
||||
import urllib # Used by imageFunc
|
||||
import imdb # Used by movieFunc
|
||||
import time # Used for logging
|
||||
import logging # Used for... you know... logging
|
||||
|
||||
from .roll import dice
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
|
||||
# I stole this. It rolls dice. I am not qualified to comment it
|
||||
def roll_dice(author : str, rollStr : str = "1d20"):
|
||||
print("Rolling "+str(rollStr))
|
||||
logThis("Rolling "+str(rollStr))
|
||||
if rollStr == '0/0': # easter eggs
|
||||
return("What do you expect me to do, destroy the universe?")
|
||||
|
||||
@ -25,8 +29,7 @@ def roll_dice(author : str, rollStr : str = "1d20"):
|
||||
outputs = author + ' :game_die:\n[Output truncated due to length]\n**Result:** ' + str(res.plain)
|
||||
else:
|
||||
outputs = outStr
|
||||
print("Successfully ran !roll")
|
||||
print("")
|
||||
logThis("Successfully ran !roll")
|
||||
return(outputs)
|
||||
|
||||
# Capitalizes all words except some of them
|
||||
@ -52,7 +55,6 @@ def time_in_range(start, end, x):
|
||||
|
||||
# Responds with a greeting of a time-aprpriate maner
|
||||
def helloFunc(author):
|
||||
print("")
|
||||
now = datetime.datetime.now()
|
||||
if time_in_range(now.replace(hour=5, minute=0, second=0, microsecond=0),now.replace(hour=10, minute=0, second=0, microsecond=0), now):
|
||||
return("Good morning, "+str(author))
|
||||
@ -72,6 +74,7 @@ def imageFunc():
|
||||
# Picks a type of camera, which decides the naming scheme
|
||||
cams = ("one","two","three","four")
|
||||
cam = random.choice(cams)
|
||||
logThis("Chose cam type "+cam)
|
||||
if cam == "one":
|
||||
a = str(random.randint(0 ,9))
|
||||
b = str(random.randint(0,9))
|
||||
@ -92,7 +95,9 @@ def imageFunc():
|
||||
c = str(random.randint(0,9))
|
||||
d = str(random.randint(0,9))
|
||||
search = ("DSC_"+a+b+c+d)
|
||||
|
||||
|
||||
logThis("Searching for "+search)
|
||||
|
||||
# Searches for the image and reads the resulting web page
|
||||
page = urllib.request.urlopen("https://www.bing.com/images/search?q="+search+"&safesearch=off")
|
||||
read = page.read()
|
||||
@ -103,8 +108,13 @@ def imageFunc():
|
||||
number = random.randint(1,len(images))-1
|
||||
image = images[number]
|
||||
|
||||
logThis("Picked image number "+str(number))
|
||||
|
||||
# Returns the image
|
||||
print("Successfully returned an image\n")
|
||||
logThis("Successfully returned an image")
|
||||
return(image)
|
||||
|
||||
|
||||
def logThis(message : str):
|
||||
localtime = time.asctime(time.localtime(time.time()))
|
||||
print(localtime+" - "+message)
|
||||
logging.info(localtime+" - "+message)
|
||||
|
@ -1,11 +1,8 @@
|
||||
import math
|
||||
import discord
|
||||
import json
|
||||
import logging
|
||||
|
||||
from funcs import gwendolynFuncs as gf
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
from funcs import cap, logThis
|
||||
|
||||
# Calculates D&D stat modifier
|
||||
def modifier(statistic):
|
||||
@ -19,22 +16,19 @@ abilities = ["acrobatics","animal_handling","arcana","athletics","deception","hi
|
||||
|
||||
# Looks up a monster
|
||||
def monsterFunc(content):
|
||||
command = gf.cap(content.lower().replace("!monster ",""))
|
||||
print("Looking up "+command)
|
||||
logging.info("Looking up "+command)
|
||||
command = cap(content.lower().replace("!monster ",""))
|
||||
logThis("Looking up "+command)
|
||||
|
||||
# 1-letter monsters don't exist
|
||||
if len(content.lower().split()) < 2:
|
||||
print("Monster doesn't exist in database\n")
|
||||
logging.info("Monster doesn't exist in database\n")
|
||||
logThis("Monster doesn't exist in database")
|
||||
return("I don't know that monster...","","","","","")
|
||||
else:
|
||||
# Opens "mensters.json"
|
||||
data = json.load(open('resources/monsters.json', encoding = "utf8"))
|
||||
for monster in data:
|
||||
if str(command) == monster["name"]:
|
||||
print("Found it!")
|
||||
logging.info("Found it!")
|
||||
logThis("Found it!")
|
||||
|
||||
# Looks at the information about the monster and returns that information
|
||||
# in seperate variables, allowing Gwendolyn to know where to seperate
|
||||
@ -52,9 +46,9 @@ def monsterFunc(content):
|
||||
for save in saves:
|
||||
if save in monster:
|
||||
if monster[save] >= 0:
|
||||
saving_throws += " "+gf.cap(save[:3])+" +"+str(monster[save])+","
|
||||
saving_throws += " "+cap(save[:3])+" +"+str(monster[save])+","
|
||||
else:
|
||||
saving_throws += " "+gf.cap(save[:3])+" "+str(monster[save])+","
|
||||
saving_throws += " "+cap(save[:3])+" "+str(monster[save])+","
|
||||
if saving_throws != "":
|
||||
saving_throws = "\n**Saving Throws**"+saving_throws[:-1]
|
||||
|
||||
@ -62,9 +56,9 @@ def monsterFunc(content):
|
||||
for skill in abilities:
|
||||
if skill in monster:
|
||||
if monster[skill] >= 0:
|
||||
skills += " "+gf.cap(skill.replace("_"," "))+" +"+str(monster[skill])+","
|
||||
skills += " "+cap(skill.replace("_"," "))+" +"+str(monster[skill])+","
|
||||
else:
|
||||
skills += " "+gf.cap(skill.replace("_"," "))+" "+str(monster[skill])+","
|
||||
skills += " "+cap(skill.replace("_"," "))+" "+str(monster[skill])+","
|
||||
if skills != "":
|
||||
skills = "\n**Skills**"+skills[:-1]
|
||||
|
||||
@ -122,29 +116,23 @@ def monsterFunc(content):
|
||||
text4 = (react)
|
||||
text5 = (leg_act)
|
||||
|
||||
print("Returning monster information")
|
||||
logging.info("Returning monster information")
|
||||
logThis("Returning monster information")
|
||||
return(str(command),text1,text2,text3,text4,text5)
|
||||
print("Couldn't find monster")
|
||||
logging.info("Couldn't find monster")
|
||||
logThis("Couldn't find monster")
|
||||
return("I don't know that monster...","","","","","")
|
||||
|
||||
# Looks up a spell
|
||||
def spellFunc(content):
|
||||
command = gf.cap(content.lower().replace("!spell ",""))
|
||||
print("Looking up "+command)
|
||||
logging.info("Looking up "+command)
|
||||
command = cap(content.lower().replace("!spell ",""))
|
||||
logThis("Looking up "+command)
|
||||
|
||||
# Opens "spells.json"
|
||||
data = json.load(open('resources/spells.json', encoding = "utf8"))
|
||||
if str(command) in data:
|
||||
print("Returning spell information")
|
||||
logging.info("Returning spell information")
|
||||
logThis("Returning spell information")
|
||||
spell_output = ("***"+str(command)+"***\n*"+str(data[str(command)]["level"])+" level "+str(data[str(command)]["school"])+"\nCasting Time: "+str(data[str(command)]["casting_time"])+"\nRange: "+str(data[str(command)]["range"])+"\nComponents: "+str(data[str(command)]["components"])+"\nDuration: "+str(data[str(command)]["duration"])+"*\n \n"+str(data[str(command)]["description"]))
|
||||
else:
|
||||
print("I don't know that spell")
|
||||
logging.info("I don't know that spell")
|
||||
logThis("I don't know that spell")
|
||||
spell_output = "I don't think that's a spell"
|
||||
print("Successfully ran !spell")
|
||||
logging.info("Successfully ran !spell")
|
||||
logThis("Successfully ran !spell")
|
||||
return(spell_output)
|
||||
|
@ -1,8 +1,7 @@
|
||||
import numpy as np
|
||||
import random
|
||||
import logging
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
from funcs import logThis
|
||||
|
||||
# Returns a list of all letter pairs in the text
|
||||
def make_pairs(corpus):
|
||||
@ -47,8 +46,7 @@ def nameGen():
|
||||
if new_letter == "\n":
|
||||
done = True
|
||||
genName = "".join(chain)
|
||||
print("Generated "+genName)
|
||||
logging.info("Generated "+genName)
|
||||
logThis("Generated "+genName)
|
||||
# Returns the name
|
||||
return(genName)
|
||||
|
||||
@ -61,8 +59,7 @@ def tavernGen():
|
||||
|
||||
# Picks one of each
|
||||
genTav = random.choice(fp)+" "+random.choice(sp)+random.choice(tp)
|
||||
print("Generated "+genTav)
|
||||
logging.info("Generated "+genTav)
|
||||
logThis("Generated "+genTav)
|
||||
|
||||
# Return the name
|
||||
return(genTav)
|
||||
|
@ -1,29 +1,24 @@
|
||||
import imdb
|
||||
import random
|
||||
import logging
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
from funcs import logThis
|
||||
|
||||
# Picks a random movie and returns information about it
|
||||
def movieFunc():
|
||||
try:
|
||||
print("Creating IMDb object")
|
||||
logging.info("Creating IMDb object")
|
||||
logThis("Creating IMDb object")
|
||||
ia = imdb.IMDb()
|
||||
|
||||
print("Picking a movie")
|
||||
logging.info("Picking a movie")
|
||||
logThis("Picking a movie")
|
||||
movs = open("resources/movies.txt", "r")
|
||||
movlist = movs.read().split("\n")
|
||||
mov = random.choice(movlist)
|
||||
movs.close()
|
||||
|
||||
print("Searching for "+mov)
|
||||
logging.info("Searching for "+mov)
|
||||
logThis("Searching for "+mov)
|
||||
s_result = ia.search_movie(mov)
|
||||
|
||||
print("Getting the data")
|
||||
logging.info("Getting the data")
|
||||
logThis("Getting the data")
|
||||
movie = s_result[0]
|
||||
ia.update(movie)
|
||||
cast = movie['cast']
|
||||
@ -31,10 +26,9 @@ def movieFunc():
|
||||
for x in range(3):
|
||||
if cast[x]:
|
||||
pcast += cast[x]['name']+", "
|
||||
print("Successfully ran !movie")
|
||||
logging.info("Successfully ran !movie")
|
||||
|
||||
logThis("Successfully ran !movie")
|
||||
return(movie['title'], movie['plot'][0].split("::")[0], movie['cover url'].replace("150","600").replace("101","404"), pcast[:-2])
|
||||
except:
|
||||
print("Something bad happened...")
|
||||
logging.info("Something bad happened...")
|
||||
logThis("Something bad happened...")
|
||||
return("error","","","")
|
||||
|
@ -1,4 +1,3 @@
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
import traceback
|
||||
@ -9,8 +8,7 @@ from re import IGNORECASE
|
||||
import numexpr
|
||||
|
||||
from . import errors
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
#from funcs import logThis
|
||||
|
||||
VALID_OPERATORS = 'k|rr|ro|mi|ma|ra|e|p'
|
||||
VALID_OPERATORS_ARRAY = VALID_OPERATORS.split('|')
|
||||
@ -41,10 +39,10 @@ def get_roll_comment(rollStr):
|
||||
no_comment = ''
|
||||
dice_set = re.split('([-+*/().=])', rollStr)
|
||||
dice_set = [d for d in dice_set if not d in (None, '')]
|
||||
logging.debug("Found dice set: " + str(dice_set))
|
||||
#logThis("Found dice set: " + str(dice_set))
|
||||
for index, dice in enumerate(dice_set):
|
||||
match = DICE_PATTERN.match(dice)
|
||||
logging.debug("Found dice group: " + str(match.groups()))
|
||||
#logThis("Found dice group: " + str(match.groups()))
|
||||
no_comment += dice.replace(match.group(5), '')
|
||||
if match.group(5):
|
||||
comment = match.group(5) + ''.join(dice_set[index + 1:])
|
||||
@ -58,7 +56,7 @@ def get_roll_comment(rollStr):
|
||||
|
||||
class Roll(object):
|
||||
def __init__(self, parts=None):
|
||||
if parts is None:
|
||||
if parts ==None:
|
||||
parts = []
|
||||
self.parts = parts
|
||||
|
||||
@ -85,10 +83,10 @@ class Roll(object):
|
||||
# parse each, returning a SingleDiceResult
|
||||
dice_set = re.split('([-+*/().=])', rollStr)
|
||||
dice_set = [d for d in dice_set if not d in (None, '')]
|
||||
logging.debug("Found dice set: " + str(dice_set))
|
||||
#logThis("Found dice set: " + str(dice_set))
|
||||
for index, dice in enumerate(dice_set):
|
||||
match = DICE_PATTERN.match(dice)
|
||||
logging.debug("Found dice group: " + str(match.groups()))
|
||||
#logThis("Found dice group: " + str(match.groups()))
|
||||
# check if it's dice
|
||||
if match.group(1):
|
||||
roll = self.roll_one(dice.replace(match.group(5), ''), adv)
|
||||
@ -111,7 +109,7 @@ class Roll(object):
|
||||
except SyntaxError:
|
||||
raise errors.InvalidArgument("No dice found to roll.")
|
||||
rolled = ' '.join(str(res) for res in self.parts if not isinstance(res, Comment))
|
||||
if rollFor is '':
|
||||
if rollFor =='':
|
||||
rollFor = ''.join(str(c) for c in self.parts if isinstance(c, Comment))
|
||||
# return final solution
|
||||
if not inline:
|
||||
@ -120,7 +118,7 @@ class Roll(object):
|
||||
str(res) for res in self.parts if not isinstance(res, Comment)) + '\n**Total:** ' + str(
|
||||
floor(total))
|
||||
skeletonReply = reply
|
||||
rollFor = rollFor if rollFor is not '' else 'Result'
|
||||
rollFor = rollFor if rollFor != '' else 'Result'
|
||||
reply = '**{}:** '.format(rollFor) + reply
|
||||
if show_blurbs:
|
||||
if adv == 1:
|
||||
@ -138,7 +136,7 @@ class Roll(object):
|
||||
reply = ' '.join(str(res) for res in self.parts if not isinstance(res, Comment)) + ' = `' + str(
|
||||
floor(total)) + '`'
|
||||
skeletonReply = reply
|
||||
rollFor = rollFor if rollFor is not '' else 'Result'
|
||||
rollFor = rollFor if rollFor != '' else 'Result'
|
||||
reply = '**{}:** '.format(rollFor) + reply
|
||||
if show_blurbs:
|
||||
if adv == 1:
|
||||
@ -157,7 +155,7 @@ class Roll(object):
|
||||
skeleton=skeletonReply, raw_dice=self)
|
||||
except Exception as ex:
|
||||
if not isinstance(ex, (SyntaxError, KeyError, errors.AvraeException)):
|
||||
logging.error('Error in roll() caused by roll {}:'.format(rollStr))
|
||||
#logThis('Error in roll() caused by roll {}:'.format(rollStr))
|
||||
traceback.print_exc()
|
||||
return DiceResult(verbose_result="Invalid input: {}".format(ex))
|
||||
|
||||
@ -168,7 +166,7 @@ class Roll(object):
|
||||
split = re.match(r'^([^\[\]]*?)\s*(\[.*\])?\s*$', dice)
|
||||
dice = split.group(1).strip()
|
||||
annotation = split.group(2)
|
||||
result.annotation = annotation if annotation is not None else ''
|
||||
result.annotation = annotation if annotation != None else ''
|
||||
# Recognizes dice
|
||||
obj = re.findall('\d+', dice)
|
||||
obj = [int(x) for x in obj]
|
||||
@ -180,21 +178,21 @@ class Roll(object):
|
||||
raise errors.InvalidArgument('Please pass in the value of the dice.')
|
||||
numDice = 1
|
||||
diceVal = obj[0]
|
||||
if adv is not 0 and diceVal == 20:
|
||||
if adv != 0 and diceVal == 20:
|
||||
numDice = 2
|
||||
ops = ['k', 'h1'] if adv is 1 else ['k', 'l1']
|
||||
ops = ['k', 'h1'] if adv ==1 else ['k', 'l1']
|
||||
elif numArgs == 2:
|
||||
numDice = obj[0]
|
||||
diceVal = obj[-1]
|
||||
if adv is not 0 and diceVal == 20:
|
||||
ops = ['k', 'h' + str(numDice)] if adv is 1 else ['k', 'l' + str(numDice)]
|
||||
if adv != 0 and diceVal == 20:
|
||||
ops = ['k', 'h' + str(numDice)] if adv ==1 else ['k', 'l' + str(numDice)]
|
||||
numDice = numDice * 2
|
||||
else: # split into xdy and operators
|
||||
numDice = obj[0]
|
||||
diceVal = obj[1]
|
||||
dice = re.split('(\d+d\d+)', dice)[-1]
|
||||
ops = VALID_OPERATORS_2.split(dice)
|
||||
ops = [a for a in ops if a is not None]
|
||||
ops = [a for a in ops if a != None]
|
||||
|
||||
# dice repair/modification
|
||||
if numDice > 300 or diceVal < 1:
|
||||
@ -215,7 +213,7 @@ class Roll(object):
|
||||
except:
|
||||
result.rolled.append(SingleDice())
|
||||
|
||||
if ops is not None:
|
||||
if ops != None:
|
||||
|
||||
rerollList = []
|
||||
reroll_once = []
|
||||
@ -226,7 +224,7 @@ class Roll(object):
|
||||
valid_operators = VALID_OPERATORS_ARRAY
|
||||
last_operator = None
|
||||
for index, op in enumerate(ops):
|
||||
if last_operator is not None and op in valid_operators and not op == last_operator:
|
||||
if last_operator != None and op in valid_operators and not op == last_operator:
|
||||
result.reroll(reroll_once, 1)
|
||||
reroll_once = []
|
||||
result.reroll(rerollList, greedy=True)
|
||||
@ -240,10 +238,10 @@ class Roll(object):
|
||||
if op == 'rr':
|
||||
rerollList += parse_selectors([list_get(index + 1, 0, ops)], result, greedy=True)
|
||||
if op == 'k':
|
||||
keep = [] if keep is None else keep
|
||||
keep = [] if keep ==None else keep
|
||||
keep += parse_selectors([list_get(index + 1, 0, ops)], result)
|
||||
if op == 'p':
|
||||
keep = [] if keep is None else keep
|
||||
keep = [] if keep ==None else keep
|
||||
keep += parse_selectors([list_get(index + 1, 0, ops)], result, inverse=True)
|
||||
if op == 'ro':
|
||||
reroll_once += parse_selectors([list_get(index + 1, 0, ops)], result)
|
||||
@ -280,9 +278,9 @@ class Part:
|
||||
class SingleDiceGroup(Part):
|
||||
def __init__(self, num_dice: int = 0, max_value: int = 0, rolled=None, annotation: str = "", result: str = "",
|
||||
operators=None):
|
||||
if operators is None:
|
||||
if operators ==None:
|
||||
operators = []
|
||||
if rolled is None:
|
||||
if rolled ==None:
|
||||
rolled = []
|
||||
self.num_dice = num_dice
|
||||
self.max_value = max_value
|
||||
@ -292,7 +290,7 @@ class SingleDiceGroup(Part):
|
||||
self.operators = operators
|
||||
|
||||
def keep(self, rolls_to_keep):
|
||||
if rolls_to_keep is None: return
|
||||
if rolls_to_keep ==None: return
|
||||
for _roll in self.rolled:
|
||||
if not _roll.value in rolls_to_keep:
|
||||
_roll.kept = False
|
||||
@ -412,7 +410,7 @@ class SingleDice:
|
||||
class Constant(Part):
|
||||
def __init__(self, value: int = 0, annotation: str = ""):
|
||||
self.value = value
|
||||
self.annotation = annotation if annotation is not None else ''
|
||||
self.annotation = annotation if annotation != None else ''
|
||||
|
||||
def __str__(self):
|
||||
return "{0.value} {0.annotation}".format(self)
|
||||
@ -426,8 +424,8 @@ class Constant(Part):
|
||||
|
||||
class Operator(Part):
|
||||
def __init__(self, op: str = "+", annotation: str = ""):
|
||||
self.op = op if op is not None else ''
|
||||
self.annotation = annotation if annotation is not None else ''
|
||||
self.op = op if op != None else ''
|
||||
self.annotation = annotation if annotation != None else ''
|
||||
|
||||
def __str__(self):
|
||||
return "{0.op} {0.annotation}".format(self)
|
||||
@ -453,16 +451,16 @@ class Comment(Part):
|
||||
def parse_selectors(opts, res, greedy=False, inverse=False):
|
||||
"""Returns a list of ints."""
|
||||
for o in range(len(opts)):
|
||||
if opts[o][0] is 'h':
|
||||
if opts[o][0] =='h':
|
||||
opts[o] = nlargest(int(opts[o].split('h')[1]), (d.value for d in res.rolled if d.kept))
|
||||
elif opts[o][0] is 'l':
|
||||
elif opts[o][0] =='l':
|
||||
opts[o] = nsmallest(int(opts[o].split('l')[1]), (d.value for d in res.rolled if d.kept))
|
||||
elif opts[o][0] is '>':
|
||||
elif opts[o][0] =='>':
|
||||
if greedy:
|
||||
opts[o] = list(range(int(opts[o].split('>')[1]) + 1, res.max_value + 1))
|
||||
else:
|
||||
opts[o] = [d.value for d in res.rolled if d.value > int(opts[o].split('>')[1])]
|
||||
elif opts[o][0] is '<':
|
||||
elif opts[o][0] =='<':
|
||||
if greedy:
|
||||
opts[o] = list(range(1, int(opts[o].split('<')[1])))
|
||||
else:
|
||||
@ -472,7 +470,7 @@ def parse_selectors(opts, res, greedy=False, inverse=False):
|
||||
if isinstance(o, list):
|
||||
out.extend(int(l) for l in o)
|
||||
elif not greedy:
|
||||
out.extend(int(o) for a in res.rolled if a.value is int(o) and a.kept)
|
||||
out.extend(int(o) for a in res.rolled if a.value ==int(o) and a.kept)
|
||||
else:
|
||||
out.append(int(o))
|
||||
|
||||
@ -498,7 +496,7 @@ class DiceResult:
|
||||
self.result = verbose_result
|
||||
self.crit = crit
|
||||
self.rolled = rolled
|
||||
self.skeleton = skeleton if skeleton is not '' else verbose_result
|
||||
self.skeleton = skeleton if skeleton != '' else verbose_result
|
||||
self.raw_dice = raw_dice # Roll
|
||||
|
||||
def __str__(self):
|
||||
@ -509,7 +507,7 @@ class DiceResult:
|
||||
|
||||
def consolidated(self):
|
||||
"""Gets the most simplified version of the roll string."""
|
||||
if self.raw_dice is None:
|
||||
if self.raw_dice ==None:
|
||||
return "0"
|
||||
parts = [] # list of (part, annotation)
|
||||
last_part = ""
|
||||
|
@ -1,19 +1,22 @@
|
||||
import json
|
||||
import string
|
||||
import logging
|
||||
|
||||
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
|
||||
from funcs import logThis
|
||||
|
||||
def getName(user : str):
|
||||
logThis("Getting name for "+user+"'s character")
|
||||
with open("resources/swcharacters.json", "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
if user in data:
|
||||
logThis("Name is "+data[user]["Name"])
|
||||
return data[user]["Name"]
|
||||
else:
|
||||
logThis("Just using "+user)
|
||||
return user
|
||||
|
||||
def setUpDict(cmd : dict):
|
||||
logThis("Setting up a dictionary in a nice way")
|
||||
if bool(cmd):
|
||||
keys = list(cmd)
|
||||
values = list(cmd.values())
|
||||
@ -22,12 +25,20 @@ def setUpDict(cmd : dict):
|
||||
return ", ".join(values)
|
||||
else:
|
||||
for x in range(len(keys)):
|
||||
if x%3 != 2:
|
||||
result += "**" + keys[x] + "**" + ": " + str(values[x]) + " "
|
||||
if type(keys[x]) is list:
|
||||
if x%3 != 2:
|
||||
result += "**" + keys[x] + "**" + ": " + ", ".join(values[x]) + " "
|
||||
else:
|
||||
result += "**" + keys[x] + "**" + ": " + ", ".join(values[x]) + "\n"
|
||||
else:
|
||||
result += "**" + keys[x] + "**" + ": " + str(values[x]) + "\n"
|
||||
if x%3 != 2:
|
||||
result += "**" + keys[x] + "**" + ": " + str(values[x]) + " "
|
||||
else:
|
||||
result += "**" + keys[x] + "**" + ": " + str(values[x]) + "\n"
|
||||
logThis("Returning a dictionary, but well formatted")
|
||||
return result
|
||||
else:
|
||||
logThis("Couldn't find anything")
|
||||
return "There doesn't seem to be anything here..."
|
||||
|
||||
def lookUp(data : dict, key : str, cmd : str = ""):
|
||||
@ -39,62 +50,87 @@ def lookUp(data : dict, key : str, cmd : str = ""):
|
||||
if cmd == "":
|
||||
break
|
||||
|
||||
logThis("Looking up "+key)
|
||||
if key in data:
|
||||
logThis(key+" exists")
|
||||
if cmd == "":
|
||||
if type(data[key]) is dict and key != "Weapons":
|
||||
return setUpDict(data[key])
|
||||
elif key == "Weapons":
|
||||
logThis("Does this even get used? I'm too scared to delete it")
|
||||
if bool(data[key]):
|
||||
logThis("Found "+(", ".join(list(data[key]))))
|
||||
return ", ".join(list(data[key]))
|
||||
else:
|
||||
logThis("There is nothing here")
|
||||
return "There doesn't seem to be anything here..."
|
||||
else:
|
||||
return data[key]
|
||||
if str(data[key]) != "":
|
||||
logThis("Returning "+str(data[key]))
|
||||
return data[key]
|
||||
else:
|
||||
logThis("There was nothing there")
|
||||
return "There doesn't seem to be anything here"
|
||||
elif cmd[0] == '+':
|
||||
logThis("Trying to add to "+key)
|
||||
try:
|
||||
cmd = cmd[1:]
|
||||
while cmd[0] == ' ':
|
||||
cmd = cmd[1:]
|
||||
except:
|
||||
logThis("Yeah, that fucked up")
|
||||
return "Can't do that"
|
||||
|
||||
if type(data[key]) is int:
|
||||
try:
|
||||
newValue = data[key] + int(cmd)
|
||||
data[key] = newValue
|
||||
logThis("Added "+cmd+" to "+key)
|
||||
return data
|
||||
except:
|
||||
logThis("Couldn't add "+cmd+" to "+key)
|
||||
return "Can't add that"
|
||||
elif type(data[key]) is list:
|
||||
try:
|
||||
data[key].append(cmd)
|
||||
logThis("Added "+cmd+" to "+key)
|
||||
return data
|
||||
except:
|
||||
logThis("Couldn't add "+cmd+" to "+key)
|
||||
return "Can't add that"
|
||||
else:
|
||||
logThis("Yeah, I can't add that to "+key)
|
||||
return "Can't add that"
|
||||
|
||||
elif cmd[0] == '-':
|
||||
logThis("Trying to remove/subtract from "+key)
|
||||
try:
|
||||
cmd = cmd[1:]
|
||||
while cmd[0] == ' ':
|
||||
cmd = cmd[1:]
|
||||
except:
|
||||
logThis("Yeah, that fucked up")
|
||||
return "Can't do that"
|
||||
|
||||
if type(data[key]) is int:
|
||||
try:
|
||||
newValue = data[key] - int(cmd)
|
||||
data[key] = newValue
|
||||
logThis("Subtracted "+cmd+" from "+key)
|
||||
return data
|
||||
except:
|
||||
logThis("Couldn't subtract "+cmd+" from "+key)
|
||||
return "Can't remove that"
|
||||
elif type(data[key]) is list:
|
||||
try:
|
||||
data[key].remove(cmd)
|
||||
logThis("Removed "+cmd+" from "+key)
|
||||
return data
|
||||
except:
|
||||
logThis("Couldn't remove "+cmd+" from "+key)
|
||||
return "Can't remove that"
|
||||
else:
|
||||
logThis("Yeah, I can't remove/subtract that from "+key)
|
||||
return "Can't remove that"
|
||||
else:
|
||||
while cmd[0] == ' ':
|
||||
@ -103,22 +139,34 @@ def lookUp(data : dict, key : str, cmd : str = ""):
|
||||
if type(data[key]) is dict:
|
||||
newKey = cmd.split(" ")[0]
|
||||
cmd = cmd[len(newKey):]
|
||||
while cmd[0] == " ":
|
||||
cmd = cmd[1:]
|
||||
if cmd == "":
|
||||
break
|
||||
data[key] = lookUp(data[key],newKey,cmd)
|
||||
return data
|
||||
if cmd != "":
|
||||
while cmd[0] == " ":
|
||||
cmd = cmd[1:]
|
||||
if cmd == "":
|
||||
break
|
||||
logThis("Looking up "+newKey+" in "+key)
|
||||
lookUpResult = lookUp(data[key],newKey,cmd)
|
||||
if type(lookUpResult) is dict:
|
||||
data[key] = lookUpResult
|
||||
return data
|
||||
else:
|
||||
return lookUpResult
|
||||
elif type(data[key]) != list:
|
||||
logThis("Trying to change "+key+" to "+cmd)
|
||||
try:
|
||||
cmd = type(data[key])(cmd)
|
||||
data[key] = cmd
|
||||
logThis("Did that")
|
||||
return data
|
||||
except:
|
||||
logThis("No. That did not work")
|
||||
return "Wrong data type"
|
||||
else:
|
||||
logThis("Yeah, that didn't work")
|
||||
return "Wrong data type"
|
||||
else:
|
||||
logThis("Couldn't find "+key)
|
||||
logThis("Testing to see if it's a multi-word key")
|
||||
cmd = key + " " + cmd
|
||||
words = cmd.split(" ")
|
||||
search = ""
|
||||
@ -128,9 +176,11 @@ def lookUp(data : dict, key : str, cmd : str = ""):
|
||||
search += " " + words[i]
|
||||
i += 1
|
||||
except:
|
||||
logThis("It wasn't. "+search+" doesn't exist")
|
||||
return search + " doesn't exist"
|
||||
if search[0] == " ":
|
||||
search = search[1:]
|
||||
logThis("Yeah! Did that! The key was "+search)
|
||||
|
||||
cmd = cmd[len(search):]
|
||||
if cmd != "":
|
||||
@ -138,16 +188,18 @@ def lookUp(data : dict, key : str, cmd : str = ""):
|
||||
cmd = cmd[1:]
|
||||
if cmd == "":
|
||||
break
|
||||
|
||||
|
||||
if cmd == "":
|
||||
logThis("Returning "+search)
|
||||
return setUpDict(data[search])
|
||||
else:
|
||||
newKey = cmd.split(" ")[0]
|
||||
cmd = cmd[len(newKey):]
|
||||
while cmd[0] == " ":
|
||||
cmd = cmd[1:]
|
||||
if cmd == "":
|
||||
break
|
||||
if cmd != "":
|
||||
while cmd[0] == " ":
|
||||
cmd = cmd[1:]
|
||||
if cmd == "":
|
||||
break
|
||||
lookUpResult = lookUp(data[search],newKey,cmd)
|
||||
if type(lookUpResult) is dict:
|
||||
data[search] = lookUpResult
|
||||
@ -156,6 +208,7 @@ def lookUp(data : dict, key : str, cmd : str = ""):
|
||||
return lookUpResult
|
||||
|
||||
def characterSheet(character : dict):
|
||||
logThis("Setting up a character sheet for "+character["Name"])
|
||||
divider = "--------------------\n"
|
||||
name = character["Name"]
|
||||
textf = ""
|
||||
@ -197,30 +250,40 @@ def charData(user : str,cmd : str):
|
||||
cmd = cmd[1:]
|
||||
if cmd == "":
|
||||
break
|
||||
|
||||
|
||||
logThis("Looking for "+user+"'s character")
|
||||
if user in data:
|
||||
logThis("Foundt it! Looking for "+key+" in the data")
|
||||
if key in data[user]:
|
||||
logThis("Found it!")
|
||||
if type(data[user][key]) is dict:
|
||||
logThis("It's a dictionary!")
|
||||
if cmd == "":
|
||||
logThis("Retrieving data")
|
||||
if key == "Weapons":
|
||||
if bool(data[user][key]):
|
||||
logThis("Returning a list of weapons")
|
||||
return ", ".join(list(data[user][key]))
|
||||
else:
|
||||
logThis("The character doesn't have any weapons. Which is probably for the best. Like, who just walks around with weapons?")
|
||||
return "There doesn't seem to be anything there..."
|
||||
else:
|
||||
return setUpDict(data[user][key])
|
||||
elif cmd[0] == "+":
|
||||
logThis("Gonna add something!!!")
|
||||
try:
|
||||
cmd = cmd[1:]
|
||||
while cmd[0] == ' ':
|
||||
cmd = cmd[1:]
|
||||
except:
|
||||
logThis("Nope. That didn't happen")
|
||||
return "Can't do that"
|
||||
|
||||
if (key == "Talents" or key == "Force-powers") and "," in cmd:
|
||||
cmd = cmd.split(",")
|
||||
while cmd[1][0] == " ":
|
||||
cmd[1] = cmd[1][1:]
|
||||
logThis("Adding "+cmd[0]+" to "+key)
|
||||
data[user][key][cmd[0]] = cmd[1]
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
@ -230,9 +293,11 @@ def charData(user : str,cmd : str):
|
||||
cmd = cmd.split(",")
|
||||
while cmd[1][0] == " ":
|
||||
cmd[1] = cmd[1][1:]
|
||||
logThis("Adding "+cmd[0]+" to "+key)
|
||||
try:
|
||||
data[user][key][cmd[0]] = int(cmd[1])
|
||||
except:
|
||||
logThis("Fucked that up")
|
||||
return "Wrong data type"
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
@ -242,6 +307,7 @@ def charData(user : str,cmd : str):
|
||||
with open("resources/swtemplates.json", "r") as f:
|
||||
templates = json.load(f)
|
||||
newWeapon = templates["Weapon"]
|
||||
logThis("Adding "+cmd+" to "+key)
|
||||
data[user][key][cmd] = newWeapon
|
||||
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
@ -249,34 +315,42 @@ def charData(user : str,cmd : str):
|
||||
return cmd+" added to weapons for " + data[user]["Name"]
|
||||
|
||||
else:
|
||||
logThis("That's not happening")
|
||||
return "Can't add that"
|
||||
|
||||
elif cmd[0] == "-":
|
||||
logThis("Gonna subtract/remove something")
|
||||
try:
|
||||
cmd = cmd[1:]
|
||||
while cmd[0] == ' ':
|
||||
cmd = cmd[1:]
|
||||
except:
|
||||
logThis("AAAAAAAAAAAA")
|
||||
return "Can't do that"
|
||||
|
||||
if key == "Talents" or key == "Force-powers" or key == "Weapons" or key == "Obligations":
|
||||
logThis("Trying to remove "+cmd+" from "+key)
|
||||
if cmd in data[user][key]:
|
||||
del data[user][key][cmd]
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
return cmd+" removed from "+key+" for "+data[user]["Name"]
|
||||
logThis("I did that")
|
||||
return cmd+" removed from "+key+" from "+data[user]["Name"]
|
||||
else:
|
||||
logThis("Welp. I fucked that up")
|
||||
return "Can't remove that"
|
||||
else:
|
||||
logThis("Urgh!")
|
||||
return "Can't remove that"
|
||||
|
||||
else:
|
||||
if key != "Talents" and key != "Force-powers":
|
||||
newKey = string.capwords(cmd.split(" ")[0])
|
||||
newcmd = cmd[len(newKey):]
|
||||
else:
|
||||
logThis("Looking up "+cmd+" in "+key)
|
||||
if key == "Talents" or key == "Force-powers":
|
||||
newKey = cmd
|
||||
newcmd = ""
|
||||
else:
|
||||
newKey = string.capwords(cmd.split(" ")[0])
|
||||
newcmd = cmd[len(newKey):]
|
||||
|
||||
lookUpResult = lookUp(data[user][key],newKey,newcmd)
|
||||
|
||||
@ -289,69 +363,86 @@ def charData(user : str,cmd : str):
|
||||
return lookUpResult
|
||||
else:
|
||||
if cmd == "":
|
||||
logThis("Retrieving data")
|
||||
if type(data[user][key]) is list:
|
||||
return key+":\n"+", ".join(data[user][key])
|
||||
else:
|
||||
return data[user][key]
|
||||
elif cmd[0] == '+':
|
||||
logThis("Adding")
|
||||
try:
|
||||
cmd = cmd[1:]
|
||||
while cmd[0] == ' ':
|
||||
cmd = cmd[1:]
|
||||
except:
|
||||
logThis("Error message")
|
||||
return "Can't do that"
|
||||
|
||||
if type(data[user][key]) is int:
|
||||
try:
|
||||
logThis("Adding "+cmd+" to "+key)
|
||||
beforeData = data[user][key]
|
||||
data[user][key] = beforeData+ int(cmd)
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
return "Added " + cmd + " to " + data[user]["Name"] + "'s " + key
|
||||
except:
|
||||
logThis("BITCH SANDWICH")
|
||||
return "Can't add that"
|
||||
elif type(data[user][key]) is list:
|
||||
try:
|
||||
logThis("Adding "+cmd+" to "+key)
|
||||
data[user][key].append(cmd)
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
return "Added " + cmd + " to " + data[user]["Name"] + "'s " + key
|
||||
except:
|
||||
logThis("tstststststs")
|
||||
return "Can't add that"
|
||||
else:
|
||||
logThis("Help")
|
||||
return "Can't add that"
|
||||
elif cmd[0] == '-':
|
||||
logThis("Removing/subtracting")
|
||||
try:
|
||||
cmd = cmd[1:]
|
||||
while cmd[0] == ' ':
|
||||
cmd = cmd[1:]
|
||||
except:
|
||||
logThis("lalalala")
|
||||
return "Can't do that"
|
||||
|
||||
if type(data[user][key]) is int:
|
||||
try:
|
||||
logThis("Subtracting "+cmd+" from "+key)
|
||||
beforeData = data[user][key]
|
||||
data[user][key] = beforeData - int(cmd)
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
return "Subtracted " + cmd + " from " + data[user]["Name"] + "'s " + key
|
||||
except:
|
||||
logThis("Tried it. Didn't want to")
|
||||
return "Can't remove that"
|
||||
elif type(data[user][key]) is list:
|
||||
try:
|
||||
logThis("removing "+cmd+" from "+key)
|
||||
beforeData = data[user][key]
|
||||
try:
|
||||
data[user][key].remove(cmd)
|
||||
except:
|
||||
logThis("They can only remove stuff that's actually in the list")
|
||||
return "Not in list"
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
return "Removed " + cmd + " from " + data[user]["Name"] + "'s " + key
|
||||
except:
|
||||
logThis("nah")
|
||||
return "Can't remove that"
|
||||
else:
|
||||
logThis("nyope")
|
||||
return "Can't remove that"
|
||||
else:
|
||||
logThis("Changing "+key+" to "+cmd)
|
||||
if type(data[user][key]) is int:
|
||||
try:
|
||||
data[user][key] = int(cmd)
|
||||
@ -360,14 +451,17 @@ def charData(user : str,cmd : str):
|
||||
elif type(data[user][key]) is str:
|
||||
data[user][key] = cmd
|
||||
else:
|
||||
logThis("I don't wanna tho")
|
||||
return "Can't do that"
|
||||
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
return "Changed " + data[user]["Name"] + "'s " + key +" to " + cmd
|
||||
else:
|
||||
logThis(key+" isn't in there")
|
||||
return "Couldn't find that data. Are you sure you spelled it correctly?"
|
||||
else:
|
||||
logThis(user+" doesn't have a character")
|
||||
return "You don't have a character. You can make one with !swchar"
|
||||
|
||||
def replaceSpaces(cmd : str):
|
||||
@ -408,6 +502,7 @@ def parseChar(user : str, cmd : str):
|
||||
text1, text2 = characterSheet(data[user])
|
||||
return text1, replaceWithSpaces(text2)
|
||||
else:
|
||||
logThis("Makin' a character for "+user)
|
||||
with open("resources/swtemplates.json", "r") as f:
|
||||
templates = json.load(f)
|
||||
newChar = templates["Character"]
|
||||
@ -417,6 +512,7 @@ def parseChar(user : str, cmd : str):
|
||||
return "", "Character for " + user + " created"
|
||||
else:
|
||||
if cmd == "Purge":
|
||||
logThis("Deleting "+user+"'s character")
|
||||
del data[user]
|
||||
with open("resources/swcharacters.json", "w") as f:
|
||||
json.dump(data,f,indent = 4)
|
||||
|
@ -1,6 +1,9 @@
|
||||
from . import swroll
|
||||
|
||||
from funcs import logThis
|
||||
|
||||
def destinyNew(num : int):
|
||||
logThis("Creating a new destiny pool with "+str(num)+" players")
|
||||
roll = swroll.roll(0,0,0,0,0,0,num)
|
||||
|
||||
with open("resources/destinyPoints.txt","wt") as f:
|
||||
@ -13,20 +16,26 @@ def destinyUse(user : str):
|
||||
points = f.read()
|
||||
|
||||
if user == "Nikolaj":
|
||||
logThis("Trying to use a dark side destiny point")
|
||||
if 'B' in points:
|
||||
points = points.replace("B","L",1)
|
||||
with open("resources/destinyPoints.txt","wt") as f:
|
||||
f.write(points)
|
||||
logThis("Did it")
|
||||
return "Used a dark side destiny point. Destiny pool is now:\n"+swroll.resultToEmoji(points)
|
||||
else:
|
||||
logThis("There were no dark side destiny points")
|
||||
return "No dark side destiny points"
|
||||
else:
|
||||
logThis("Trying to use a light side destiny point")
|
||||
if 'L' in points:
|
||||
points = points.replace("L","B",1)
|
||||
with open("resources/destinyPoints.txt","wt") as f:
|
||||
f.write(points)
|
||||
logThis("Did it")
|
||||
return "Used a light side destiny point. Destiny pool is now:\n"+swroll.resultToEmoji(points)
|
||||
else:
|
||||
logThis("There were no dark side destiny points")
|
||||
return "No light side destiny points"
|
||||
|
||||
def parseDestiny(user : str, cmd : str):
|
||||
@ -38,6 +47,7 @@ def parseDestiny(user : str, cmd : str):
|
||||
|
||||
|
||||
if cmd == "":
|
||||
logThis("Retrieving destiny pool info")
|
||||
with open("resources/destinyPoints.txt","rt") as f:
|
||||
return swroll.resultToEmoji(f.read())
|
||||
else:
|
||||
|
@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
|
||||
from . import swchar
|
||||
from funcs import logThis
|
||||
|
||||
with open("resources/swskills.json", "r") as f:
|
||||
skillData = json.load(f)
|
||||
@ -35,6 +36,7 @@ def roll(abi : int = 1, prof : int = 0, dif : int = 3, cha : int = 0, boo : int
|
||||
return result
|
||||
|
||||
def simplify(result : str):
|
||||
logThis("Simplifying "+result)
|
||||
simp = ""
|
||||
success = (result.count('S') + result.count('R')) - (result.count('F') + result.count('D'))
|
||||
advantage = result.count('A') - result.count('H')
|
||||
@ -110,10 +112,8 @@ def diceToEmoji(dice : list):
|
||||
|
||||
return emoji
|
||||
|
||||
def getDice(user : str, skill : str):
|
||||
return "yes"
|
||||
|
||||
def obligationRoll():
|
||||
logThis("Rolling for obligation")
|
||||
with open("resources/swcharacters.json", "r") as f:
|
||||
data = json.load(f)
|
||||
|
||||
@ -144,10 +144,13 @@ def parseRoll(user : str,cmd : str = ""):
|
||||
return obligationRoll()
|
||||
|
||||
elif string.capwords(commands[0]) in skillData:
|
||||
logThis("Oh look! This guy has skills!")
|
||||
if swchar.userHasChar:
|
||||
logThis("They have a character. That much we know")
|
||||
skillLevel = swchar.charData(user,"Skills " + string.capwords(commands[0]))
|
||||
|
||||
if string.capwords(commands[0]) == "Lightsaber":
|
||||
logThis("The skill is lightsaber")
|
||||
charLevel = swchar.charData(user,"Characteristics " + swchar.lightsaberChar(user))
|
||||
else:
|
||||
charLevel = swchar.charData(user,"Characteristics " + skillData[string.capwords(commands[0])])
|
||||
@ -156,16 +159,20 @@ def parseRoll(user : str,cmd : str = ""):
|
||||
proficiencyDice = min(skillLevel,charLevel)
|
||||
|
||||
commands = [str(abilityDice)] + [str(proficiencyDice)] + commands[1:]
|
||||
logThis("Converted skill to dice")
|
||||
else:
|
||||
logThis("Okay, no they don't i guess")
|
||||
return "You don't have a user. You can make one with !swchar"
|
||||
|
||||
elif string.capwords(commands[0]) in ["Ranged","Piloting"]:
|
||||
logThis("They fucked up writing the name of a ranged or piloting skill")
|
||||
if string.capwords(commands[0]) == "Ranged":
|
||||
return "Did you mean \"Ranged - Heavy\" or \"Ranged - Light\""
|
||||
else:
|
||||
return "Did you mean \"Piloting - Planetary\" or \"Piloting - Space\""
|
||||
|
||||
try:
|
||||
logThis("Converting commands to dice")
|
||||
for x in range(len(commands)):
|
||||
if commands[x-1] != "":
|
||||
if commands[x-1][0] == "A":
|
||||
@ -185,8 +192,10 @@ def parseRoll(user : str,cmd : str = ""):
|
||||
else:
|
||||
rollParameters[x-1] = int(commands[x-1])
|
||||
except:
|
||||
logThis("Someone fucked u-up! (it was them)")
|
||||
return "Invalid input!"
|
||||
|
||||
logThis("Rolling "+str(rollParameters))
|
||||
rollResults = roll(rollParameters[0],rollParameters[1],rollParameters[2],rollParameters[3],rollParameters[4],rollParameters[5],rollParameters[6])
|
||||
|
||||
simplified = simplify(rollResults)
|
||||
@ -194,7 +203,9 @@ def parseRoll(user : str,cmd : str = ""):
|
||||
name = swchar.getName(user)
|
||||
|
||||
if simplified != rollResults:
|
||||
return name + " rolls " + diceToEmoji(rollParameters) + "\nResult: " + resultToEmoji(rollResults) + "\nSimplified: " + resultToEmoji(simplify(rollResults))
|
||||
logThis("Returns results and simplified results")
|
||||
return name + " rolls " + diceToEmoji(rollParameters) + "\nResult: " + resultToEmoji(rollResults) + "\nSimplified: " + resultToEmoji(simplify(rollResults))
|
||||
else:
|
||||
logThis("Returns results")
|
||||
return name + " rolls " + diceToEmoji(rollParameters) + "\nResult: " + resultToEmoji(rollResults)
|
||||
|
||||
|
@ -473,7 +473,14 @@
|
||||
"Weapons": {
|
||||
"Lightsaber": {
|
||||
"Skill": "",
|
||||
"Damage": 2,
|
||||
"Damage": 0,
|
||||
"Range": "Engaged",
|
||||
"Crit": 0,
|
||||
"Special": []
|
||||
},
|
||||
"Light Blaster Pistol": {
|
||||
"Skill": "",
|
||||
"Damage": 0,
|
||||
"Range": "",
|
||||
"Crit": 0,
|
||||
"Special": []
|
||||
|
Reference in New Issue
Block a user