some cleaning up

This commit is contained in:
Nikolaj
2022-01-28 13:20:15 +01:00
parent 08435d6934
commit 2b21d43627
6 changed files with 320 additions and 325 deletions

View File

@ -15,9 +15,10 @@ class Generators():
yield (corpus[i], corpus[i+1], corpus[i+2]) yield (corpus[i], corpus[i+1], corpus[i+2])
# Generates a random name # Generates a random name
async def nameGen(self, ctx): async def name_gen(self, ctx):
# Makes a list of all names from "names.txt" # Makes a list of all names from "names.txt"
names = open('gwendolyn/resources/names.txt', encoding='utf8').read() with open("gwendolyn/resources/names.txt", "r", encoding='utf8') as file_pointer:
names = file_pointer.read()
corpus = list(names) corpus = list(names)
# Makes a list of pairs # Makes a list of pairs
@ -28,13 +29,13 @@ class Generators():
# Makes a dictionary of all letters that come after all other letters # Makes a dictionary of all letters that come after all other letters
for letter_1, letter_2 in pairs: for letter_1, letter_2 in pairs:
if letter_1 in letter_dict.keys(): if letter_1 in letter_dict:
letter_dict[letter_1].append(letter_2) letter_dict[letter_1].append(letter_2)
else: else:
letter_dict[letter_1] = [letter_2] letter_dict[letter_1] = [letter_2]
for letter_1, letter_2, letter_3 in triplets: for letter_1, letter_2, letter_3 in triplets:
if letter_1+letter_2 in letter_dict.keys(): if letter_1+letter_2 in letter_dict:
letter_dict[letter_1+letter_2].append(letter_3) letter_dict[letter_1+letter_2].append(letter_3)
else: else:
letter_dict[letter_1+letter_2] = [letter_3] letter_dict[letter_1+letter_2] = [letter_3]
@ -60,7 +61,7 @@ class Generators():
done = False done = False
# Creates the name one letter at a time # Creates the name one letter at a time
while done == False: while not done:
if random.randint(1,10) > 1: if random.randint(1,10) > 1:
try: try:
new_letter = random.choice(letter_dict[chain[-2]+chain[-1]]) new_letter = random.choice(letter_dict[chain[-2]+chain[-1]])
@ -79,15 +80,15 @@ class Generators():
await ctx.send(gen_name) await ctx.send(gen_name)
# Generates a random tavern name # Generates a random tavern name
async def tavernGen(self, ctx): async def tavern_gen(self, ctx):
# _lists first parts, second parts and third parts of tavern names # _lists first parts, second parts and third parts of tavern names
fp = ["The Silver","The Golden","The Staggering","The Laughing","The Prancing","The Gilded","The Running","The Howling","The Slaughtered","The Leering","The Drunken","The Leaping","The Roaring","The Frowning","The Lonely","The Wandering","The Mysterious","The Barking","The Black","The Gleaming","The Tap-Dancing","The Sad","The Sexy","The Artificial","The Groovy","The Merciful","The Confused","The Pouting","The Horny","The Okay","The Friendly","The Hungry","The Handicapped","The Fire-breathing","The One-Eyed","The Psychotic","The Mad","The Evil","The Idiotic","The Trusty","The Busty"] first_part = ["The Silver","The Golden","The Staggering","The Laughing","The Prancing","The Gilded","The Running","The Howling","The Slaughtered","The Leering","The Drunken","The Leaping","The Roaring","The Frowning","The Lonely","The Wandering","The Mysterious","The Barking","The Black","The Gleaming","The Tap-Dancing","The Sad","The Sexy","The Artificial","The Groovy","The Merciful","The Confused","The Pouting","The Horny","The Okay","The Friendly","The Hungry","The Handicapped","The Fire-breathing","The One-Eyed","The Psychotic","The Mad","The Evil","The Idiotic","The Trusty","The Busty"]
sp = ["Eel","Dolphin","Dwarf","Pegasus","Pony","Rose","Stag","Wolf","Lamb","Demon","Goat","Spirit","Horde","Jester","Mountain","Eagle","Satyr","Dog","Spider","Star","Dad","Rat","Jeremy","Mouse","Unicorn","Pearl","Ant","Crab","Penguin","Octopus","Lawyer","Ghost","Toad","Handjob","Immigrant","SJW","Dragon","Bard","Sphinx","Soldier","Salmon","Owlbear","Kite","Frost Giant","Arsonist"] second_part = ["Eel","Dolphin","Dwarf","Pegasus","Pony","Rose","Stag","Wolf","Lamb","Demon","Goat","Spirit","Horde","Jester","Mountain","Eagle","Satyr","Dog","Spider","Star","Dad","Rat","Jeremy","Mouse","Unicorn","Pearl","Ant","Crab","Penguin","Octopus","Lawyer","Ghost","Toad","Handjob","Immigrant","SJW","Dragon","Bard","Sphinx","Soldier","Salmon","Owlbear","Kite","Frost Giant","Arsonist"]
tp = [" Tavern"," Inn","","","","","","","","",""] third_part = [" Tavern"," Inn","","","","","","","","",""]
# Picks one of each # Picks one of each
genTav = random.choice(fp)+" "+random.choice(sp)+random.choice(tp) gen_tav = random.choice(first_part)+" "+random.choice(second_part)+random.choice(third_part)
self.bot.log("Generated "+genTav) self.bot.log("Generated "+gen_tav)
# Return the name # Return the name
await ctx.send(genTav) await ctx.send(gen_tav)

View File

@ -1,4 +1,8 @@
import discord, discord_slash, wolframalpha, requests, os import os
import requests
import discord
import wolframalpha
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
class NerdShit(): class NerdShit():
@ -6,9 +10,9 @@ class NerdShit():
"""Runs misc commands.""" """Runs misc commands."""
self.bot = bot self.bot = bot
async def wolfSearch(self,ctx,content): async def wolf_search(self,ctx,content):
await self.bot.defer(ctx) await self.bot.defer(ctx)
fnt = ImageFont.truetype('gwendolyn/resources/fonts/times-new-roman.ttf', 20) font = ImageFont.truetype('gwendolyn/resources/fonts/times-new-roman.ttf', 20)
self.bot.log("Requesting data") self.bot.log("Requesting data")
bot = wolframalpha.Client(self.bot.credentials["wolfram_alpha_key"]) bot = wolframalpha.Client(self.bot.credentials["wolfram_alpha_key"])
res = bot.query(content) res = bot.query(content)
@ -19,33 +23,33 @@ class NerdShit():
if int(res.numpods) > 0: if int(res.numpods) > 0:
for pod in res.pods: for pod in res.pods:
titles += [pod.title] titles += [pod.title]
for x, sub in enumerate(pod.subpods): for i, sub in enumerate(pod.subpods):
pods += [sub] pods += [sub]
if x > 0: if i > 0:
titles += [""] titles += [""]
podChunks = [pods[x:x+2] for x in range(0, len(pods), 2)] pod_chunks = [pods[x:x+2] for x in range(0, len(pods), 2)]
titleChucks = [titles[x:x+2] for x in range(0, len(titles), 2)] title_chunks = [titles[x:x+2] for x in range(0, len(titles), 2)]
await ctx.send(f"Response for \"{content}\"") await ctx.send(f"Response for \"{content}\"")
for x, chunk in enumerate(podChunks): for i, chunk in enumerate(pod_chunks):
width = 0 width = 0
for title in titleChucks[x]: for title in title_chunks[i]:
width = max(width,fnt.getsize(title)[0]) width = max(width,font.getsize(title)[0])
height = 5 height = 5
heights = [] heights = []
for count, pod in enumerate(chunk): for count, pod in enumerate(chunk):
heights += [height] heights += [height]
width = max(width,int(pod.img['@width'])) width = max(width,int(pod.img['@width']))
if titleChucks[x][count] == "": if title_chunks[i][count] == "":
placeFor_text = 0 place_for_text = 0
else: else:
placeFor_text = 30 place_for_text = 30
height += int(pod.img["@height"]) + 10 + placeFor_text height += int(pod.img["@height"]) + 10 + place_for_text
width += 10 width += 10
height += 5 height += 5
wolfImage = Image.new("RGB",(width,height),color=(255,255,255)) wolf_image = Image.new("RGB",(width,height),color=(255,255,255))
for count, pod in enumerate(chunk): for count, pod in enumerate(chunk):
response = requests.get(pod.img["@src"]) response = requests.get(pod.img["@src"])
@ -53,29 +57,29 @@ class NerdShit():
file.write(response.content) file.write(response.content)
file.close() file.close()
old_image = Image.open("gwendolyn/resources/wolfTemp.png") old_image = Image.open("gwendolyn/resources/wolfTemp.png")
oldSize = old_image.size old_size = old_image.size
if titleChucks[x][count] == "": if title_chunks[i][count] == "":
placeFor_text = 0 place_for_text = 0
else: else:
placeFor_text = 30 place_for_text = 30
newSize = (width,int(oldSize[1]+10+placeFor_text)) new_size = (width,int(old_size[1]+10+place_for_text))
new_image = Image.new("RGB",newSize,color=(255,255,255)) new_image = Image.new("RGB",new_size,color=(255,255,255))
new_image.paste(old_image, (int((int(oldSize[0]+10)-oldSize[0])/2),int(((newSize[1]-placeFor_text)-oldSize[1])/2)+placeFor_text)) new_image.paste(old_image, (int((int(old_size[0]+10)-old_size[0])/2),int(((new_size[1]-place_for_text)-old_size[1])/2)+place_for_text))
if titleChucks[x][count] != "": if title_chunks[i][count] != "":
d = ImageDraw.Draw(new_image,"RGB") drawer = ImageDraw.Draw(new_image,"RGB")
d.text((5,7),titleChucks[x][count],font=fnt,fill=(150,150,150)) drawer.text((5,7),title_chunks[i][count],font=font,fill=(150,150,150))
wolfImage.paste(new_image,(0,heights[count])) wolf_image.paste(new_image,(0,heights[count]))
new_image.close() new_image.close()
old_image.close() old_image.close()
count += 1 count += 1
wolfImage.save("gwendolyn/resources/wolf.png") wolf_image.save("gwendolyn/resources/wolf.png")
wolfImage.close() wolf_image.close()
await ctx.channel.send(file = discord.File("gwendolyn/resources/wolf.png")) await ctx.channel.send(file = discord.File("gwendolyn/resources/wolf.png"))
os.remove("gwendolyn/resources/wolf.png") os.remove("gwendolyn/resources/wolf.png")
os.remove("gwendolyn/resources/wolfTemp.png") os.remove("gwendolyn/resources/wolfTemp.png")
else: else:
self.bot.log("No returned data") self.bot.log("No returned data")
await ctx.send("Could not find anything relating to your search") await ctx.send("Could not find anything relating to your search")

View File

@ -1,24 +1,24 @@
import imdb # Used in movieFunc
import random # Used in movieFunc import random # Used in movieFunc
import discord # Used in movieFunc
import datetime # Used in helloFunc import datetime # Used in helloFunc
import urllib # Used in imageFunc import urllib # Used in imageFunc
import ast
import imdb # Used in movieFunc
import discord # Used in movieFunc
import lxml # Used in imageFunc import lxml # Used in imageFunc
import fandom # Used in findWikiPage import fandom # Used in findWikiPage
import d20 # Used in rollDice import d20 # Used in rollDice
import ast
from .plex import Plex from .plex import Plex
from .nerd_shit import NerdShit from .nerd_shit import NerdShit
from .generators import Generators from .generators import Generators
from gwendolyn.utils import cap
fandom.set_lang("da") fandom.set_lang("da")
fandom.set_wiki("senkulpa") fandom.set_wiki("senkulpa")
class MyStringifier(d20.MarkdownStringifier): class MyStringifier(d20.MarkdownStringifier):
def _str_expression(self, node): def _str_expression(self, node):
if node.comment == None: if node.comment is None:
result_text = "Result" result_text = "Result"
else: else:
result_text = node.comment.capitalize() result_text = node.comment.capitalize()
@ -33,23 +33,23 @@ class Other():
self.generators = Generators(self.bot) self.generators = Generators(self.bot)
# Picks a random movie and returns information about it # Picks a random movie and returns information about it
async def movieFunc(self, ctx): async def movie_func(self, ctx):
await self.bot.defer(ctx) await self.bot.defer(ctx)
self.bot.log("Creating IMDb object") self.bot.log("Creating IMDb object")
imdbClient = imdb.IMDb() imdb_client = imdb.IMDb()
self.bot.log("Picking a movie") self.bot.log("Picking a movie")
with open("gwendolyn/resources/movies.txt", "r") as f: with open("gwendolyn/resources/movies.txt", "r") as file_pointer:
movie_list = f.read().split("\n") movie_list = file_pointer.read().split("\n")
movie_name = random.choice(movie_list) movie_name = random.choice(movie_list)
self.bot.log(f"Searching for {movie_name}") self.bot.log(f"Searching for {movie_name}")
searchResult = imdbClient.search_movie(movie_name) search_result = imdb_client.search_movie(movie_name)
self.bot.log("Getting the data") self.bot.log("Getting the data")
movie = searchResult[0] movie = search_result[0]
imdbClient.update(movie) imdb_client.update(movie)
self.bot.log("Successfully ran /movie") self.bot.log("Successfully ran /movie")
@ -63,13 +63,13 @@ class Other():
await ctx.send(embed = embed) await ctx.send(embed = embed)
# Responds with a greeting of a time-appropriate maner # Responds with a greeting of a time-appropriate maner
async def helloFunc(self, ctx): async def hello_func(self, ctx):
def time_in_range(start, end, x): def time_in_range(start, end, i):
# Return true if x is in the range [start, end] # Return true if i is in the range [start, end]
if start <= end: if start <= end:
return start <= x <= end return start <= i <= end
else: else:
return start <= x or x <= end return start <= i or i <= end
author = ctx.author.display_name author = ctx.author.display_name
now = datetime.datetime.now() now = datetime.datetime.now()
@ -87,31 +87,22 @@ class Other():
await ctx.send(send_message) await ctx.send(send_message)
# Finds a random picture online # Finds a random picture online
async def imageFunc(self, ctx): async def image_func(self, ctx):
# Picks a type of camera, which decides the naming scheme # Picks a type of camera, which decides the naming scheme
cams = ("one","two","three","four") cams = ("one","two","three","four")
cam = random.choice(cams) cam = random.choice(cams)
self.bot.log("Chose cam type "+cam) self.bot.log("Chose cam type "+cam)
if cam == "one": if cam == "one":
a = str(random.randint(0 ,9)) search = f"img_{''.join([random.randint(0,9) for _ in range(4)])}"
b = str(random.randint(0,9))
c = str(random.randint(0,9))
d = str(random.randint(0,9))
search = ("img_"+a+b+c+d)
elif cam == "two": elif cam == "two":
a = str(random.randint(2012,2016)) year = str(random.randint(2012,2016))
b = str(random.randint(1,12)).zfill(2) month = str(random.randint(1,12)).zfill(2)
c = str(random.randint(1,29)).zfill(2) day = str(random.randint(1,29)).zfill(2)
search = ("IMG_"+a+b+c) search = f"IMG_{year}{month}{day}"
elif cam == "three": elif cam == "three":
a = str(random.randint(1,500)).zfill(4) search = f"IMAG_{str(random.randint(1,500)).zfill(4)}"
search = ("IMAG_"+a)
elif cam == "four": elif cam == "four":
a = str(random.randint(0,9)) search = f"DSC_{''.join([random.randint(0,9) for _ in range(4)])}"
b = str(random.randint(0,9))
c = str(random.randint(0,9))
d = str(random.randint(0,9))
search = ("DSC_"+a+b+c+d)
self.bot.log("Searching for "+search) self.bot.log("Searching for "+search)
@ -127,37 +118,37 @@ class Other():
# Picks an image # Picks an image
number = random.randint(1,len(images))-1 number = random.randint(1,len(images))-1
image = ast.literal_eval(str(images[number])) image = ast.literal_eval(str(images[number]))
imageUrl = image["murl"] image_url = image["murl"]
self.bot.log("Picked image number "+str(number)) self.bot.log("Picked image number "+str(number))
# Returns the image # Returns the image
self.bot.log("Successfully returned an image") self.bot.log("Successfully returned an image")
await ctx.send(imageUrl) await ctx.send(image_url)
# Finds a page from the Senkulpa Wikia # Finds a page from the Senkulpa Wikia
async def findWikiPage(self, ctx, search : str): async def find_wiki_page(self, ctx, search : str):
await self.bot.defer(ctx) await self.bot.defer(ctx)
foundPage = False found_page = False
if search != "": if search != "":
self.bot.log("Trying to find wiki page for "+search) self.bot.log("Trying to find wiki page for "+search)
searchResults = fandom.search(search) search_results = fandom.search(search)
if len(searchResults) > 0: if len(search_results) > 0:
foundPage = True found_page = True
searchResult = searchResults[0] search_result = search_results[0]
else: else:
self.bot.log("Couldn't find the page") self.bot.log("Couldn't find the page")
await ctx.send("Couldn't find page") await ctx.send("Couldn't find page")
else: else:
foundPage = True found_page = True
self.bot.log("Searching for a random page") self.bot.log("Searching for a random page")
searchResult = fandom.random() search_result = fandom.random()
if foundPage: if found_page:
self.bot.log(f"Found page \"{searchResult[0]}\"") self.bot.log(f"Found page \"{search_result[0]}\"")
page = fandom.page(pageid = searchResult[1]) page = fandom.page(pageid = search_result[1])
content = page.summary content = page.summary
images = page.images images = page.images
@ -173,24 +164,24 @@ class Other():
await ctx.send(embed = embed) await ctx.send(embed = embed)
async def rollDice(self, ctx, rollString): async def roll_dice(self, ctx, roll_string):
user = ctx.author.display_name user = ctx.author.display_name
while len(rollString) > 1 and rollString[0] == " ": while len(roll_string) > 1 and roll_string[0] == " ":
rollString = rollString[1:] roll_string = roll_string[1:]
roll = d20.roll(rollString, allow_comments=True, stringifier=MyStringifier()) roll = d20.roll(roll_string, allow_comments=True, stringifier=MyStringifier())
await ctx.send(f"{user} :game_die:\n{roll}") await ctx.send(f"{user} :game_die:\n{roll}")
async def helpFunc(self, ctx, command): async def help_func(self, ctx, command):
if command == "": if command == "":
with open("gwendolyn/resources/help/help.txt",encoding="utf-8") as f: with open("gwendolyn/resources/help/help.txt",encoding="utf-8") as file_pointer:
text = f.read() text = file_pointer.read()
em = discord.Embed(title = "Help", description = text,colour = 0x59f442) embed = discord.Embed(title = "Help", description = text,colour = 0x59f442)
await ctx.send(embed = em) await ctx.send(embed = embed)
else: else:
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id)) self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as f: with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as file_pointer:
text = f.read() text = file_pointer.read()
em = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442) embed = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442)
await ctx.send(embed = em) await ctx.send(embed = embed)

View File

@ -6,18 +6,18 @@ class StarWarsChar():
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def getChar_name(self, user : str): def get_char_name(self, user : str):
self.bot.log("Getting name for "+self.bot.database_funcs.get_name(user)+"'s character") self.bot.log("Getting name for "+self.bot.database_funcs.get_name(user)+"'s character")
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) user_character = self.bot.database["starwars characters"].find_one({"_id":user})
if userCharacter != None: if user_character != None:
self.bot.log("Name is "+userCharacter["Name"]) self.bot.log("Name is "+user_character["Name"])
return userCharacter["Name"] return user_character["Name"]
else: else:
self.bot.log("Just using "+self.bot.database_funcs.get_name(user)) self.bot.log("Just using "+self.bot.database_funcs.get_name(user))
return self.bot.database_funcs.get_name(user) return self.bot.database_funcs.get_name(user)
def setUpDict(self, cmd : dict): def set_up_dict(self, cmd : dict):
self.bot.log("Setting up a dictionary in a nice way") self.bot.log("Setting up a dictionary in a nice way")
if bool(cmd): if bool(cmd):
keys = list(cmd) keys = list(cmd)
@ -26,24 +26,24 @@ class StarWarsChar():
if isinstance(values[0],dict): if isinstance(values[0],dict):
return ", ".join(values) return ", ".join(values)
else: else:
for x, key in enumerate(keys): for i, key in enumerate(keys):
if type(key) is list: if type(key) is list:
if x%3 != 2: if i%3 != 2:
result += "**" + key + "**" + ": " + ", ".join(values[x]) + " " result += "**" + key + "**" + ": " + ", ".join(values[i]) + " "
else: else:
result += "**" + key + "**" + ": " + ", ".join(values[x]) + "\n" result += "**" + key + "**" + ": " + ", ".join(values[i]) + "\n"
else: else:
if x%3 != 2: if i%3 != 2:
result += "**" + key + "**" + ": " + str(values[x]) + " " result += "**" + key + "**" + ": " + str(values[i]) + " "
else: else:
result += "**" + key + "**" + ": " + str(values[x]) + "\n" result += "**" + key + "**" + ": " + str(values[i]) + "\n"
self.bot.log("Returning a dictionary, but well formatted") self.bot.log("Returning a dictionary, but well formatted")
return result return result
else: else:
self.bot.log("Couldn't find anything") self.bot.log("Couldn't find anything")
return "There doesn't seem to be anything here..." return "There doesn't seem to be anything here..."
def lookUp(self, data : dict, key : str, cmd : str = ""): def look_up(self, data : dict, key : str, cmd : str = ""):
if cmd == " ": if cmd == " ":
cmd = "" cmd = ""
elif cmd != "": elif cmd != "":
@ -57,7 +57,7 @@ class StarWarsChar():
self.bot.log(key+" exists") self.bot.log(key+" exists")
if cmd == "": if cmd == "":
if type(data[key]) is dict and key != "Weapons": if type(data[key]) is dict and key != "Weapons":
return self.setUpDict(data[key]) return self.set_up_dict(data[key])
elif key == "Weapons": elif key == "Weapons":
self.bot.log("Does this even get used? I'm too scared to delete it") self.bot.log("Does this even get used? I'm too scared to delete it")
if bool(data[key]): if bool(data[key]):
@ -85,21 +85,21 @@ class StarWarsChar():
if type(data[key]) is int: if type(data[key]) is int:
try: try:
newValue = data[key] + int(cmd) new_value = data[key] + int(cmd)
data[key] = newValue data[key] = new_value
self.bot.log("Added "+cmd+" to "+key) self.bot.log("Added "+cmd+" to "+key)
return data return data
except: except:
self.bot.log("Couldn't add "+cmd+" to "+key) self.bot.log("Couldn't add "+cmd+" to "+key)
return "Can't add that" return "Can't add that"
elif type(data[key]) is list: elif type(data[key]) is list:
try: try:
data[key].append(cmd) data[key].append(cmd)
self.bot.log("Added "+cmd+" to "+key) self.bot.log("Added "+cmd+" to "+key)
return data return data
except: except:
self.bot.log("Couldn't add "+cmd+" to "+key) self.bot.log("Couldn't add "+cmd+" to "+key)
return "Can't add that" return "Can't add that"
else: else:
self.bot.log("Yeah, I can't add that to "+key) self.bot.log("Yeah, I can't add that to "+key)
return "Can't add that" return "Can't add that"
@ -116,21 +116,21 @@ class StarWarsChar():
if type(data[key]) is int: if type(data[key]) is int:
try: try:
newValue = data[key] - int(cmd) new_value = data[key] - int(cmd)
data[key] = newValue data[key] = new_value
self.bot.log("Subtracted "+cmd+" from "+key) self.bot.log("Subtracted "+cmd+" from "+key)
return data return data
except: except:
self.bot.log("Couldn't subtract "+cmd+" from "+key) self.bot.log("Couldn't subtract "+cmd+" from "+key)
return "Can't remove that" return "Can't remove that"
elif type(data[key]) is list: elif type(data[key]) is list:
try: try:
data[key].remove(cmd) data[key].remove(cmd)
self.bot.log("Removed "+cmd+" from "+key) self.bot.log("Removed "+cmd+" from "+key)
return data return data
except: except:
self.bot.log("Couldn't remove "+cmd+" from "+key) self.bot.log("Couldn't remove "+cmd+" from "+key)
return "Can't remove that" return "Can't remove that"
else: else:
self.bot.log("Yeah, I can't remove/subtract that from "+key) self.bot.log("Yeah, I can't remove/subtract that from "+key)
return "Can't remove that" return "Can't remove that"
@ -139,20 +139,20 @@ class StarWarsChar():
cmd = cmd[1:] cmd = cmd[1:]
if type(data[key]) is dict: if type(data[key]) is dict:
newKey = cmd.split(" ")[0] new_key = cmd.split(" ")[0]
cmd = cmd[len(newKey):] cmd = cmd[len(new_key):]
if cmd != "": if cmd != "":
while cmd[0] == " ": while cmd[0] == " ":
cmd = cmd[1:] cmd = cmd[1:]
if cmd == "": if cmd == "":
break break
self.bot.log("Looking up "+newKey+" in "+key) self.bot.log("Looking up "+new_key+" in "+key)
lookUpResult = self.lookUp(data[key],newKey,cmd) look_up_result = self.look_up(data[key],new_key,cmd)
if type(lookUpResult) is dict: if type(look_up_result) is dict:
data[key] = lookUpResult data[key] = look_up_result
return data return data
else: else:
return lookUpResult return look_up_result
elif type(data[key]) != list: elif type(data[key]) != list:
self.bot.log("Trying to change "+key+" to "+cmd) self.bot.log("Trying to change "+key+" to "+cmd)
try: try:
@ -193,23 +193,23 @@ class StarWarsChar():
if cmd == "": if cmd == "":
self.bot.log("Returning "+search) self.bot.log("Returning "+search)
return self.setUpDict(data[search]) return self.set_up_dict(data[search])
else: else:
newKey = cmd.split(" ")[0] new_key = cmd.split(" ")[0]
cmd = cmd[len(newKey):] cmd = cmd[len(new_key):]
if cmd != "": if cmd != "":
while cmd[0] == " ": while cmd[0] == " ":
cmd = cmd[1:] cmd = cmd[1:]
if cmd == "": if cmd == "":
break break
lookUpResult = self.lookUp(data[search],newKey,cmd) look_up_result = self.look_up(data[search],new_key,cmd)
if type(lookUpResult) is dict: if type(look_up_result) is dict:
data[search] = lookUpResult data[search] = look_up_result
return data return data
else: else:
return lookUpResult return look_up_result
def characterSheet(self,character : dict): def character_sheet(self,character : dict):
self.bot.log("Setting up a character sheet for "+character["Name"]) self.bot.log("Setting up a character sheet for "+character["Name"])
divider = "--------------------\n" divider = "--------------------\n"
name = character["Name"] name = character["Name"]
@ -219,8 +219,8 @@ class StarWarsChar():
text1 = "**Species**: "+character["Species"]+"\n**Career**: "+character["Career"]+"\n**Specialization Trees**: "+", ".join(character["Specialization-trees"])+textf+"\n**Soak**: "+str(character["Soak"]) text1 = "**Species**: "+character["Species"]+"\n**Career**: "+character["Career"]+"\n**Specialization Trees**: "+", ".join(character["Specialization-trees"])+textf+"\n**Soak**: "+str(character["Soak"])
text2 = "\n\n**Wounds**: "+str(character["Wounds"])+"/"+str(character["Wound-threshold"])+"\n**Strain**: "+str(character["Strain"])+"/"+str(character["Strain-threshold"]) text2 = "\n\n**Wounds**: "+str(character["Wounds"])+"/"+str(character["Wound-threshold"])+"\n**Strain**: "+str(character["Strain"])+"/"+str(character["Strain-threshold"])
text3 = self.setUpDict(character["Characteristics"]) text3 = self.set_up_dict(character["Characteristics"])
text4 = self.setUpDict(character["Skills"]) text4 = self.set_up_dict(character["Skills"])
text5 = "" text5 = ""
text6 = "" text6 = ""
text7 = "" text7 = ""
@ -240,7 +240,7 @@ class StarWarsChar():
return name, text1+text2+"\n\n"+text3+divider+text4+"\n"+divider+text5+text6+text7+text8 return name, text1+text2+"\n\n"+text3+divider+text4+"\n"+divider+text5+text6+text7+text8
def char_data(self,user : str,cmd : str): def char_data(self,user : str,cmd : str):
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) user_character = self.bot.database["starwars characters"].find_one({"_id":user})
key = string.capwords(cmd.split(" ")[0]) key = string.capwords(cmd.split(" ")[0])
cmd = cmd[len(key):] cmd = cmd[len(key):]
@ -253,23 +253,23 @@ class StarWarsChar():
break break
self.bot.log("Looking for "+self.bot.database_funcs.get_name(user)+"'s character") self.bot.log("Looking for "+self.bot.database_funcs.get_name(user)+"'s character")
if userCharacter != None: if user_character != None:
self.bot.log("Found it! Looking for "+key+" in the data") self.bot.log("Found it! Looking for "+key+" in the data")
if key in userCharacter: if key in user_character:
self.bot.log("Found it!") self.bot.log("Found it!")
if type(userCharacter[key]) is dict: if type(user_character[key]) is dict:
self.bot.log("It's a dictionary!") self.bot.log("It's a dictionary!")
if cmd == "": if cmd == "":
self.bot.log("Retrieving data") self.bot.log("Retrieving data")
if key == "Weapons": if key == "Weapons":
if bool(userCharacter[key]): if bool(user_character[key]):
self.bot.log("Returning a list of weapons") self.bot.log("Returning a list of weapons")
return ", ".join(list(userCharacter[key])) return ", ".join(list(user_character[key]))
else: else:
self.bot.log("The character doesn't have any weapons. Which is probably for the best. Like, who just walks around with weapons?") self.bot.log("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..." return "There doesn't seem to be anything there..."
else: else:
return self.setUpDict(userCharacter[key]) return self.set_up_dict(user_character[key])
elif cmd[0] == "+": elif cmd[0] == "+":
self.bot.log("Gonna add something!!!") self.bot.log("Gonna add something!!!")
try: try:
@ -287,7 +287,7 @@ class StarWarsChar():
self.bot.log("Adding "+cmd[0]+" to "+key) self.bot.log("Adding "+cmd[0]+" to "+key)
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$set": {key+"."+cmd[0] : cmd[1]}}) {"$set": {key+"."+cmd[0] : cmd[1]}})
return cmd[0]+" added to "+key+" for " + userCharacter["Name"] return cmd[0]+" added to "+key+" for " + user_character["Name"]
elif key == "Obligations" and "," in cmd: elif key == "Obligations" and "," in cmd:
cmd = cmd.split(",") cmd = cmd.split(",")
@ -300,17 +300,17 @@ class StarWarsChar():
except: except:
self.bot.log("Fucked that up") self.bot.log("Fucked that up")
return "Wrong data type" return "Wrong data type"
return cmd[0]+" added to "+key+" for " + userCharacter["Name"] return cmd[0]+" added to "+key+" for " + user_character["Name"]
elif key == "Weapons": elif key == "Weapons":
with open("gwendolyn/resources/star_wars/starwarstemplates.json", "r") as f: with open("gwendolyn/resources/star_wars/starwarstemplates.json", "r") as file_pointer:
templates = json.load(f) templates = json.load(file_pointer)
newWeapon = templates["Weapon"] new_weapon = templates["Weapon"]
self.bot.log("Adding "+cmd+" to "+key) self.bot.log("Adding "+cmd+" to "+key)
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$set": {key+"."+cmd : newWeapon}}) {"$set": {key+"."+cmd : new_weapon}})
return cmd+" added to weapons for " + userCharacter["Name"] return cmd+" added to weapons for " + user_character["Name"]
else: else:
self.bot.log("That's not happening") self.bot.log("That's not happening")
@ -328,11 +328,11 @@ class StarWarsChar():
if key == "Talents" or key == "Force-powers" or key == "Weapons" or key == "Obligations": if key == "Talents" or key == "Force-powers" or key == "Weapons" or key == "Obligations":
self.bot.log("Trying to remove "+cmd+" from "+key) self.bot.log("Trying to remove "+cmd+" from "+key)
if cmd in userCharacter[key]: if cmd in user_character[key]:
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$unset": {cmd}}) {"$unset": {cmd}})
self.bot.log("I did that") self.bot.log("I did that")
return cmd+" removed from "+key+" from "+userCharacter["Name"] return cmd+" removed from "+key+" from "+user_character["Name"]
else: else:
self.bot.log("Welp. I fucked that up") self.bot.log("Welp. I fucked that up")
return "Can't remove that" return "Can't remove that"
@ -343,27 +343,27 @@ class StarWarsChar():
else: else:
self.bot.log("Looking up "+cmd+" in "+key) self.bot.log("Looking up "+cmd+" in "+key)
if key == "Talents" or key == "Force-powers": if key == "Talents" or key == "Force-powers":
newKey = cmd new_key = cmd
newcmd = "" new_cmd = ""
else: else:
newKey = string.capwords(cmd.split(" ")[0]) new_key = string.capwords(cmd.split(" ")[0])
newcmd = cmd[len(newKey):] new_cmd = cmd[len(new_key):]
lookUpResult = self.lookUp(userCharacter[key],newKey,newcmd) look_up_result = self.look_up(user_character[key],new_key,new_cmd)
if type(lookUpResult) is dict: if type(look_up_result) is dict:
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$set": {key : lookUpResult}}) {"$set": {key : look_up_result}})
return "Changed " + userCharacter["Name"] + "'s " + key return "Changed " + user_character["Name"] + "'s " + key
else: else:
return lookUpResult return look_up_result
else: else:
if cmd == "": if cmd == "":
self.bot.log("Retrieving data") self.bot.log("Retrieving data")
if type(userCharacter[key]) is list: if type(user_character[key]) is list:
return key+":\n"+", ".join(userCharacter[key]) return key+":\n"+", ".join(user_character[key])
else: else:
return userCharacter[key] return user_character[key]
elif cmd[0] == '+': elif cmd[0] == '+':
self.bot.log("Adding") self.bot.log("Adding")
try: try:
@ -374,21 +374,21 @@ class StarWarsChar():
self.bot.log("Error message") self.bot.log("Error message")
return "Can't do that" return "Can't do that"
if type(userCharacter[key]) is int: if type(user_character[key]) is int:
try: try:
self.bot.log("Adding "+cmd+" to "+key) self.bot.log("Adding "+cmd+" to "+key)
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$inc": {key : int(cmd)}}) {"$inc": {key : int(cmd)}})
return "Added " + cmd + " to " + userCharacter["Name"] + "'s " + key return "Added " + cmd + " to " + user_character["Name"] + "'s " + key
except: except:
self.bot.log("BITCH SANDWICH") self.bot.log("BITCH SANDWICH")
return "Can't add that" return "Can't add that"
elif type(userCharacter[key]) is list: elif type(user_character[key]) is list:
try: try:
self.bot.log("Adding "+cmd+" to "+key) self.bot.log("Adding "+cmd+" to "+key)
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$push": {key : cmd}}) {"$push": {key : cmd}})
return "Added " + cmd + " to " + userCharacter["Name"] + "'s " + key return "Added " + cmd + " to " + user_character["Name"] + "'s " + key
except: except:
self.bot.log("tstststststs") self.bot.log("tstststststs")
return "Can't add that" return "Can't add that"
@ -405,16 +405,16 @@ class StarWarsChar():
self.bot.log("lalalala ") self.bot.log("lalalala ")
return "Can't do that" return "Can't do that"
if type(userCharacter[key]) is int: if type(user_character[key]) is int:
try: try:
self.bot.log("Subtracting "+cmd+" from "+key) self.bot.log("Subtracting "+cmd+" from "+key)
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$inc": {key : -int(cmd)}}) {"$inc": {key : -int(cmd)}})
return "Subtracted " + cmd + " from " + userCharacter["Name"] + "'s " + key return "Subtracted " + cmd + " from " + user_character["Name"] + "'s " + key
except: except:
self.bot.log("Tried it. Didn't want to") self.bot.log("Tried it. Didn't want to")
return "Can't remove that" return "Can't remove that"
elif type(userCharacter[key]) is list: elif type(user_character[key]) is list:
try: try:
self.bot.log("removing "+cmd+" from "+key) self.bot.log("removing "+cmd+" from "+key)
try: try:
@ -423,7 +423,7 @@ class StarWarsChar():
except: except:
self.bot.log("They can only remove stuff that's actually in the list") self.bot.log("They can only remove stuff that's actually in the list")
return "Not in list" return "Not in list"
return "Removed " + cmd + " from " + userCharacter["Name"] + "'s " + key return "Removed " + cmd + " from " + user_character["Name"] + "'s " + key
except: except:
self.bot.log("nah") self.bot.log("nah")
return "Can't remove that" return "Can't remove that"
@ -432,20 +432,20 @@ class StarWarsChar():
return "Can't remove that" return "Can't remove that"
else: else:
self.bot.log("Changing "+key+" to "+cmd) self.bot.log("Changing "+key+" to "+cmd)
if type(userCharacter[key]) is int: if type(user_character[key]) is int:
try: try:
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$set": {key : int(cmd)}}) {"$set": {key : int(cmd)}})
except: except:
self.bot.log("I don't wanna tho") self.bot.log("I don't wanna tho")
return "Can't do that" return "Can't do that"
elif type(userCharacter[key]) is str: elif type(user_character[key]) is str:
self.bot.database["starwars characters"].update_one({"_id":user}, self.bot.database["starwars characters"].update_one({"_id":user},
{"$set": {key : cmd}}) {"$set": {key : cmd}})
else: else:
self.bot.log("I don't wanna tho") self.bot.log("I don't wanna tho")
return "Can't do that" return "Can't do that"
return "Changed " + userCharacter["Name"] + "'s " + key +" to " + cmd return "Changed " + user_character["Name"] + "'s " + key +" to " + cmd
else: else:
self.bot.log(key+" isn't in there") self.bot.log(key+" isn't in there")
return "Couldn't find that data. Are you sure you spelled it correctly?" return "Couldn't find that data. Are you sure you spelled it correctly?"
@ -453,32 +453,32 @@ class StarWarsChar():
self.bot.log(user+" doesn't have a character") self.bot.log(user+" doesn't have a character")
return "You don't have a character. You can make one with /starwarscharacter" return "You don't have a character. You can make one with /starwarscharacter"
def replaceSpaces(self,cmd : str): def replace_spaces(self,cmd : str):
withSpaces = ["Specialization Trees","Wound Threshold","Strain Threshold","Defense - Ranged","Defense - Melee","Force Rating","Core Worlds","Outer Rim","Piloting - Planetary","Piloting - Space","Ranged - Heavy","Ranged - Light","Lightsaber Characteristic","Critical Injuries","Force Powers"] with_spaces = ["Specialization Trees","Wound Threshold","Strain Threshold","Defense - Ranged","Defense - Melee","Force Rating","Core Worlds","Outer Rim","Piloting - Planetary","Piloting - Space","Ranged - Heavy","Ranged - Light","Lightsaber Characteristic","Critical Injuries","Force Powers"]
withoutSpaces = ["Specialization-trees","Wound-threshold","Strain-threshold","Defense-ranged","Defense-melee","Force-rating","Core-worlds","Outer-rim","Piloting-planetary","Piloting-space","Ranged-heavy","Ranged-light","Lightsaber-characteristic","Critical-injuries","Force-powers"] without_spaces = ["Specialization-trees","Wound-threshold","Strain-threshold","Defense-ranged","Defense-melee","Force-rating","Core-worlds","Outer-rim","Piloting-planetary","Piloting-space","Ranged-heavy","Ranged-light","Lightsaber-characteristic","Critical-injuries","Force-powers"]
for x, value in enumerate(withoutSpaces): for i, value in enumerate(without_spaces):
cmd = cmd.replace(withSpaces[x],value) cmd = cmd.replace(with_spaces[i],value)
return cmd return cmd
def replaceWithSpaces(self,cmd : str): def replace_with_spaces(self,cmd : str):
withSpaces = ["Specialization Trees","Wound Threshold","Strain Threshold","Defense - Ranged","Defense - Melee","Force Rating","Core Worlds","Outer Rim","Piloting - Planetary","Piloting - Space","Ranged - Heavy","Ranged - light","Lightsaber Characteristic","Critical Injuries","Force Powers"] with_spaces = ["Specialization Trees","Wound Threshold","Strain Threshold","Defense - Ranged","Defense - Melee","Force Rating","Core Worlds","Outer Rim","Piloting - Planetary","Piloting - Space","Ranged - Heavy","Ranged - light","Lightsaber Characteristic","Critical Injuries","Force Powers"]
withoutSpaces = ["Specialization-trees","Wound-threshold","Strain-threshold","Defense-ranged","Defense-melee","Force-rating","Core-worlds","Outer-rim","Piloting-planetary","Piloting-space","Ranged-heavy","Ranged-light","Lightsaber-characteristic","Critical-injuries","Force-powers"] without_spaces = ["Specialization-trees","Wound-threshold","Strain-threshold","Defense-ranged","Defense-melee","Force-rating","Core-worlds","Outer-rim","Piloting-planetary","Piloting-space","Ranged-heavy","Ranged-light","Lightsaber-characteristic","Critical-injuries","Force-powers"]
for x, value in enumerate(withoutSpaces): for i, value in enumerate(without_spaces):
cmd = cmd.replace(value,withSpaces[x]) cmd = cmd.replace(value,with_spaces[i])
return cmd return cmd
async def parseChar(self, ctx, parameters : str): async def parse_char(self, ctx, parameters : str):
user = f"#{ctx.author.id}" user = f"#{ctx.author.id}"
cmd = string.capwords(parameters.replace("+","+ ").replace("-","- ").replace(",",", ")) cmd = string.capwords(parameters.replace("+","+ ").replace("-","- ").replace(",",", "))
returnEmbed = False return_embed = False
cmd = self.replaceSpaces(cmd) cmd = self.replace_spaces(cmd)
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) user_character = self.bot.database["starwars characters"].find_one({"_id":user})
if cmd == " ": if cmd == " ":
cmd = "" cmd = ""
@ -490,17 +490,17 @@ class StarWarsChar():
if cmd == "": if cmd == "":
if userCharacter != None: if user_character != None:
title, text = self.characterSheet(userCharacter) title, text = self.character_sheet(user_character)
text = self.replaceWithSpaces(text) text = self.replace_with_spaces(text)
returnEmbed = True return_embed = True
else: else:
self.bot.log("Makin' a character for "+self.bot.database_funcs.get_name(user)) self.bot.log("Makin' a character for "+self.bot.database_funcs.get_name(user))
with open("gwendolyn/resources/star_wars/starwarstemplates.json", "r") as f: with open("gwendolyn/resources/star_wars/starwarstemplates.json", "r") as file_pointer:
templates = json.load(f) templates = json.load(file_pointer)
newChar = templates["Character"] new_char = templates["Character"]
newChar["_id"] = user new_char["_id"] = user
self.bot.database["starwars characters"].insert_one(newChar) self.bot.database["starwars characters"].insert_one(new_char)
await ctx.send("Character for " + self.bot.database_funcs.get_name(user) + " created") await ctx.send("Character for " + self.bot.database_funcs.get_name(user) + " created")
else: else:
if cmd == "Purge": if cmd == "Purge":
@ -508,22 +508,21 @@ class StarWarsChar():
self.bot.database["starwars characters"].delete_one({"_id":user}) self.bot.database["starwars characters"].delete_one({"_id":user})
await ctx.send("Character for " + self.bot.database_funcs.get_name(user) + " deleted") await ctx.send("Character for " + self.bot.database_funcs.get_name(user) + " deleted")
else: else:
await ctx.send(self.replaceWithSpaces(str(self.char_data(user,cmd)))) await ctx.send(self.replace_with_spaces(str(self.char_data(user,cmd))))
if returnEmbed: if return_embed:
em = discord.Embed(title = title, description = text, colour=0xDEADBF) embed = discord.Embed(title = title, description = text, colour=0xDEADBF)
await ctx.send(embed = em) await ctx.send(embed = embed)
def lightsaberChar(self,user : str): def lightsaber_char(self,user : str):
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) user_character = self.bot.database["starwars characters"].find_one({"_id":user})
if userCharacter != None: if user_character != None:
return userCharacter["Lightsaber-characteristic"] return user_character["Lightsaber-characteristic"]
def userHasChar(self,user : str): def user_has_char(self,user : str):
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) user_character = self.bot.database["starwars characters"].find_one({"_id":user})
return userCharacter != None
return user_character != None

View File

@ -2,27 +2,27 @@ class StarWarsDestiny():
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def destinyNew(self, num : int): def destiny_new(self, num : int):
self.bot.log("Creating a new destiny pool with "+str(num)+" players") self.bot.log("Creating a new destiny pool with "+str(num)+" players")
roll, diceResults = self.bot.star_wars.roll.roll(0,0,0,0,0,0,num) roll, dice_results = self.bot.star_wars.roll.roll(0,0,0,0,0,0,num)
roll = "".join(sorted(roll)) roll = "".join(sorted(roll))
with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as f: with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as file_pointer:
f.write(roll) file_pointer.write(roll)
return "Rolled for Destiny Points and got:\n"+self.bot.star_wars.roll.diceResultToEmoji(diceResults)+"\n"+self.bot.star_wars.roll.resultToEmoji(roll) return "Rolled for Destiny Points and got:\n"+self.bot.star_wars.roll.diceResultToEmoji(dice_results)+"\n"+self.bot.star_wars.roll.resultToEmoji(roll)
def destinyUse(self, user : str): def destiny_use(self, user : str):
with open("gwendolyn/resources/star_wars/destinyPoints.txt","rt") as f: with open("gwendolyn/resources/star_wars/destinyPoints.txt","rt") as file_pointer:
points = f.read() points = file_pointer.read()
if user == "Nikolaj": if user == "Nikolaj":
self.bot.log("Trying to use a dark side destiny point") self.bot.log("Trying to use a dark side destiny point")
if 'B' in points: if 'B' in points:
points = points.replace("B","L",1) points = points.replace("B","L",1)
points = "".join(sorted(points)) points = "".join(sorted(points))
with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as f: with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as file_pointer:
f.write(points) file_pointer.write(points)
self.bot.log("Did it") self.bot.log("Did it")
return "Used a dark side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points) return "Used a dark side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points)
else: else:
@ -33,15 +33,15 @@ class StarWarsDestiny():
if 'L' in points: if 'L' in points:
points = points.replace("L","B",1) points = points.replace("L","B",1)
points = "".join(sorted(points)) points = "".join(sorted(points))
with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as f: with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as file_pointer:
f.write(points) file_pointer.write(points)
self.bot.log("Did it") self.bot.log("Did it")
return "Used a light side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points) return "Used a light side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points)
else: else:
self.bot.log("There were no dark side destiny points") self.bot.log("There were no dark side destiny points")
return "No light side destiny points" return "No light side destiny points"
async def parseDestiny(self, ctx, cmd : str): async def parse_destiny(self, ctx, cmd : str):
user = f"#{ctx.author.id}" user = f"#{ctx.author.id}"
if cmd != "": if cmd != "":
while cmd[0] == ' ': while cmd[0] == ' ':
@ -51,22 +51,22 @@ class StarWarsDestiny():
if cmd == "": if cmd == "":
self.bot.log("Retrieving destiny pool info") self.bot.log("Retrieving destiny pool info")
with open("gwendolyn/resources/star_wars/destinyPoints.txt","rt") as f: with open("gwendolyn/resources/star_wars/destinyPoints.txt","rt") as file_pointer:
send_message = self.bot.star_wars.roll.resultToEmoji(f.read()) send_message = self.bot.star_wars.roll.resultToEmoji(file_pointer.read())
else: else:
commands = cmd.upper().split(" ") commands = cmd.upper().split(" ")
if commands[0] == "N": if commands[0] == "N":
if len(commands) > 1: if len(commands) > 1:
send_message = self.destinyNew(int(commands[1])) send_message = self.destiny_new(int(commands[1]))
else: else:
send_message = "You need to give an amount of players" send_message = "You need to give an amount of players"
elif commands[0] == "U": elif commands[0] == "U":
send_message = self.destinyUse(user) send_message = self.destiny_use(user)
else: else:
send_message = "I didn't quite understand that" send_message = "I didn't quite understand that"
message_list = send_message.split("\n") message_list = send_message.split("\n")
await ctx.send(message_list[0]) await ctx.send(message_list[0])
if len(message_list) > 1: if len(message_list) > 1:
for messageItem in message_list[1:]: for message_item in message_list[1:]:
await ctx.channel.send(messageItem) await ctx.channel.send(message_item)

View File

@ -13,43 +13,43 @@ class StarWarsRoll():
# Rolls the specified dice # Rolls the specified dice
def roll(self, abi : int = 1, prof : int = 0, dif : int = 3, cha : int = 0, boo : int = 0, setb : int = 0, force : int = 0): def roll(self, abi : int = 1, prof : int = 0, dif : int = 3, cha : int = 0, boo : int = 0, setb : int = 0, force : int = 0):
result = "" result = ""
diceResult = [] dice_result = []
for _ in range(abi): for _ in range(abi):
choice = random.choice(["","S","S","SS","A","A","SA","AA"]) choice = random.choice(["","S","S","SS","A","A","SA","AA"])
result += choice result += choice
diceResult.append("abi"+choice) dice_result.append("abi"+choice)
for _ in range(prof): for _ in range(prof):
choice = random.choice(["","S","S","SS","SS","A","SA","SA","SA","AA","AA","R"]) choice = random.choice(["","S","S","SS","SS","A","SA","SA","SA","AA","AA","R"])
result += choice result += choice
diceResult.append("prof"+choice) dice_result.append("prof"+choice)
for _ in range(dif): for _ in range(dif):
choice = random.choice(["","F","FF","H","H","H","HH","FH"]) choice = random.choice(["","F","FF","H","H","H","HH","FH"])
result += choice result += choice
diceResult.append("dif"+choice) dice_result.append("dif"+choice)
for _ in range(cha): for _ in range(cha):
choice = random.choice(["","F","F","FF","FF","H","H","FH","FH","HH","HH","D"]) choice = random.choice(["","F","F","FF","FF","H","H","FH","FH","HH","HH","D"])
result += choice result += choice
diceResult.append("cha"+choice) dice_result.append("cha"+choice)
for _ in range(boo): for _ in range(boo):
choice = random.choice(["","","S","SA","AA","A"]) choice = random.choice(["","","S","SA","AA","A"])
result += choice result += choice
diceResult.append("boo"+choice) dice_result.append("boo"+choice)
for _ in range(setb): for _ in range(setb):
choice = random.choice(["","","F","F","H","H"]) choice = random.choice(["","","F","F","H","H"])
result += choice result += choice
diceResult.append("setb"+choice) dice_result.append("setb"+choice)
for _ in range (force): for _ in range (force):
choice = random.choice(["B","B","B","B","B","B","BB","L","L","LL","LL","LL"]) choice = random.choice(["B","B","B","B","B","B","BB","L","L","LL","LL","LL"])
result += choice result += choice
diceResult.append("force"+choice) dice_result.append("force"+choice)
return result, diceResult return result, dice_result
# Lets dice cancel each other out # Lets dice cancel each other out
def simplify(self, result : str): def simplify(self, result : str):
@ -78,9 +78,9 @@ class StarWarsRoll():
return simp return simp
# Returns emoji that symbolize the dice results # Returns emoji that symbolize the dice results
def diceResultToEmoji(self, diceResults : list): def dice_result_to_emoji(self, dice_results : list):
emoji = "" emoji = ""
for result in diceResults: for result in dice_results:
if result == "abiA": if result == "abiA":
emoji += "<:abil1a:695267684476125264> " emoji += "<:abil1a:695267684476125264> "
elif result == "abiSA": elif result == "abiSA":
@ -167,7 +167,7 @@ class StarWarsRoll():
return emoji return emoji
# Returns emoji that symbolize the results of the dice rolls # Returns emoji that symbolize the results of the dice rolls
def resultToEmoji(self, result : str): def result_to_emoji(self, result : str):
emoji = "" emoji = ""
for char in result: for char in result:
if char == 'S': if char == 'S':
@ -190,7 +190,7 @@ class StarWarsRoll():
return emoji return emoji
# Converts emoji into letters # Converts emoji into letters
def emojiToResult(self, emoji : str): def emoji_to_result(self, emoji : str):
result = "" result = ""
for char in emoji: for char in emoji:
if char == "<:light:691010089905029171>": if char == "<:light:691010089905029171>":
@ -201,7 +201,7 @@ class StarWarsRoll():
return result return result
# Returns emoji that symbolize the dice # Returns emoji that symbolize the dice
def diceToEmoji(self, dice : list): def dice_to_emoji(self, dice : list):
emoji = "" emoji = ""
for _ in range(dice[0]): for _ in range(dice[0]):
@ -222,7 +222,7 @@ class StarWarsRoll():
return emoji return emoji
# Rolls for obligation # Rolls for obligation
def obligationRoll(self): def obligation_roll(self):
self.bot.log("Rolling for obligation") self.bot.log("Rolling for obligation")
data = self.bot.database["starwarscharacters"] data = self.bot.database["starwarscharacters"]
@ -239,40 +239,40 @@ class StarWarsRoll():
return random.choice(table) return random.choice(table)
# Rolls for critical injury # Rolls for critical injury
async def critRoll(self, ctx, addington : int): async def crit_roll(self, ctx, addington : int):
dd = "<:difficulty:690973992470708296>" difficulty_die = "<:difficulty:690973992470708296>"
sd = "<:setback:690972157890658415>" setback_die = "<:setback:690972157890658415>"
bd = "<:boost:690972178216386561>" boost_die = "<:boost:690972178216386561>"
roll = random.randint(1,100) + addington roll = random.randint(1,100) + addington
injuries = [ injuries = [
"**Minor nick**: The target suffers 1 strain, "+dd] * 5 + [ "**Minor nick**: The target suffers 1 strain, "+difficulty_die] * 5 + [
"**Slowed down**: The target can only act during the last allied initiative slot this turn, "+dd] * 5 + [ "**Slowed down**: The target can only act during the last allied initiative slot this turn, "+difficulty_die] * 5 + [
"**Sudden Jolt**: The target drops whatever is in hand, "+dd] * 5 + [ "**Sudden Jolt**: The target drops whatever is in hand, "+difficulty_die] * 5 + [
"**Distracted**: The target cannot perform a Free maneuver during his next turn, "+dd] * 5 + [ "**Distracted**: The target cannot perform a Free maneuver during his next turn, "+difficulty_die] * 5 + [
"**Off-Balance**: The target adds "+sd+" to his next skill check, "+dd] * 5 + [ "**Off-Balance**: The target adds "+setback_die+" to his next skill check, "+difficulty_die] * 5 + [
"**Discouraging Wound**: Flip one light side Destiny point to a dark side Destiny point (reverse if NPC), "+dd] * 5 + [ "**Discouraging Wound**: Flip one light side Destiny point to a dark side Destiny point (reverse if NPC), "+difficulty_die] * 5 + [
"**Stunned**: The target is staggered until the end of his next turn, "+dd] * 5 + [ "**Stunned**: The target is staggered until the end of his next turn, "+difficulty_die] * 5 + [
"**Stinger**: Increase the difficulty of next check by one, "+dd] * 5 + [ "**Stinger**: Increase the difficulty of next check by one, "+difficulty_die] * 5 + [
"**Bowled Over**: The target is knocked prone and suffers 1 strain, "+dd+dd] * 5 + [ "**Bowled Over**: The target is knocked prone and suffers 1 strain, "+difficulty_die+difficulty_die] * 5 + [
"**Head Ringer**: The target increases the difficulty of all Intellect and Cunning checks by one until the end of the encounter, "+dd+dd] * 5 + [ "**Head Ringer**: The target increases the difficulty of all Intellect and Cunning checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**Fearsome Wound**: The target increases the difficulty of all Presence and Willpower checks by one until the end of the encounter, "+dd+dd] * 5 + [ "**Fearsome Wound**: The target increases the difficulty of all Presence and Willpower checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**Agonizing Wound**: The target increases the difficulty of all Brawn and Agility checks by one until the end of the encounter, "+dd+dd] * 5 + [ "**Agonizing Wound**: The target increases the difficulty of all Brawn and Agility checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**Slightly Dazed**: The target is disoriented until the end of the encounter, "+dd+dd] * 5 + [ "**Slightly Dazed**: The target is disoriented until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**Scattered Senses**: The target removes all "+bd+" from skill checks until the end of the encounter, "+dd+dd] * 5 + [ "**Scattered Senses**: The target removes all "+boost_die+" from skill checks until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**Hamstrung**: The target loses his free maneuver until the end of the encounter, "+dd+dd] * 5 + [ "**Hamstrung**: The target loses his free maneuver until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**Overpowered**: The target leaves himself open, and the attacker may immediately attempt another free attack agains him, using the exact same pool as the original, "+dd+dd] * 5 + [ "**Overpowered**: The target leaves himself open, and the attacker may immediately attempt another free attack agains him, using the exact same pool as the original, "+difficulty_die+difficulty_die] * 5 + [
"**Winded**: Until the end of the encounter, the target cannot voluntarily suffer strain to activate any abilities or gain additional maneuvers, "+dd+dd] * 5 + [ "**Winded**: Until the end of the encounter, the target cannot voluntarily suffer strain to activate any abilities or gain additional maneuvers, "+difficulty_die+difficulty_die] * 5 + [
"**Compromised**: Incerase difficulty of all skill checks by one until the end of the encounter, "+dd+dd] * 5 + [ "**Compromised**: Incerase difficulty of all skill checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
"**At the brink**: The target suffers 1 strain each time he performs an action, "+dd+dd+dd] * 5 + [ "**At the brink**: The target suffers 1 strain each time he performs an action, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
"**Crippled**: One of the target's limbs (selected by the GM) is crippled until healed or replaced. Increase difficulty of all checks that require use of that limb by one, "+dd+dd+dd] * 5 + [ "**Crippled**: One of the target's limbs (selected by the GM) is crippled until healed or replaced. Increase difficulty of all checks that require use of that limb by one, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
"**Maimed**: One of the target's limbs (selected by the GM) is permanently lost. Unless the target has a cybernetic replacement, the target cannot perform actions that would require the use of that limb. All other actions gain "+sd+", "+dd+dd+dd] * 5 + [ "**Maimed**: One of the target's limbs (selected by the GM) is permanently lost. Unless the target has a cybernetic replacement, the target cannot perform actions that would require the use of that limb. All other actions gain "+setback_die+", "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
"HI"] * 5 + [ "HI"] * 5 + [
"**Temporarily Lame**: Until this critical injury is healed, the target cannot perform more than one maneuver during his turn, "+dd+dd+dd] * 5 + [ "**Temporarily Lame**: Until this critical injury is healed, the target cannot perform more than one maneuver during his turn, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
"**Blinded**: The target can no longer see. Upgrade the difficulty of all checks twice. Upgrade the difficulty of perception checks three times, "+dd+dd+dd] * 5 + [ "**Blinded**: The target can no longer see. Upgrade the difficulty of all checks twice. Upgrade the difficulty of perception checks three times, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
"**Knocked Senseless**: The target is staggered for the remainder of the encounter, "+dd+dd+dd] * 5 + [ "**Knocked Senseless**: The target is staggered for the remainder of the encounter, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
"GI"] * 5 + [ "GI"] * 5 + [
"**Bleeding Out**: Every round, the target suffers 1 wound and 1 strain at the beginning of his turn. For every five wounds he suffers beyond his wound threshold, he suffers one additional critical injury. (If he suffers this one again, roll again), "+dd+dd+dd+dd] * 10 + [ "**Bleeding Out**: Every round, the target suffers 1 wound and 1 strain at the beginning of his turn. For every five wounds he suffers beyond his wound threshold, he suffers one additional critical injury. (If he suffers this one again, roll again), "+difficulty_die+difficulty_die+difficulty_die+difficulty_die] * 10 + [
"**The End is Nigh**: The target will die after the last initiative slot during the next round, "+dd+dd+dd+dd] * 10 + [ "**The End is Nigh**: The target will die after the last initiative slot during the next round, "+difficulty_die+difficulty_die+difficulty_die+difficulty_die] * 10 + [
"**Dead**: U B Dead :("] "**Dead**: U B Dead :("]
if roll >= len(injuries): if roll >= len(injuries):
@ -282,56 +282,56 @@ class StarWarsRoll():
if results == "HI": if results == "HI":
characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"]) characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"])
results = "**Horrific Injury**: Until this criticil injury is healed, treat the target's "+characteristic+" as if it's one lower, "+dd+dd+dd results = "**Horrific Injury**: Until this criticil injury is healed, treat the target's "+characteristic+" as if it's one lower, "+difficulty_die+difficulty_die+difficulty_die
if results == "GI": if results == "GI":
characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"]) characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"])
results = "**Gruesome Injury**: The target's "+characteristic+" is permanently one lower, "+dd+dd+dd+dd results = "**Gruesome Injury**: The target's "+characteristic+" is permanently one lower, "+difficulty_die+difficulty_die+difficulty_die+difficulty_die
send_message = "Roll: "+str(roll)+"\nInjury:\n"+results send_message = "Roll: "+str(roll)+"\nInjury:\n"+results
message_list = send_message.split("\n") message_list = send_message.split("\n")
await ctx.send(message_list[0]) await ctx.send(message_list[0])
if len(message_list) > 1: if len(message_list) > 1:
for messageItem in message_list[1:]: for message_item in message_list[1:]:
await ctx.channel.send(messageItem) await ctx.channel.send(message_item)
# Parses the command into something the other functions understand # Parses the command into something the other functions understand
async def parseRoll(self, ctx, cmd : str = ""): async def parse_roll(self, ctx, cmd : str = ""):
user = f"#{ctx.author.id}" user = f"#{ctx.author.id}"
cmd = re.sub(' +',' ',cmd.upper()) + " " cmd = re.sub(' +',' ',cmd.upper()) + " "
if cmd[0] == " ": if cmd[0] == " ":
cmd = cmd[1:] cmd = cmd[1:]
cmd = self.bot.star_wars.character.replaceSpaces(string.capwords(cmd)) cmd = self.bot.star_wars.character.replaceSpaces(string.capwords(cmd))
commands = cmd.split(" ") commands = cmd.split(" ")
validCommand = False valid_command = False
if commands[0] == "": if commands[0] == "":
rollParameters = [1,0,3,0,0,0,0] roll_parameters = [1,0,3,0,0,0,0]
else: else:
rollParameters = [0,0,0,0,0,0,0] roll_parameters = [0,0,0,0,0,0,0]
if string.capwords(commands[0]) == "Obligations": if string.capwords(commands[0]) == "Obligations":
send_message = self.obligationRoll() send_message = self.obligation_roll()
elif string.capwords(commands[0]) in skill_data: elif string.capwords(commands[0]) in skill_data:
self.bot.log("Oh look! This guy has skills!") self.bot.log("Oh look! This guy has skills!")
if self.bot.star_wars.character.userHasChar(user): if self.bot.star_wars.character.userHasChar(user):
self.bot.log("They have a character. That much we know") self.bot.log("They have a character. That much we know")
skillLevel = self.bot.star_wars.character.char_data(user,"Skills " + string.capwords(commands[0])) skill_level = self.bot.star_wars.character.char_data(user,"Skills " + string.capwords(commands[0]))
if string.capwords(commands[0]) == "Lightsaber": if string.capwords(commands[0]) == "Lightsaber":
self.bot.log("The skill is lightsaber") self.bot.log("The skill is lightsaber")
charLevel = self.bot.star_wars.character.char_data(user,"Characteristics " + self.bot.star_wars.character.lightsaberChar(user)) char_level = self.bot.star_wars.character.char_data(user,"Characteristics " + self.bot.star_wars.character.lightsaberChar(user))
else: else:
charLevel = self.bot.star_wars.character.char_data(user,"Characteristics " + skill_data[string.capwords(commands[0])]) char_level = self.bot.star_wars.character.char_data(user,"Characteristics " + skill_data[string.capwords(commands[0])])
abilityDice = abs(charLevel-skillLevel) ability_dice = abs(char_level-skill_level)
proficiencyDice = min(skillLevel,charLevel) proficiency_dice = min(skill_level,char_level)
commands = [str(abilityDice)] + [str(proficiencyDice)] + commands[1:] commands = [str(ability_dice)] + [str(proficiency_dice)] + commands[1:]
self.bot.log("Converted skill to dice") self.bot.log("Converted skill to dice")
validCommand = True valid_command = True
else: else:
self.bot.log("Okay, no they don't i guess") self.bot.log("Okay, no they don't i guess")
send_message = "You don't have a user. You can make one with /starwarscharacter" send_message = "You don't have a user. You can make one with /starwarscharacter"
@ -343,49 +343,49 @@ class StarWarsRoll():
else: else:
send_message = "Did you mean \"Piloting - Planetary\" or \"Piloting - Space\"" send_message = "Did you mean \"Piloting - Planetary\" or \"Piloting - Space\""
else: else:
validCommand = True valid_command = True
if validCommand: if valid_command:
self.bot.log("Converting commands to dice") self.bot.log("Converting commands to dice")
for x, command in enumerate(commands): for i, command in enumerate(commands):
if command != "": if command != "":
command = command.upper() command = command.upper()
if command[0] == "A": if command[0] == "A":
rollParameters[0] = int(command.replace("A","")) roll_parameters[0] = int(command.replace("A",""))
elif command[0] == "P": elif command[0] == "P":
rollParameters[1] = int(command.replace("P","")) roll_parameters[1] = int(command.replace("P",""))
elif command[0] == "D": elif command[0] == "D":
rollParameters[2] = int(command.replace("D","")) roll_parameters[2] = int(command.replace("D",""))
elif command[0] == "C": elif command[0] == "C":
rollParameters[3] = int(command.replace("C","")) roll_parameters[3] = int(command.replace("C",""))
elif command[0] == "B": elif command[0] == "B":
rollParameters[4] = int(command.replace("B","")) roll_parameters[4] = int(command.replace("B",""))
elif command[0] == "S": elif command[0] == "S":
rollParameters[5] = int(command.replace("S","")) roll_parameters[5] = int(command.replace("S",""))
elif command[0] == "F": elif command[0] == "F":
rollParameters[6] = int(command.replace("F","")) roll_parameters[6] = int(command.replace("F",""))
else: else:
rollParameters[x] = int(command) roll_parameters[i] = int(command)
self.bot.log("Rolling "+str(rollParameters)) self.bot.log("Rolling "+str(roll_parameters))
rollResults, diceResults = self.roll(rollParameters[0],rollParameters[1],rollParameters[2],rollParameters[3],rollParameters[4],rollParameters[5],rollParameters[6]) roll_results, dice_results = self.roll(roll_parameters[0],roll_parameters[1],roll_parameters[2],roll_parameters[3],roll_parameters[4],roll_parameters[5],roll_parameters[6])
simplified = self.simplify(rollResults) simplified = self.simplify(roll_results)
name = self.bot.star_wars.character.getChar_name(user) name = self.bot.star_wars.character.getChar_name(user)
self.bot.log("Returns results and simplified results") self.bot.log("Returns results and simplified results")
if simplified == "": if simplified == "":
send_message = name + " rolls: " + "\n" + self.diceResultToEmoji(diceResults) + "\nEverything cancels out!" send_message = name + " rolls: " + "\n" + self.dice_result_to_emoji(dice_results) + "\nEverything cancels out!"
else: else:
send_message = name + " rolls: " + "\n" + self.diceResultToEmoji(diceResults) + "\n" + self.resultToEmoji(simplified) send_message = name + " rolls: " + "\n" + self.dice_result_to_emoji(dice_results) + "\n" + self.result_to_emoji(simplified)
message_list = send_message.split("\n") message_list = send_message.split("\n")
await ctx.send(message_list[0]) await ctx.send(message_list[0])
if len(message_list) > 1: if len(message_list) > 1:
for messageItem in message_list[1:]: for message_item in message_list[1:]:
if messageItem == "": if message_item == "":
self.bot.log("Tried to send empty message") self.bot.log("Tried to send empty message")
else: else:
await ctx.channel.send(messageItem) await ctx.channel.send(message_item)