Esempio n. 1
0
async def saving_throw(context, stat=None, advantage_or_disadvantage=""):
    server = context.guild.id
    user = get_user_id(str(context.author.id))
    if not stat:
        await context.send(
            f"Hey <@{context.author.id}>, to do a saving throw or ability check do `!st <stat> (a|d)` where stat is one of (con, cha, str, dex, kno, wis). You can also add an a or d to signify advantage or disadvantage."
        )
    stat = stat.lower()[:3]
    current = users[server][user].get("active")
    if current and stat in ALLOWED_STATS:
        bonus = characters[current].get_stat(stat)
        sign = "+"
        if bonus < 0:
            sign = "-"
            bonus *= -1
        query = f"1d20{sign}{bonus}"
        if advantage_or_disadvantage:
            query += advantage_or_disadvantage[0]
        await context.invoke(client.get_command("roll"), query)
    elif current:
        await context.send(
            f"Hey <@{context.author.id}>, that doesn't seem like a valid stat."
        )
    else:
        logger.info(f"{server} couldn't find character ID for {user}")
        await context.send(
            f"Hey <@{context.author.id}>, it looks like you haven't created any characters yet."
        )
Esempio n. 2
0
async def create_character(context, user, name, level, gold, *stats):
    # Stats = HP, Attack, Defense, Speed, Dexterity, Charisma, Knowledge, Wisdom, Strength, Constitution,
    try:
        character = PlayerCharacter(user, name, *stats, level, gold)
    except TypeError:
        await context.send(
            f"Hey uh <@{context.author.id}>, you're missing some stats there."
        )
        return
    await context.send(
        f"Got it! Your character has now been created. Check it out! If it looks good, send a Y to confirm. Otherwise send a N."
    )
    await context.send(character.info())
    message = await client.wait_for("message", timeout=20)
    if message and message.content.lower()[0] == "y":
        server = context.guild.id
        user = get_user_id(user)
        uuid = gen_utils.generate_unique_id(set(characters.keys()))
        characters[uuid] = character
        users[server][user]["characters"].append(uuid)
        users[server][user]["active"] = uuid
        gen_utils.save_file(users, get_file_path("users"))
        gen_utils.save_file(characters, get_file_path("characters"))
        logger.info(f"Created Character for {name} ({user})")
        await context.send(f"Your character has been saved!")
    else:
        await context.send(f"Well that was useless. Your character has not been saved.")
Esempio n. 3
0
def execute_non_select_sql_query(conn, sql_query):
    try:
        with conn.cursor() as cur:
            cur.execute(sql_query)
            conn.commit()
            logger.info("DB output: " + str(cur.statusmessage))
    except (Exception, psycopg2.DatabaseError) as error:
        logger.error(error)
Esempio n. 4
0
def execute_select_sql_query(conn, sql_query):
    try:
        with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
            cur.execute(sql_query)
            result = cur.fetchone()
            logger.info("DB output: " + str(cur.statusmessage))
            return result
    except (Exception, psycopg2.DatabaseError) as error:
        logger.error(error)
Esempio n. 5
0
async def character_info(context, user=None):
    server = context.guild.id
    if user:
        user = get_user_id(user)
    else:
        user = get_user_id(str(context.author.id))
    current = users[server][user].get("active")
    if current:
        await context.send(characters[current].info())
    else:
        logger.info(f"{server}: couldn't find character ID for {user}")
        await context.send(f"<@{user}> doesn't have any characters yet.")
Esempio n. 6
0
async def roll(context, *roll):
    roll = "".join(roll).lower().replace(" ", "")
    author = context.author
    logger.info(f"Roll: {author.name + '#' + author.discriminator} :: {roll}")
    advantage_or_disadvantage = roll[-1] in ["a", "d"]
    repeat_roll = len(roll.split("r")) > 1
    if advantage_or_disadvantage:
        result = roll_dice.with_advantage_or_disadvantage(
            roll[:-1], roll[-1], author.id
        )
    elif repeat_roll:
        roll, repeats = roll.split("r")
        if repeats.isdigit():
            result = roll_dice.and_repeat(roll, int(repeats), author.id)
        else:
            result = f"<@{author.id}>, if you want to roll multiple times, do`?r <roll>r<num_times>`."
    else:
        result = roll_dice.normally(roll, author.id)
    await context.send(result)
Esempio n. 7
0
def load_files(file_root_dir, file_dict):
    dicts = {
        "users": defaultdict(partial(defaultdict, get_default_user)),
        "characters": dict(),
        "abilities": defaultdict(partial(defaultdict, dict)),
        "items": defaultdict(partial(defaultdict, dict)),
        "aliases": defaultdict(list),
    }
    for key, value in file_dict.items():
        file_path = os.path.join(f"{file_root_dir}/{value}")
        if os.path.exists(file_path):
            logger.info(f"Loading from {file_path}")
            dicts[key] = joblib.load(file_path)
    return (
        dicts["users"],
        dicts["characters"],
        dicts["abilities"],
        dicts["items"],
        dicts["aliases"],
    )
Esempio n. 8
0
async def change_stat(context, user, stat, value):
    server = context.guild.id
    user = get_user_id(user)
    value = int(value)
    stat = stat.lower()[:3]
    current = users[server][user].get("active")
    if current and stat in ALLOWED_STATS:
        old_value = characters[current].get_stat(stat)
        characters[current].set_stat(stat, value)
        character_name = characters[current].get_name()
        await context.send(
            f"Successfully changed the stat for {character_name}(<@{user}>) from {old_value} to {value}!"
        )
    elif current:
        await context.send(
            f"Hey <@{context.author.id}>, that doesn't seem like a valid stat."
        )
    else:
        logger.info(f"{server} couldn't find character ID for {user}")
        await context.send(
            f"Hey <@{context.author.id}>, it looks like that person doesn't have any characters yet."
        )
Esempio n. 9
0
# async def create_ability(context):
#     # Have a file containing abilities
#     # Only Admins can make abilities
#     pass


@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game("with fate."))


@client.event
async def on_command_error(context, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await context.send(
            f"<@{context.author.id}>, doesn't seem like you gave enough information for that command!"
        )
    elif isinstance(error, commands.MissingPermissions):
        await context.send(f"You have no power here, <@{context.author.id}> the Grey.")
    else:
        raise error


if __name__ == "__main__":
    logger.info("Loading DnData..")
    users, characters, abilities, items, aliases = gen_utils.load_files(
        DATA_LOCATION, DATAFILE_NAMES
    )
    logger.info("Booting up client..")
    client.run(TOKEN)
Esempio n. 10
0
def save_file(data, file_path):
    logger.info(f"Saving to {file_path}")
    joblib.dump(data, file_path)