Example #1
0
def argparse(args, character=None, splitter=argsplit):
    """
    Parses arguments.

    :param args: A list of arguments to parse.
    :type args: str or Iterable
    :return: The parsed arguments.
    :rtype: :class:`~utils.argparser.ParsedArguments`
    """
    if isinstance(args, str):
        args = splitter(args)
    if character:
        from aliasing.evaluators import MathEvaluator
        evaluator = MathEvaluator.with_character(character)
        args = [evaluator.transformed_str(a) for a in args]

    parsed = collections.defaultdict(lambda: [])
    index = 0
    for a in args:
        if a.startswith('-'):
            parsed[a.lstrip('-')].append(list_get(index + 1, True, args))
        else:
            parsed[a].append(True)
        index += 1
    return ParsedArguments(parsed)
Example #2
0
    async def csettings(self, ctx, *args):
        """Updates personalization settings for the currently active character.

        __**Valid Arguments**__
        Use `<setting> reset` to reset a setting to the default.

        `color <hex color>` - Colors all character-based built-in embeds this color. Accessible as the cvar `color`
        `criton <number>` - Makes attacks crit on something other than a 20.
        `reroll <number>` - Defines a number that a check will automatically reroll on, for cases such as Halfling Luck.
        `srslots true/false` - Enables/disables whether spell slots reset on a Short Rest.
        `embedimage true/false` - Enables/disables whether a character's image is automatically embedded.
        `critdice <number>` - Adds additional damage dice on a critical hit. 
        `talent true/false` - Enables/disables whether to apply a rogue's Reliable Talent on checks you're proficient with.
        `ignorecrit true/false` - Prevents critical hits from applying, for example with adamantine armor."""  # noqa: E501
        char = await Character.from_ctx(ctx)

        out = []
        skip = False
        for i, arg in enumerate(args):
            if skip:
                continue
            if arg in CHARACTER_SETTINGS:
                skip = True
                out.append(CHARACTER_SETTINGS[arg].run(ctx, char, list_get(i + 1, None, args)))

        if not out:
            return await ctx.send(f"No valid settings found. See `{ctx.prefix}help {ctx.invoked_with}` for a list "
                                  f"of valid settings.")

        await char.commit(ctx)
        await ctx.send('\n'.join(out))
Example #3
0
def argparse(args, character=None, splitter=argsplit):
    """
    Parses arguments.
    :param args: A list of arguments to parse.
    :param character: A Character object, if args should have cvars parsed.
    :param splitter: A function to use to split a string into a list of arguments.
    :return: The parsed arguments (ParsedArguments).
    :rtype ParsedArguments
    """
    if isinstance(args, str):
        args = splitter(args)
    if character:
        from cogs5e.funcs.scripting import MathEvaluator
        evaluator = MathEvaluator.with_character(character)
        args = [evaluator.parse(a) for a in args]

    parsed = collections.defaultdict(lambda: [])
    index = 0
    for a in args:
        if a.startswith('-'):
            parsed[a.lstrip('-')].append(list_get(index + 1, True, args))
        else:
            parsed[a].append(True)
        index += 1
    return ParsedArguments(args, parsed)
Example #4
0
    async def csettings(self, ctx, *args):
        """
        Opens the Character Settings menu.

        In this menu, you can change your character's cosmetic and gameplay settings, such as their embed color,
        crit range, extra crit dice, and more.
        """
        char = await ctx.get_character()

        if not args:
            settings_ui = ui.CharacterSettingsUI.new(ctx.bot,
                                                     owner=ctx.author,
                                                     character=char)
            await settings_ui.send_to(ctx)
            return

        # old deprecated CLI behaviour
        out = []
        skip = False
        for i, arg in enumerate(args):
            if skip:
                continue
            if arg in CHARACTER_SETTINGS:
                skip = True
                out.append(CHARACTER_SETTINGS[arg].run(
                    ctx, char, list_get(i + 1, None, args)))

        if not out:
            return await ctx.send(
                f"No valid settings found. Try `{ctx.prefix}csettings` with no arguments to use an "
                f"interactive menu!")

        await char.options.commit(ctx.bot.mdb, char)
        await ctx.send('\n'.join(out))
Example #5
0
    async def csettings(self, ctx, *args):
        """Updates settings for the currently active character."""
        char = await ctx.get_character()

        if not args:
            settings_ui = ui.CharacterSettingsUI.new(ctx.bot,
                                                     owner=ctx.author,
                                                     character=char)
            await settings_ui.send_to(ctx)
            return

        # old deprecated CLI behaviour
        out = []
        skip = False
        for i, arg in enumerate(args):
            if skip:
                continue
            if arg in CHARACTER_SETTINGS:
                skip = True
                out.append(CHARACTER_SETTINGS[arg].run(
                    ctx, char, list_get(i + 1, None, args)))

        if not out:
            return await ctx.send(
                f"No valid settings found. Try `{ctx.prefix}csettings` with no arguments to use an "
                f"interactive menu!")

        await char.options.commit(ctx.bot.mdb, char)
        await ctx.send('\n'.join(out))
Example #6
0
 def parse_args(self, args):
     out = {}
     index = 0
     for a in args:
         if a == '-f':
             if out.get(a.replace('-', '')) is None:
                 out[a.replace('-', '')] = [list_get(index + 1, None, args)]
             else:
                 out[a.replace('-', '')].append(list_get(index + 1, None, args))
         elif a.startswith('-'):
             nextArg = list_get(index + 1, None, args)
             if nextArg is None or nextArg.startswith('-'): nextArg = True
             out[a.replace('-', '')] = nextArg
         else:
             out[a] = 'True'
         index += 1
     return out
Example #7
0
def argparse(args):
    """
    Parses arguments.
    :param args: A list of arguments to parse.
    :return: The parsed arguments (ParsedArguments).
    """
    parsed = {}
    index = 0
    for a in args:
        if a.startswith('-'):
            if parsed.get(a.lstrip('-')) is None:
                parsed[a.lstrip('-')] = [list_get(index + 1, True, args)]
            else:
                parsed[a.lstrip('-')].append(list_get(index + 1, True, args))
        else:
            if parsed.get(a) is None:
                parsed[a] = [True]
            else:
                parsed[a].append(True)
        index += 1
    return ParsedArguments(args, parsed)
Example #8
0
    async def csettings(self, ctx, *args):
        """Updates personalization settings for the currently active character.
        Valid Arguments:
        `color <hex color>` - Colors all embeds this color.
        `criton <number>` - Makes attacks crit on something other than a 20.
        `reroll <number>` - Defines a number that a check will automatically reroll on, for cases such as Halfling Luck.
        `srslots true/false` - Enables/disables whether spell slots reset on a Short Rest.
        `embedimage true/false` - Enables/disables whether a character's image is automatically embedded.
        `critdice <number>` - Adds additional dice for to critical attacks.
        `talent true/false` - Enables/disables whether to apply a rogue's Reliable Talent on checks you're proficient with."""
        char = await Character.from_ctx(ctx)

        out = ['Operations complete!']
        skip = False
        for i, arg in enumerate(args):
            if skip:
                continue
            if arg in CHARACTER_SETTINGS:
                skip = True
                out.append(CHARACTER_SETTINGS[arg].run(ctx, char, list_get(i + 1, None, args)))

        await char.commit(ctx)
        await ctx.send('\n'.join(out))
Example #9
0
    async def csettings(self, ctx, *args):
        """Updates personalization settings for the currently active character.
        Valid Arguments:
        `color <hex color>` - Colors all embeds this color.
        `criton <number>` - Makes attacks crit on something other than a 20.
        `reroll <number>` - Defines a number that a check will automatically reroll on, for cases such as Halfling Luck.
        `srslots true/false` - Enables/disables whether spell slots reset on a Short Rest.
        `embedimage true/false` - Enables/disables whether a character's image is automatically embedded.
        `critdice <number>` - Adds additional dice for to critical attacks."""
        char: Character = await Character.from_ctx(ctx)

        out = 'Operations complete!\n'
        index = 0
        for arg in args:
            if arg == 'color':
                color = list_get(index + 1, None, args)
                if color is None:
                    current_color = hex(char.get_color()) if char.get_setting(
                        'color') else "random"
                    out += f'\u2139 Your character\'s current color is {current_color}. ' \
                        f'Use "{ctx.prefix}csettings color reset" to reset it to random.\n'
                elif color.lower() == 'reset':
                    char.set_setting('color', None)
                    out += "\u2705 Color reset to random.\n"
                else:
                    try:
                        color = int(color, base=16)
                    except (ValueError, TypeError):
                        out += f'\u274c Unknown color. Use "{ctx.prefix}csettings color reset" to reset it to random.\n'
                    else:
                        if not 0 <= color <= 0xffffff:
                            out += '\u274c Invalid color.\n'
                        else:
                            char.set_setting('color', color)
                            out += "\u2705 Color set to {}.\n".format(
                                hex(color))
            if arg == 'criton':
                criton = list_get(index + 1, None, args)
                if criton is None:
                    current = str(char.get_setting(
                        'criton')) + '-20' if char.get_setting(
                            'criton') else "20"
                    out += f'\u2139 Your character\'s current crit range is {current}. ' \
                        f'Use "{ctx.prefix}csettings criton reset" to reset it to 20.\n'
                elif criton.lower() == 'reset':
                    char.set_setting('criton', None)
                    out += "\u2705 Crit range reset to 20.\n"
                else:
                    try:
                        criton = int(criton)
                    except (ValueError, TypeError):
                        out += f'\u274c Invalid number. Use "{ctx.prefix}csettings criton reset" to reset it to 20.\n'
                    else:
                        if not 0 < criton <= 20:
                            out += '\u274c Crit range must be between 1 and 20.\n'
                        elif criton == 20:
                            char.set_setting('criton', None)
                            out += "\u2705 Crit range reset to 20.\n"
                        else:
                            char.set_setting('criton', criton)
                            out += "\u2705 Crit range set to {}-20.\n".format(
                                criton)
            if arg == 'reroll':
                reroll = list_get(index + 1, None, args)
                if reroll is None:
                    current = char.get_setting('reroll')
                    out += f'\u2139 Your character\'s current reroll is {current}. ' \
                        f'Use "{ctx.prefix}csettings reroll reset" to reset it.\n'
                elif reroll.lower() == 'reset':
                    char.set_setting('reroll', None)
                    out += "\u2705 Reroll reset.\n"
                else:
                    try:
                        reroll = int(reroll)
                    except (ValueError, TypeError):
                        out += f'\u274c Invalid number. Use "{ctx.prefix}csettings reroll reset" to reset it.\n'
                    else:
                        if not 1 <= reroll <= 20:
                            out += '\u274c Reroll must be between 1 and 20.\n'
                        else:
                            char.set_setting('reroll', reroll)
                            out += "\u2705 Reroll set to {}.\n".format(reroll)
            if arg == 'critdice':
                critdice = list_get(index + 1, None, args)
                if critdice is None:
                    current = char.get_setting('critdice')
                    out += f'\u2139 Extra crit dice are currently set to {current}. ' \
                        f'Use "{ctx.prefix}csettings critdice reset" to reset it.\n'
                elif critdice.lower() == 'reset':
                    char.set_setting('critdice', None)
                    out += "\u2705 Extra crit dice reset.\n"
                else:
                    try:
                        critdice = int(critdice)
                    except (ValueError, TypeError):
                        out += f'\u274c Invalid number. Use "{ctx.prefix}csettings critdice reset" to reset it.\n'
                    else:
                        if not 0 <= critdice <= 20:
                            out += f'\u274c Extra crit dice must be between 1 and 20. Use "{ctx.prefix}csettings critdice reset" to reset it.\n'
                        else:
                            char.set_setting('critdice', critdice)
                            out += "\u2705 Extra crit dice set to {}.\n".format(
                                critdice)
            if arg == 'srslots':
                srslots = list_get(index + 1, None, args)
                if srslots is None:
                    out += '\u2139 Short rest slots are currently {}.\n' \
                        .format("enabled" if char.get_setting('srslots') else "disabled")
                else:
                    try:
                        srslots = get_positivity(srslots)
                    except AttributeError:
                        out += f'\u274c Invalid input. Use "{ctx.prefix}csettings srslots false" to reset it.\n'
                    else:
                        char.set_setting('srslots', srslots)
                        out += "\u2705 Short Rest slots {}.\n".format(
                            "enabled" if char.get_setting('srslots'
                                                          ) else "disabled")
            if arg == 'embedimage':
                embedimage = list_get(index + 1, None, args)
                if embedimage is None:
                    out += '\u2139 Embed Image is currently {}.\n' \
                        .format("enabled" if char.get_setting('embedimage') else "disabled")
                else:
                    try:
                        embedimage = get_positivity(embedimage)
                    except AttributeError:
                        out += f'\u274c Invalid input. Use "{ctx.prefix}csettings embedimage true" to reset it.\n'
                    else:
                        char.set_setting('embedimage', embedimage)
                        out += "\u2705 Embed Image {}.\n".format(
                            "enabled" if char.get_setting('embedimage'
                                                          ) else "disabled")
            index += 1

        await char.commit(ctx)
        await ctx.send(out)
from discord.ext import commands
from discord.ext.commands.errors import CommandInvokeError

from cogs5e.models.errors import AvraeException, EvaluationError
from utils.functions import discord_trim, get_positivity, list_get, gen_error_message
from utils.redisIO import RedisIO

TESTING = get_positivity(os.environ.get("TESTING", False))
if 'test' in sys.argv:
    TESTING = True
prefix = '!' if not TESTING else '#'
shard_id = 0
shard_count = 1
SHARDED = False
if '-s' in sys.argv:
    temp_shard_id = list_get(sys.argv.index('-s') + 1, None, sys.argv)
    if temp_shard_id is not None:
        shard_count = os.environ.get('SHARDS', 1)
        shard_id = temp_shard_id if int(temp_shard_id) < int(
            shard_count) else 0
        SHARDED = True
# -----COGS-----
DYNAMIC_COGS = [
    "cogs5e.dice", "cogs5e.charGen", "cogs5e.gametrack", "cogs5e.homebrew",
    "cogs5e.initTracker", "cogs5e.lookup", "cogs5e.pbpUtils",
    "cogs5e.sheetManager", "cogsmisc.customization"
]
STATIC_COGS = [
    "cogsmisc.adminUtils", "cogsmisc.core", "cogsmisc.permissions",
    "cogsmisc.publicity", "cogsmisc.repl", "cogsmisc.stats", "utils.help"
]