Beispiel #1
0
async def shootfoot(cmd: SigmaCommand, message: discord.Message, args: list):
    global feet_data
    if not feet_data:
        with open(cmd.resource('feets.yml')) as footfile:
            feet_data = yaml.safe_load(footfile)
    if args:
        foot_lang = None
        foot_lang_search = args[0].lower()
        for foot_key in feet_data.keys():
            if foot_key.lower() == foot_lang_search:
                foot_lang = foot_key
        if foot_lang:
            joke_list = feet_data.get(foot_lang)
        else:
            joke_list = None
    else:
        foot_lang = secrets.choice(list(feet_data.keys()))
        joke_list = feet_data.get(foot_lang)
    if joke_list:
        joke = secrets.choice(joke_list)
        response = discord.Embed(color=0xbf6952, title=f'🔫 How to shoot yourself in the foot with {foot_lang}...')
        response.description = joke
    else:
        response = discord.Embed(color=0x696969, title=f'🔍 I don\'t know how to do it with {foot_lang_search}.')
    await message.channel.send(embed=response)
Beispiel #2
0
async def cook(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    global recipe_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if not recipe_core:
        recipe_core = RecipeCore(cmd.resource('data'))
    if args:
        lookup = ' '.join(args)
        recipe = recipe_core.find_recipe(lookup)
        used_items = []
        if recipe:
            req_satisfied = True
            for ingredient in recipe.ingredients:
                user_inv = await cmd.db.get_inventory(message.author)
                in_inventory = False
                for item in user_inv:
                    if item['item_file_id'] == ingredient.file_id:
                        used_items.append(item)
                        in_inventory = True
                        break
                if not in_inventory:
                    req_satisfied = False
            if req_satisfied:
                cooked_item_data = item_core.get_item_by_name(
                    recipe.name).generate_inventory_item()
                await cmd.db.add_to_inventory(message.author, cooked_item_data)
                for req_item in used_items:
                    await cmd.db.del_from_inventory(message.author,
                                                    req_item['item_id'])
                quality = cook_quality[cooked_item_data['quality']]
                connector = 'a'
                if quality[0].lower() in ['a', 'e', 'i', 'o', 'u']:
                    connector = 'an'
                head_title = f'{recipe.icon} You made {connector} {quality.lower()} {recipe.name}'
                response = discord.Embed(color=recipe.color, title=head_title)
                response.set_author(name=message.author.display_name,
                                    icon_url=user_avatar(message.author))
            else:
                response = discord.Embed(
                    color=0xBE1931, title=f'❗ You\'re missing ingredients.')
        else:
            response = discord.Embed(color=0x696969,
                                     title=f'🔍 I couldn\'t find that.')
    else:
        response = discord.Embed(color=0xBE1931, title=f'❗ Nothing inputted.')
    await message.channel.send(embed=response)
Beispiel #3
0
async def timeconvert(cmd: SigmaCommand, message: discord.Message, args: list):
    global tz_aliases
    global tz_offsets
    if not tz_aliases:
        with open(cmd.resource('tz_aliases.yml')) as tz_a_file:
            tz_aliases = yaml.safe_load(tz_a_file)
    if not tz_offsets:
        with open(cmd.resource('tz_offsets.yml')) as tz_o_file:
            tz_offsets = yaml.safe_load(tz_o_file)
    if args:
        conv_input = ' '.join(args).split('>')
        if len(conv_input) == 2:
            from_pieces = conv_input[0].split()
            if len(from_pieces) == 2:
                from_time = from_pieces[0]
                from_zone = from_pieces[1]
                if from_zone.lower() in tz_aliases:
                    from_zone = tz_aliases.get(from_zone.lower())
                if from_zone.lower() in tz_offsets:
                    from_zone = tz_offsets.get(from_zone.lower())
                to_zone = conv_input[1]
                if to_zone.lower() in tz_aliases:
                    to_zone = tz_aliases.get(to_zone.lower())
                if to_zone.lower() in tz_offsets:
                    to_zone = tz_offsets.get(to_zone.lower())
                try:
                    from_string = f'{arrow.utcnow().format("YYYY-MM-DD")} {from_time}:00'
                    if from_zone != 0:
                        from_arrow = arrow.get(from_string).to(str(from_zone))
                    else:
                        from_arrow = arrow.get(from_string)
                    to_arrow = from_arrow.to(str(to_zone))
                    time_out = to_arrow.format('DD. MMM. YYYY - HH:mm:ss (ZZ)')
                    response = discord.Embed(color=0xf9f9f9,
                                             title=f'🕥 {time_out}')
                except ParserError:
                    response = discord.Embed(
                        color=0xBE1931, title='❗ Could not parse that time.')
            else:
                response = discord.Embed(color=0xBE1931,
                                         title='❗ Invalid first argument.')
        else:
            response = discord.Embed(color=0xBE1931,
                                     title='❗ Invalid input arguments.')
    else:
        response = discord.Embed(color=0xBE1931, title='❗ Nothing inputted.')
    await message.channel.send(embed=response)
async def inventorystats(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    inv = await cmd.db.get_inventory(target)
    item_o_list = []
    for item in inv:
        item_o = item_core.get_item_by_file_id(item['item_file_id'])
        item_o_list.append(item_o)
    item_o_list = sorted(item_o_list, key=lambda x: x.rarity, reverse=True)
    inv = item_o_list
    if inv:
        total_value = 0
        rarity_dict = {}
        type_dict = {}
        for item_o_item in item_o_list:
            total_value += item_o_item.value
            if item_o_item.type.lower() in type_dict:
                type_count = type_dict[item_o_item.type.lower()]
            else:
                type_count = 0
            type_count += 1
            type_dict.update({item_o_item.type.lower(): type_count})
            if item_o_item.rarity_name in rarity_dict:
                rare_count = rarity_dict[item_o_item.rarity_name]
            else:
                rare_count = 0
            rare_count += 1
            rarity_dict.update({item_o_item.rarity_name: rare_count})
        type_keys = ['fish', 'plant', 'animal']
        type_list = []
        for type_key in type_keys:
            if type_key in type_dict:
                type_num = type_dict[type_key]
            else:
                type_num = 0
            type_list.append([type_key.upper(), type_num])
        type_out = boop(type_list)
        rare_keys = ['common', 'uncommon', 'rare', 'legendary', 'prime',
                     'spectral', 'ethereal', 'antimatter', 'omnipotent']
        rare_list = []
        for rare_key in rare_keys:
            if rare_key in rarity_dict:
                rare_num = rarity_dict[rare_key]
            else:
                rare_num = 0
            rare_list.append([rare_key.upper(), rare_num])
        rare_out = boop(rare_list)
        response = discord.Embed(color=0xc16a4f)
        response.set_author(name=f'{target.name}#{target.discriminator}', icon_url=user_avatar(target))
        response.add_field(name='Items by Type', value=f'```py\n{type_out}\n```', inline=False)
        response.add_field(name='Items by Rarity', value=f'```py\n{rare_out}\n```', inline=False)
    else:
        response = discord.Embed(color=0xc6e4b5, title='💸 Totally empty...')
    await message.channel.send(embed=response)
Beispiel #5
0
 def load_command_executable(self, root: str, command_data: dict, plugin_data: dict):
     command_data.update({'path': os.path.join(root)})
     command_function = self.load_function(root, command_data)
     cmd = SigmaCommand(self.bot, command_function, plugin_data, command_data)
     if cmd.alts:
         for alt in cmd.alts:
             self.alts.update({alt: cmd.name})
     self.commands.update({command_data.get('name'): cmd})
Beispiel #6
0
async def sell(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    currency = cmd.bot.cfg.pref.currency
    if args:
        inv = await cmd.db.get_inventory(message.author)
        if inv:
            lookup = ' '.join(args)
            if lookup == 'all':
                value = 0
                count = 0
                for invitem in inv:
                    item_ob_id = item_core.get_item_by_file_id(
                        invitem['item_file_id'])
                    value += item_ob_id.value
                    count += 1
                    await cmd.db.del_from_inventory(message.author,
                                                    invitem['item_id'])
                await cmd.db.add_currency(message.author, message.guild, value)
                currency = cmd.bot.cfg.pref.currency
                response = discord.Embed(
                    color=0xc6e4b5,
                    title=f'💶 You sold {count} items for {value} {currency}.')
            else:
                item_o = item_core.get_item_by_name(lookup)
                if item_o:
                    item = await cmd.db.get_inventory_item(
                        message.author, item_o.file_id)
                else:
                    item = None
                if item:
                    value = item_o.value
                    await cmd.db.add_currency(message.author, message.guild,
                                              value)
                    await cmd.db.del_from_inventory(message.author,
                                                    item['item_id'])
                    response = discord.Embed(
                        color=0xc6e4b5,
                        title=
                        f'💶 You sold the {item_o.name} for {value} {currency}.'
                    )
                else:
                    response = discord.Embed(
                        color=0x696969,
                        title=
                        f'🔍 I didn\'t find any {lookup} in your inventory.')
        else:
            response = discord.Embed(
                color=0xc6e4b5,
                title=f'💸 Your inventory is empty, {message.author.name}...')
    else:
        response = discord.Embed(color=0xBE1931,
                                 title='❗ You didn\'t input anything.')
    await message.channel.send(embed=response)
Beispiel #7
0
async def realprogrammers(cmd: SigmaCommand, message: discord.Message,
                          args: list):
    global joke_cache
    if not joke_cache:
        with open(cmd.resource('real-programmers'), 'r',
                  encoding='utf-8') as joke_file:
            joke_cache = yaml.safe_load(joke_file)
    joke = secrets.choice(joke_cache)
    response = discord.Embed(color=0xf9f9f9, title=f'💻 Real programmers...')
    response.description = joke
    await message.channel.send(embed=response)
Beispiel #8
0
async def dadjoke(cmd: SigmaCommand, message: discord.Message, args: list):
    with open(cmd.resource('dadjokes.json'), 'r',
              encoding='utf-8') as dadjokes_file:
        jokes = dadjokes_file.read()
        jokes = json.loads(jokes)
    joke_list = jokes['JOKES']
    end_joke_choice = secrets.choice(joke_list)
    end_joke = end_joke_choice['setup']
    punchline = end_joke_choice['punchline']
    embed = discord.Embed(color=0xFFDC5D)
    embed.add_field(name='😖 Have An Awful Dad Joke',
                    value=f'{end_joke}\n...\n{punchline}')
    await message.channel.send(None, embed=embed)
Beispiel #9
0
 def load_command_executable(self, root, command_data, module_data):
     """
     Loads the command's executable and defining function call.
     :type root: str
     :type command_data: dict
     :type module_data: dict
     """
     command_data.update({'path': os.path.join(root)})
     command_function = self.load_function(root, command_data)
     cmd = SigmaCommand(self.bot, command_function, module_data, command_data)
     if cmd.alts:
         for alt in cmd.alts:
             self.alts.update({alt: cmd.name})
     self.commands.update({command_data.get('name'): cmd})
Beispiel #10
0
async def filtersell(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if args:
        full_qry = ' '.join(args)
        arguments = full_qry.split(':')
        if len(arguments) >= 2:
            mode = arguments[0].lower()
            lookup = ' '.join(arguments[1:])
            inv = await cmd.db.get_inventory(message.author)
            if inv:
                sell_count = 0
                sell_value = 0
                if mode == 'name':
                    attribute = 'name'
                elif mode == 'type':
                    attribute = 'type'
                elif mode == 'rarity' or mode == 'quality':
                    attribute = 'rarity_name'
                else:
                    attribute = None
                if attribute:
                    sell_id_list = []
                    for item in inv:
                        item_ob_id = item_core.get_item_by_file_id(
                            item['item_file_id'])
                        item_attribute = getattr(item_ob_id, attribute)
                        if item_attribute.lower() == lookup.lower():
                            sell_value += item_ob_id.value
                            sell_count += 1
                            sell_id_list.append(item['item_id'])
                    await sell_item_ids(cmd.db, message.author, sell_id_list)
                    await cmd.db.add_currency(message.author, message.guild,
                                              sell_value)
                    currency = cmd.bot.cfg.pref.currency
                    sell_title = f'💶 You sold {sell_count} items for {sell_value} {currency}.'
                    response = discord.Embed(color=0xc6e4b5, title=sell_title)
                else:
                    response = discord.Embed(color=0xBE1931,
                                             title='❗ Invalid arguments.')
            else:
                response = discord.Embed(color=0xBE1931,
                                         title='❗ Your inventory is empty.')
        else:
            response = discord.Embed(color=0xBE1931,
                                     title='❗ Invalid number of arguments.')
    else:
        response = discord.Embed(color=0xBE1931, title='❗ Nothing inputted.')
    await message.channel.send(embed=response)
Beispiel #11
0
async def wfbounties(cmd: SigmaCommand, message: discord.Message, args: list):
    if args:
        try:
            btier = abs(int(args[0]))
            if not 5 >= btier >= 1:
                btier = None
        except ValueError:
            btier = None
        if btier:
            world_state = 'http://content.warframe.com/dynamic/worldState.php'
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(world_state) as data:
                        data = await data.read()
                        data = json.loads(data)
                synd_missions = data['SyndicateMissions']
                poe_data = None
                for synd_mission in synd_missions:
                    if synd_mission['Tag'] == 'CetusSyndicate':
                        poe_data = synd_mission
            except aiohttp.ClientPayloadError:
                poe_data = None
            if poe_data:
                end_stamp = int(poe_data['Expiry']['$date']['$numberLong']) // 1000
                end_arr = arrow.get(end_stamp)
                with open(cmd.resource('bounty_rewards.yml'), encoding='utf-8') as reward_file:
                    reward_data = yaml.safe_load(reward_file)
                job_index = btier - 1
                job = poe_data['Jobs'][job_index]
                job_mission = capital_split(job.get('jobType').split('/')[-1])
                job_rewards = reward_data.get(job.get('rewards').split('/')[-1])
                job_info = f'Levels: {job.get("minEnemyLevel")} - {job.get("maxEnemyLevel")}'
                job_info += f' | Standing: {job.get("xpAmounts")[0]} - {job.get("xpAmounts")[-1]}'
                job_info += f' | Mission: {job_mission}'
                cetus_wh = 'https://vignette.wikia.nocookie.net/warframe/images/8/80/OstronSigil.png'
                cetus_or = 'https://i.imgur.com/Bbz9JOJ.png'
                response = discord.Embed(color=0xb74624, timestamp=end_arr.datetime)
                response.set_author(name=f'Ostron Tier {btier} Bounty', icon_url=cetus_or)
                response.add_field(name='Job Information', value=job_info)
                response.add_field(name='Bounty Rewards', value=', '.join(job_rewards))
                response.set_footer(text=f'Bounties change {end_arr.humanize()}.', icon_url=cetus_wh)
            else:
                response = discord.Embed(title='❗ Could not retrieve Plains of Eidolon data.', color=0xBE1931)
        else:
            response = discord.Embed(title='❗ Invalid tier provided.', color=0xBE1931)
    else:
        response = discord.Embed(title='❗ Please provide a bounty tier.', color=0xBE1931)
    await message.channel.send(embed=response)
Beispiel #12
0
async def finditem(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if args:
        lookup = ' '.join(args)
        item = item_core.get_item_by_name(lookup)
        if item:
            response = item.make_inspect_embed(cmd.bot.cfg.pref.currency)
        else:
            response = discord.Embed(color=0x696969,
                                     title=f'🔍 I didn\'t find any {lookup}.')
    else:
        response = discord.Embed(color=0xBE1931,
                                 title='❗ You didn\'t input anything.')
    await message.channel.send(embed=response)
Beispiel #13
0
async def viewrecipe(cmd: SigmaCommand, message: discord.Message, args: list):
    global recipe_core
    if not recipe_core:
        recipe_core = RecipeCore(cmd.resource('data'))
    if args:
        lookup = ' '.join(args)
        recipe = recipe_core.find_recipe(lookup)
        currency = cmd.bot.cfg.pref.currency
        if recipe:
            response = discord.Embed(color=recipe.color)
            ingredients = ''
            ing_value = 0
            recipe.ingredients.sort(key=lambda x: x.name)
            req_satisfied = True
            for ingredient in recipe.ingredients:
                user_inv = await cmd.db.get_inventory(message.author)
                in_inventory = False
                for item in user_inv:
                    if item['item_file_id'] == ingredient.file_id:
                        in_inventory = True
                        break
                if in_inventory:
                    in_inventory = '▫'
                else:
                    in_inventory = '▪'
                    req_satisfied = False
                ingredients += f'\n{in_inventory} **{ingredient.name}**'
                ing_value += ingredient.value
            ing_icon = recipe.ingredients[0].icon
            item_title = f'{recipe.icon} {recipe.name}'
            item_short = f'Type: **{recipe.type}**\nValue: **{recipe.value} {currency}**'
            item_short += f'\nHave Ingredients: **{req_satisfied}**'
            item_short += f'\nIngredient Value: **{ing_value} {currency}**'
            response.add_field(name=item_title, value=item_short, inline=True)
            response.add_field(name=f'{ing_icon} Ingredients',
                               value=ingredients,
                               inline=True)
            response.add_field(name='📰 Description',
                               value=recipe.desc,
                               inline=False)
        else:
            response = discord.Embed(color=0x696969,
                                     title=f'🔍 I couldn\'t find that.')
    else:
        response = discord.Embed(color=0xBE1931, title=f'❗ Nothing inputted.')
    await message.channel.send(embed=response)
Beispiel #14
0
async def httpstatus(cmd: SigmaCommand, message: discord.Message, args: list):
    if args:
        lookup = args[0]
        with open(cmd.resource('http_status.json'), 'r', encoding='utf-8') as status_file:
            status_data = json.loads(status_file.read())
        if lookup in status_data:
            status_id = lookup
            status_data = status_data[status_id]
            status_message = status_data['message']
            status_description = status_data['description']
            response = discord.Embed(color=0x3B88C3)
            response.add_field(name=f'🌐 {status_id}: {status_message}', value=f'{status_description}.')
        else:
            response = discord.Embed(color=0xBE1931, title='❗ Invalid status code.')
    else:
        response = discord.Embed(color=0xBE1931, title='❗ Nothing inputted.')
    await message.channel.send(embed=response)
async def itemstatistics(cmd: SigmaCommand, message: discord.Message,
                         args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    page_number = 1
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    if args:
        try:
            page_number = abs(int(args[0]))
            if page_number == 0:
                page_number = 1
        except TypeError:
            page_number = 1
        except ValueError:
            page_number = 1
    start_range = (page_number - 1) * 10
    end_range = page_number * 10
    all_stats = await cmd.db[cmd.db.db_cfg.database].ItemStatistics.find_one(
        {'UserID': target.id}) or {}
    if '_id' in all_stats:
        all_stats.pop('_id')
        all_stats.pop('UserID')
    all_stats = [[x, all_stats.get(x)] for x in all_stats.keys()]
    mem_count = len(all_stats)
    all_stats = sorted(all_stats, key=lambda k: k[1], reverse=True)
    all_stats = all_stats[start_range:end_range]
    listing = []
    for stat in all_stats:
        item_o = item_core.get_item_by_file_id(stat[0])
        amount = stat[1]
        listing.append([item_o.name, amount])
    out_table = boop(listing, ['Item', 'Count'])
    response = discord.Embed(color=0xc16a4f)
    response.set_author(name=f'{target.name}\'s Item Statistics',
                        icon_url=user_avatar(target))
    response.description = f'```hs\n{out_table}\n```'
    response.set_footer(
        text=
        f'{target.name} has found {mem_count} out of {len(item_core.all_items)} items.'
    )
    await message.channel.send(embed=response)
Beispiel #16
0
 def load_command_executable(self, root, command_data, module_data):
     """
     Loads the command's executable and defining function call.
     :param root: The command origin path.
     :type root: str
     :param command_data: Document containing the command's details.
     :type command_data: dict
     :param module_data: Document containing the module's details.
     :type module_data: dict
     :return:
     :rtype:
     """
     command_data.update({'path': os.path.join(root)})
     command_function = self.load_function(root, command_data)
     cmd = SigmaCommand(self.bot, command_function, module_data,
                        command_data)
     if cmd.alts:
         for alt in cmd.alts:
             self.alts.update({alt: cmd.name})
     self.commands.update({command_data.get('name'): cmd})
Beispiel #17
0
async def recipes(cmd: SigmaCommand, message: discord.Message, args: list):
    global recipe_core
    if not recipe_core:
        recipe_core = RecipeCore(cmd.resource('data'))
    if args:
        try:
            page = int(args[0]) - 1
            if page < 0:
                page = 0
        except ValueError:
            page = 0
    else:
        page = 0
    list_start = page * 10
    list_end = (page + 1) * 10
    recipe_list = sorted(recipe_core.recipes,
                         key=lambda x: x.name)[list_start:list_end]
    recipe_look = secrets.choice(recipe_core.recipes)
    recipe_icon = recipe_look.icon
    recipe_color = recipe_look.color
    recipe_boop_head = ['Name', 'Type', 'Value', 'Ingr.']
    recipe_boop_list = []
    stats_text = f'Showing recipes: {list_start}-{list_end}.'
    stats_text += f'\nThere is a total of {len(recipe_core.recipes)} recipes.'
    if recipe_list:
        for recipe in recipe_list:
            req_satisfied = await check_requirements(cmd, message, recipe)
            recipe_boop_list.append(
                [recipe.name, recipe.type, recipe.value, req_satisfied])
        recipe_table = boop(recipe_boop_list, recipe_boop_head)
        response = discord.Embed(color=recipe_color)
        response.add_field(name=f'{recipe_icon} Recipe Stats',
                           value=f'```py\n{stats_text}\n```',
                           inline=False)
        response.add_field(name=f'📰 Recipes On Page {page + 1}',
                           value=f'```hs\n{recipe_table}\n```')
    else:
        response = discord.Embed(color=0x696969,
                                 title=f'🔍 This page is empty.')
    await message.channel.send(embed=response)
Beispiel #18
0
async def chances(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    if args:
        try:
            upgrade_level = int(args[-1])
        except ValueError:
            upgrade_level = None
    else:
        upgrade_level = None
    if upgrade_level is None:
        upgrade_file = await cmd.db[cmd.db.db_cfg.database].Upgrades.find_one({'UserID': target.id}) or {}
        upgrade_level = upgrade_file.get('luck') or 0
    top_roll, rarities = item_core.create_roll_range(upgrade_level)
    out_lines = []
    table_head = ['Rarity', 'Chance']
    for rarity_key in rarities.keys():
        if rarity_key != 0:
            new_key = rarity_key - 1
            range_top = rarities.get(rarity_key) - rarities.get(new_key)
            chance = round((range_top / top_roll) * 100, 5)
            out_line = [rarity_names.get(new_key).title(), f'{chance}%']
            out_lines.append(out_line)
    range_top = top_roll - rarities.get(9)
    chance = round((range_top / top_roll) * 100, 5)
    out_line = [rarity_names.get(9).title(), f'{chance}%']
    out_lines.append(out_line)
    out_table = boop(out_lines, table_head)
    response = discord.Embed(color=0x1b6f5f)
    response.set_author(name=f'{target.name}\'s Item Chances', icon_url=user_avatar(target))
    response.add_field(name=f'Lv{upgrade_level} Chances Table', value=f'```bat\n{out_table}\n```', inline=False)
    await message.channel.send(embed=response)
Beispiel #19
0
async def inventory(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    upgrade_file = await cmd.db[cmd.db.db_cfg.database
                                ].Upgrades.find_one({'UserID': target.id})
    if upgrade_file is None:
        await cmd.db[cmd.db.db_cfg.database
                     ].Upgrades.insert_one({'UserID': target.id})
        upgrade_file = {}
    if 'storage' in upgrade_file:
        storage = upgrade_file['storage']
    else:
        storage = 0
    inv_limit = 64 + (8 * storage)
    page_number = 1
    if args:
        try:
            page_number = abs(int(args[0]))
            if page_number == 0:
                page_number = 1
        except TypeError:
            page_number = 1
        except ValueError:
            page_number = 1
    start_range = (page_number - 1) * 10
    end_range = page_number * 10
    inv = await cmd.db.get_inventory(target)
    total_inv = len(inv)
    item_o_list = []
    for item in inv:
        item_o = item_core.get_item_by_file_id(item['item_file_id'])
        item_o_list.append(item_o)
    item_o_list = sorted(item_o_list, key=lambda x: x.rarity, reverse=True)
    inv = item_o_list[start_range:end_range]
    if inv:
        headers = ['Type', 'Item', 'Value', 'Rarity']
        to_format = []
        total_value = 0
        for item_o_item in inv:
            to_format.append([
                item_o_item.type, item_o_item.name, f'{item_o_item.value}',
                f'{item_o_item.rarity_name.title()}'
            ])
        for item_o_item in item_o_list:
            total_value += item_o_item.value
        output = boop(to_format, column_names=headers)
        response = discord.Embed(color=0xc16a4f)
        response.set_author(name=f'{target.name}#{target.discriminator}',
                            icon_url=user_avatar(target))
        inv_text = f'Showing items {start_range}-{end_range}.'
        inv_text += f'\nYou have {total_inv}/{inv_limit} items in your inventory.'
        inv_text += f'\nTotal value of your inventory is {total_value} {cmd.bot.cfg.pref.currency}.'
        response.add_field(name='📦 Inventory Stats',
                           value=f'```py\n{inv_text}\n```')
        response.add_field(name=f'📋 Items Currently On Page {page_number}',
                           value=f'```hs\n{output}\n```',
                           inline=False)
    else:
        response = discord.Embed(color=0xc6e4b5, title='💸 Totally empty...')
    await message.channel.send(embed=response)
Beispiel #20
0
 def load_all_modules(self):
     self.alts = {}
     self.commands = {}
     self.events = {}
     directory = 'sigma/modules'
     for root, dirs, files in os.walk(directory):
         for file in files:
             if file == 'module.yml':
                 file_path = (os.path.join(root, file))
                 with open(file_path, encoding='utf-8') as plugin_file:
                     plugin_data = yaml.safe_load(plugin_file)
                     if plugin_data['enabled']:
                         if self.init:
                             self.log.info(
                                 f'Loading the {plugin_data["name"]} Module'
                             )
                         if 'commands' in plugin_data:
                             if plugin_data[
                                     'category'] not in self.categories:
                                 self.categories.append(
                                     plugin_data['category'])
                             for command_data in plugin_data['commands']:
                                 if self.bot.cfg.pref.music_only:
                                     if plugin_data['category'] == 'music':
                                         add_cmd = True
                                     else:
                                         add_cmd = False
                                 elif self.bot.cfg.pref.text_only:
                                     if plugin_data['category'] != 'music':
                                         add_cmd = True
                                     else:
                                         add_cmd = False
                                 else:
                                     add_cmd = True
                                 if add_cmd:
                                     if command_data['enabled']:
                                         module_root_location = os.path.join(
                                             root)
                                         command_module_location = os.path.join(
                                             root, command_data["name"])
                                         command_module_location = command_module_location.replace(
                                             '/', '.')
                                         command_module_location = command_module_location.replace(
                                             '\\', '.')
                                         command_function = importlib.import_module(
                                             command_module_location)
                                         importlib.reload(command_function)
                                         command_data.update(
                                             {'path': module_root_location})
                                         cmd = SigmaCommand(
                                             self.bot, command_function,
                                             plugin_data, command_data)
                                         if cmd.alts:
                                             for alt in cmd.alts:
                                                 self.alts.update(
                                                     {alt: cmd.name})
                                         self.commands.update(
                                             {command_data['name']: cmd})
                         if self.bot.cfg.dsc.bot:
                             if not self.bot.cfg.pref.music_only:
                                 if 'events' in plugin_data:
                                     for event_data in plugin_data[
                                             'events']:
                                         if event_data['enabled']:
                                             command_module_location = os.path.join(
                                                 root, event_data["name"])
                                             command_module_location = command_module_location.replace(
                                                 '/', '.')
                                             command_module_location = command_module_location.replace(
                                                 '\\', '.')
                                             event_function = importlib.import_module(
                                                 command_module_location)
                                             importlib.reload(
                                                 event_function)
                                             event = SigmaEvent(
                                                 self.bot, event_function,
                                                 plugin_data, event_data)
                                             if event.event_type in self.events:
                                                 event_list = self.events[
                                                     event.event_type]
                                             else:
                                                 event_list = []
                                             event_list.append(event)
                                             self.events.update({
                                                 event.event_type:
                                                 event_list
                                             })
Beispiel #21
0
async def forage(cmd: SigmaCommand, message: discord.Message, args: list):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if not await cmd.bot.cool_down.on_cooldown(cmd.name, message.author):
        upgrade_file = await cmd.db[cmd.db.db_cfg.database].Upgrades.find_one(
            {'UserID': message.author.id})
        if upgrade_file is None:
            await cmd.db[cmd.db.db_cfg.database
                         ].Upgrades.insert_one({'UserID': message.author.id})
            upgrade_file = {}
        inv = await cmd.db.get_inventory(message.author)
        if 'storage' in upgrade_file:
            storage = upgrade_file['storage']
        else:
            storage = 0
        inv_limit = 64 + (8 * storage)
        if len(inv) < inv_limit:
            base_cooldown = 60
            if 'stamina' in upgrade_file:
                stamina = upgrade_file['stamina']
            else:
                stamina = 0
            cooldown = int(base_cooldown - ((base_cooldown / 100) *
                                            ((stamina * 0.5) /
                                             (1.25 + (0.01 * stamina)))))
            if cooldown < 12:
                cooldown = 12
            await cmd.bot.cool_down.set_cooldown(cmd.name, message.author,
                                                 cooldown)
            rarity = await item_core.roll_rarity(cmd.db, message.author.id)
            if args:
                if message.author.id in cmd.bot.cfg.dsc.owners:
                    try:
                        if int(args[0]) <= 9:
                            rarity = int(args[0])
                        else:
                            pass
                    except TypeError:
                        pass
            item = item_core.pick_item_in_rarity('plant', rarity)
            connector = 'a'
            if item.rarity_name[0].lower() in ['a', 'e', 'i', 'o', 'u']:
                connector = 'an'
            if rarity == 0:
                if item.name[0].lower() in ['a', 'e', 'i', 'o', 'u']:
                    connector = 'an'
                response_title = f'{item.icon} You found {connector} {item.name} and threw it away!'
            else:
                response_title = f'{item.icon} You found {connector} {item.rarity_name} {item.name}!'
                data_for_inv = item.generate_inventory_item()
                await cmd.db.add_to_inventory(message.author, data_for_inv)
                await item_core.add_item_statistic(cmd.db, item,
                                                   message.author)
            response = discord.Embed(color=item.color, title=response_title)
            response.set_author(name=message.author.display_name,
                                icon_url=user_avatar(message.author))
        else:
            response = discord.Embed(color=0xBE1931,
                                     title=f'❗ Your inventory is full.')
    else:
        timeout = await cmd.bot.cool_down.get_cooldown(cmd.name,
                                                       message.author)
        response = discord.Embed(
            color=0x696969,
            title=f'🕙 You are resting for another {timeout} seconds.')
    await message.channel.send(embed=response)
Beispiel #22
0
async def quiz(cmd: SigmaCommand, message: discord.Message, args: list):
    # exit if quiz is already active in the channel
    if message.channel.id in active_quizzes:
        return

    # load quizzes from the resources
    quizzes = []
    for root, dirs, files in os.walk(cmd.resource('')):
        index = 1
        for file in files:
            if file.endswith('.yml'):
                file_path = (os.path.join(root, file))
                with open(file_path, encoding='utf-8') as quiz_file:
                    data = yaml.safe_load(quiz_file)
                    data.update({'index': index})
                    quizzes.append(data)
                    index += 1
    # respond with a list of available quizzes
    response_body = ''
    for quiz_item in quizzes:
        response_body += f"`#{quiz_item['index']}.` {quiz_item['quiz']}"
    response = discord.Embed(color=message.guild.me.color, title='Pick a quiz', description=response_body)
    quiz_list = await message.channel.send(embed=response)

    def check_value(msg):
        # check if the message is an integer
        try:
            int(msg.content)
            return True
        except ValueError:
            return False

    # wait for user response
    response = discord.Embed(color=message.guild.me.color)  # response for user response
    try:
        index = await cmd.bot.wait_for('message', check=check_value, timeout=5)
        active_quizzes[message.channel.id] = True
        await quiz_list.delete()  # delete the quiz list
        await index.delete()  # delete the user response
        index = index.content
        queue = []
        # look for the chosen index in the data
        for quiz_item in quizzes:
            if str(quiz_item['index']) == str(index):
                # grab 10 random items
                while len(queue) != 2:
                    addition = quiz_item['questions'].pop(secrets.randbelow(len(quiz_item['questions'])))
                    queue.append(addition)
        if not queue:
            response.title = 'Selected quiz was not found'
            await message.channel.send(embed=response)
        else:
            # start the quiz
            unanswered = []
            scores = {}
            for item in queue:
                response = discord.Embed(color=message.guild.me.color, title=quiz_item['quiz'])
                response.description = quiz_item['question_template']
                response.description = response.description.replace('${question}', 'or '.join(item['questions']))
                await message.channel.send(embed=response)
                # awaiting for the user answer
                response = discord.Embed(color=message.guild.me.color, title=quiz_item['quiz'])
                try:
                    def check_answer(msg):
                        if msg.content in item['answers']:
                            out = True
                        else:
                            out = False
                        return out

                    answer = await cmd.bot.wait_for('message', check=check_answer, timeout=12)
                    await answer.delete()
                    response = discord.Embed(color=0x00FF00, title=quiz_item['quiz'])
                    desc_text = f"Correct answer by {answer.author.mention}!"
                    desc_text += f" The answer was {'or '.join(item['answers'])}"
                    response.description = desc_text
                    await message.channel.send(embed=response)
                    try:
                        scores[answer.author.id] += 1
                    except KeyError:
                        scores[answer.author.id] = 1
                except asyncio.TimeoutError:
                    response = discord.Embed(color=0xFF0000, title=quiz_item['quiz'])
                    response.description = f"Correct answer was {'or '.join(item['answers'])}"
                    await message.channel.send(embed=response)
                    unanswered.append(item)
            summary = discord.Embed(color=message.guild.me.color, title='Quiz end')
            summary_body = '**Final scores**\n'
            for uid in scores:
                summary_body += f"<@{uid}> - {scores[uid]} point(s) \n"
            if unanswered:
                summary_body += '\n**Unanswered questions**\n'
                for item in unanswered:
                    summary_body += f"{', '.join(item['questions'])} ({', '.join(item['answers'])})\n"
            summary.description = summary_body
            await message.channel.send(embed=summary)
            del active_quizzes[message.channel.id]
    except asyncio.TimeoutError:
        response.title = 'Timed out, please use the command again to pick a quiz'
        await message.channel.send(embed=response)