Ejemplo n.º 1
0
async def liststatuses(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    status_data = await cmd.db[cmd.db.db_nam].StatusFiles.find({}
                                                               ).to_list(None)
    if status_data:
        status_list = [[s['id'], s['text']] for s in status_data]
        status_list = sorted(status_list, key=lambda x: x[1])
        total_status = len(status_list)
        page = pld.args[0] if pld.args else 1
        status_list, page = PaginatorCore.paginate(status_list, page)
        status_block = boop(status_list, ['ID', 'Text'])
        response = discord.Embed(
            color=await get_image_colors(user_avatar(cmd.bot.user)))
        response.set_author(
            name=f'{cmd.bot.user.name}\'s Status Rotation Items',
            icon_url=user_avatar(cmd.bot.user))
        info = f'Showing {len(status_list)} items out of {total_status} on page {page}.'
        response.add_field(name='Info', value=f'```py\n{info}\n```')
        response.add_field(name="List",
                           value=f'```\n{status_block}\n```',
                           inline=False)
    else:
        response = GenericResponse('No statuses found.').not_found()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 2
0
async def commandstatistics(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        single = True
        cmd_name = pld.args[0].lower()
        if cmd_name in cmd.bot.modules.alts:
            cmd_name = cmd.bot.modules.alts[cmd_name]
        cmd_stats = await cmd.db[cmd.db.db_nam].CommandStats.find_one({'command': cmd_name})
        stat_list, page = [cmd_stats] if cmd_stats else None, None
    else:
        single = False
        all_stats = await cmd.db[cmd.db.db_nam].CommandStats.find({}).to_list(None)
        all_stats = [asi for asi in all_stats if asi.get('command') in cmd.bot.modules.commands]
        stat_list = sorted(all_stats, key=lambda k: k.get('count'), reverse=True)
        stat_list, page = PaginatorCore.paginate(stat_list, pld.args[0] if pld.args else 1, 15)
    if stat_list:
        out_list = [[sli.get('command').upper(), str(sli.get('count', 0))] for sli in stat_list]
        out_table = boop(out_list, ['Command', 'Count'])
        out_table = f'```hs\n{out_table}\n```'
        if single:
            response = discord.Embed(color=0xf, title='📟 **Command Statistics**', description=out_table)
            await pld.msg.channel.send(embed=response)
        else:
            response = f'📟 **Command Statistics**: Page {page}\n{out_table}'
            await pld.msg.channel.send(response)
    else:
        response = GenericResponse('No statistics to show.').not_found()
        await pld.msg.channel.send(embed=response)
Ejemplo n.º 3
0
async def ingame(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    response = discord.Embed(color=0x1ABC9C)
    games, online, playing = make_games_dict(pld.msg.guild)
    sorted_games = sorted(games.items(), key=operator.itemgetter(1), reverse=True)
    page = pld.args[0] if pld.args else 1
    game_list, page = PaginatorCore.paginate(sorted_games, page)
    start_range = (page - 1) * 10
    out_table_list = []
    game_count = len(sorted_games)
    index = start_range
    for key, value in game_list:
        index += 1
        if len(key) > 32:
            key = key[:32] + '...'
        out_table_list.append([str(index), key, value, str(value / playing * 100).split('.')[0] + '%'])
    output = boop(out_table_list)
    general_stats_list = [['Online', online], ['In-Game', playing], ['Unique Games', game_count]]
    out_block = f'```hs\n{boop(general_stats_list)}\n```'
    response.add_field(name='👾 Current Gaming Statistics on ' + pld.msg.guild.name, value=out_block, inline=False)
    response.add_field(name=f'🎮 By Game on Page {page}', value=f'```haskell\n{output}\n```', inline=False)
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 4
0
async def listemoterolegroups(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    emote_groups = pld.settings.get('emote_role_groups') or {}
    if emote_groups:
        group_list = list(emote_groups.keys())
        group_count = len(group_list)
        page = pld.args[0] if pld.args else 1
        group_list, page = PaginatorCore.paginate(group_list, page)
        ender = 's' if group_count > 1 else ''
        summary = f'Showing **{len(group_list)}** group{ender} from Page **#{page}**.'
        summary += f'\n{pld.msg.guild.name} has **{group_count}** emote role group{ender}.'
        rl_out = ''
        group_list = sorted(group_list)
        for rl in group_list:
            rl_out += f'\n`{rl}`: {len(list(emote_groups.get(rl)))} Roles'
        guild_icon = str(pld.msg.guild.icon_url) if pld.msg.guild.icon_url else discord.Embed.Empty
        response = discord.Embed(color=await get_image_colors(guild_icon))
        response.set_author(name=pld.msg.guild.name, icon_url=guild_icon)
        response.add_field(name='Emote Role Group Summary', value=summary, inline=False)
        response.add_field(name='List of Emote Role Groups', value=f'{rl_out}', inline=False)
        response.set_footer(text=f'You can see all roles in a group using the {cmd.bot.cfg.pref.prefix}verg command.')
    else:
        response = GenericResponse(f'{pld.msg.guild.name} has no emote role groups.').not_found()
    await pld.msg.channel.send(embed=response)
async def warmachinelist(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    target = pld.msg.mentions[0] if pld.msg.mentions else pld.msg.author
    machines = await SigmaMachine.get_machines(cmd.db, target)
    machines_owned = len(machines)
    machines, page = PaginatorCore.paginate(machines,
                                            pld.args[0] if pld.args else 1, 5)
    if machines:
        out_list = '\n'.join([f'`{m.id}`: **{m.name}**' for m in machines])
        response = discord.Embed(color=0x8899a6)
        response.set_author(name=f'{target.name}\'s Warmachines',
                            icon_url=user_avatar(target))
        response.add_field(name='List', value=out_list, inline=False)
        response.set_footer(
            text=
            f'[Page {page}] Showing {len(machines)}/{machines_owned} machines owned.'
        )
    else:
        response = error('You don\'t own any machine.')
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 6
0
async def viewlists(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    lookup_data = {'server_id': pld.msg.guild.id}
    list_coll = cmd.db[cmd.db.db_nam].CustomLists
    list_files = await list_coll.find(lookup_data).to_list(None)
    if list_files:
        list_lines = []
        for list_file in list_files:
            author_id = list_file.get('user_id')
            author = await cmd.bot.get_user(author_id)
            list_name = list_file.get('name')
            creator = f'{author.name}#{author.discriminator}' if author else author_id
            mode, icon = list_file.get('mode'), ''
            if mode in ['private', 'locked']:
                icon = '⛔' if mode == 'private' else '🔏'
            list_line = f'`{list_file.get("list_id")}` - {list_name} - {creator} `{icon}`'
            list_lines.append(list_line)
        page = pld.args[0] if pld.args else 1
        list_lines, page = PaginatorCore.paginate(list_lines, page)
        response = discord.Embed(color=0xF9F9F9,
                                 title=f':books: Custom Lists | Page {page}')
        list_list = '\n'.join(list_lines)
        response.description = list_list
    else:
        response = GenericResponse(
            'There are no lists on this server.').not_found()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 7
0
async def wfsales(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    sales = await WorldState().flashsales
    if sales:
        discount_only, title = get_mode(pld.args)
        sales_data_all = get_items(sales, discount_only)
        total_item = len(sales_data_all)
        page = pld.args[-1] if pld.args else 1
        sales_data, page = PaginatorCore.paginate(sales_data_all, page)
        start_range, end_range = (page - 1) * 10, page * 10
        no_discounts = True
        for item in sales_data:
            if item['discount'] != 0:
                no_discounts = False
                break
        headers = ['Name', 'Platinum']
        if not no_discounts:
            headers.append('Discount')
        if sales_data:
            total_plat = sum([x['premiumOverride'] for x in sales_data_all])
            sales_data = sorted(sales_data, key=lambda x: x['item'])
            stat_block = f'Showing items {start_range}-{end_range}. Page {page}'
            stat_block += f'\nThere are {total_item} items valued at {total_plat} platinum.'
            item_list = []
            for sale_item in sales_data:
                if no_discounts:
                    item_list.append([
                        sale_item.get('item'),
                        sale_item.get('premiumOverride')
                    ])
                else:
                    item_list.append([
                        sale_item.get('item'),
                        sale_item.get('premiumOverride'),
                        f"-{sale_item.get('discount')}%"
                    ])
            item_table = boop(item_list, headers)
            response = discord.Embed(color=0x336699)
            response.set_author(name='Warframe Promotions',
                                icon_url=warframe_icon)
            response.add_field(name='Details',
                               value=f'```py\n{stat_block}\n```',
                               inline=False)
            response.add_field(name=title,
                               value=f'```hs\n{item_table}\n```',
                               inline=False)
        else:
            response = discord.Embed(color=0x336699)
            response.set_author(
                name='No items found, try adding the "all" argument.',
                icon_url=warframe_icon)
    else:
        response = error('Could not retrieve Sales data.')
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 8
0
async def allitems(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    reci_core = await get_recipe_core(cmd.db)
    item_core = await get_item_core(cmd.db)
    item_o_list = item_core.all_items
    special = False
    if pld.args:
        types = ['animals', 'animal', 'plants', 'plant', 'fish']
        selection = pld.args[0].lower()
        if selection in types:
            sort = selection[:-1] if selection.endswith('s') else selection
            item_o_list = [
                i for i in item_core.all_items if i.type == sort.title()
            ]
            special = True
    item_o_list = sorted(item_o_list, key=attrgetter('value'), reverse=True)
    item_o_list = sorted(item_o_list, key=attrgetter('name'), reverse=False)
    item_o_list = sorted(item_o_list, key=attrgetter('rarity'), reverse=True)
    item_o_list = deduplicate(item_o_list)
    if special:
        page = pld.args[1] if len(pld.args) > 1 else 1
    else:
        page = pld.args[0] if pld.args else 1
    inv, page = PaginatorCore.paginate(item_o_list, page)
    start_range, end_range = (page - 1) * 10, page * 10
    if inv:
        all_reci = reci_core.recipes
        headers = ['Type', 'Name', 'Value', 'Rarity']
        to_format = []
        total_value = 0
        for item_o_item in inv:
            in_rec = '*' if is_ingredient(all_reci, item_o_item) else ''
            to_format.append([
                item_o_item.type, f'{item_o_item.name}{in_rec}',
                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'{cmd.bot.user.name}',
                            icon_url=user_avatar(cmd.bot.user))
        inv_text = f'Showing items {start_range}-{end_range} out of {len(item_o_list)}.'
        inv_text += f'\nThe total value of this pool is {total_value} {cmd.bot.cfg.pref.currency}.'
        response.add_field(name='📦 Item Pool Stats',
                           value=f'```py\n{inv_text}\n```')
        response.add_field(name=f'📋 Items Currently On Page {page}',
                           value=f'```hs\n{output}\n```',
                           inline=False)
    else:
        response = GenericResponse(
            'Could not retrieve Item Core data.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 9
0
async def listinactivewarnings(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.msg.author == pld.msg.guild.owner:
        target = pld.msg.mentions[0] if pld.msg.mentions else pld.msg.author
        if target:
            lookup = {
                'guild': pld.msg.guild.id,
                'target.id': target.id,
                'warning.active': False
            }
            warnings = await cmd.db[cmd.db.db_nam
                                    ].Warnings.find(lookup).to_list(None)
            if warnings:
                warn_list = []
                for warning in warnings:
                    warn_id = warning.get('warning').get('id')
                    moderator = await cmd.bot.get_user(
                        warning.get('moderator').get('id'))
                    if moderator:
                        moderator = moderator.name
                    else:
                        moderator = warning.get('moderator').get('name')
                    warn_time = arrow.get(
                        warning.get('warning').get('timestamp')).format(
                            'DD. MMM. YYYY. HH:mm')
                    warn_list.append(
                        f'`{warn_id}` by **{moderator}** on {warn_time}.')
                page = pld.args[1] if len(pld.args) > 1 else 1
                warn_list, page = PaginatorCore.paginate(warn_list, page, 5)
                start_range, end_range = (page - 1) * 5, page * 5
                warn_list = '\n'.join(warn_list)
                ender = 's' if len(warnings) > 1 else ''
                start = f'{target.name} has' if target.id != pld.msg.author.id else 'You have'
                response = discord.Embed(color=0xFFCC4D)
                response.add_field(
                    name=
                    f'âš  {start} {len(warnings)} inactive warning{ender}.',
                    value=warn_list)
                response.set_footer(
                    text=
                    f'Showing warns {start_range}-{end_range} out of {len(warnings)}.'
                )
            else:
                start = f'{target.name} doesn\'t' if target.id != pld.msg.author.id else 'You don\'t'
                response = discord.Embed(
                    color=0x55acee,
                    title=f'💠 {start} have any inactive warnings.')
        else:
            response = GenericResponse('No user targeted.').error()
    else:
        response = GenericResponse(
            'Access Denied. Server Owner needed.').denied()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 10
0
async def inventory(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    reci_core = await get_recipe_core(cmd.db)
    item_core = await get_item_core(cmd.db)
    target = pld.msg.mentions[0] if pld.msg.mentions else pld.msg.author
    upgrade_file = await cmd.db.get_profile(target.id, 'upgrades') or {}
    storage = upgrade_file.get('storage', 0)
    inv_limit = 64 + (8 * storage)
    inv = await cmd.db.get_inventory(target.id)
    total_inv = len(inv)
    item_o_list = []
    item_filter = get_filter(pld.args)
    for item in inv:
        item_o = item_core.get_item_by_file_id(item['item_file_id'])
        add = item_belongs(item_filter, item_o) if item_filter else True
        if add:
            item_o_list.append(item_o)
    item_o_list = sorted(item_o_list, key=attrgetter('value'), reverse=True)
    item_o_list = sorted(item_o_list, key=attrgetter('name'), reverse=False)
    item_o_list = sorted(item_o_list, key=attrgetter('rarity'), reverse=True)
    inv, page = PaginatorCore.paginate(item_o_list, get_page_number(pld.args))
    start_range, end_range = (page - 1) * 10, page * 10
    if inv:
        all_reci = reci_core.recipes
        headers = ['Type', 'Name', 'Value', 'Rarity']
        to_format = []
        total_value = 0
        for item_o_item in inv:
            in_rec = '*' if is_ingredient(all_reci, item_o_item) else ''
            to_format.append([
                item_o_item.type, f'{item_o_item.name}{in_rec}',
                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)
        inv_text = f'Showing items {start_range}-{end_range}.'
        pronouns = ['You', 'your'
                    ] if target.id == pld.msg.author.id else ['They', 'their']
        inv_text += f'\n{pronouns[0]} have {total_inv}/{inv_limit} items in {pronouns[1]} inventory.'
        inv_text += f'\nTotal value of {pronouns[1]} 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}',
                           value=f'```hs\n{output}\n```',
                           inline=False)
    else:
        title = '🔍 No items matching that filter.' if item_filter else '💸 Totally empty...'
        response = discord.Embed(color=0xc6e4b5, title=title)
    response.set_author(name=f'{target.name}#{target.discriminator}',
                        icon_url=user_avatar(target))
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 11
0
async def permitted(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        if len(pld.args) >= 2:
            if ':' in pld.args[1]:
                target_type = get_target_type(pld.args[0].lower())
                if target_type:
                    perm_mode = pld.args[1].split(':')[0]
                    node_name = pld.args[1].split(':')[1]
                    modes = {
                        'c': ('Command', 'command_exceptions', cmd.bot.modules.commands, True),
                        'm': ('Module', 'module_exceptions', cmd.bot.modules.categories, False)
                    }
                    perms = await get_all_perms(cmd.db, pld.msg)
                    mode_vars = modes.get(perm_mode)
                    if mode_vars:
                        mode_name, exception_group, check_group, check_alts = mode_vars
                        if check_alts:
                            if node_name in cmd.bot.modules.alts:
                                node_name = cmd.bot.modules.alts[node_name]
                        if node_name in check_group:
                            exceptions = perms.get(exception_group, {}).get(node_name, {}).get(target_type, [])
                            overridden_items = get_exceptions(pld.msg, exceptions, target_type)
                            guild_icon = str(pld.msg.guild.icon_url) if pld.msg.guild.icon_url else discord.Embed.Empty
                            if overridden_items:
                                total_overrides = len(overridden_items)
                                page = pld.args[2] if len(pld.args) > 2 else 1
                                overrides, page = PaginatorCore.paginate(overridden_items, page, 50)
                                title = f'{pld.msg.guild.name} {node_name.upper()} {target_type[:-1].title()} Overrides'
                                info = f'[Page {page}] Showing {len(overrides)} '
                                info += f'out of {total_overrides} channel overrides.'
                                response = discord.Embed(color=await get_image_colors(guild_icon))
                                response.set_author(name=title, icon_url=guild_icon)
                                response.description = ', '.join(overrides)
                                response.set_footer(text=info)
                            else:
                                title = f'🔍 No {target_type[:-1]} overrides found for {node_name}.'
                                response = discord.Embed(color=0x696969, title=title)
                        else:
                            mmn = mode_name.lower()
                            response = not_found(f'No {node_name} {mmn} found.')
                    else:
                        response = error('Unrecognized lookup mode, see usage example.')
                else:
                    response = error('Invalid target type.')
            else:
                response = error('Separate permission type and name with a colon.')
        else:
            response = error('Not enough arguments.')
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response)
 def test_page(self):
     assert PaginatorCore.paginate([], 0) == ([], 1)
     assert PaginatorCore.paginate([], 1) == ([], 1)
     assert PaginatorCore.paginate([], 2) == ([], 1)
     assert PaginatorCore.paginate([], "0") == ([], 1)
     assert PaginatorCore.paginate([], "1") == ([], 1)
     assert PaginatorCore.paginate([], "2") == ([], 1)
     assert PaginatorCore.paginate([], None) == ([], 1)
Ejemplo n.º 13
0
async def whoplays(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        if pld.args[0].isdigit():
            game_title = ' '.join(pld.args[1:])
            page = True
        else:
            game_title = ' '.join(pld.args)
            page = False
        game_name = None
        gamer_list = []
        playing, total = 0, 0
        for member in pld.msg.guild.members:
            if not member.activities:
                continue
            activity = member.activities[-1]
            is_custom = isinstance(activity, discord.CustomActivity)
            is_spotify = isinstance(activity, discord.Spotify)
            if is_custom or is_spotify:
                continue
            total += 1
            if activity.name.lower() == game_title.lower():
                if not game_name:
                    game_name = activity.name
                member_name = member.name
                for escapable in '*_~`':
                    member_name = member_name.replace(escapable,
                                                      f'\\{escapable}')
                gamer_list.append(member_name)
                playing += 1
        title = f'{playing}/{total} people are playing {game_name}'
        if gamer_list:
            total_gamers = len(gamer_list)
            page = pld.args[0] if page else 1
            gamer_list, page = PaginatorCore.paginate(sorted(gamer_list), page,
                                                      20)
            gamers = '- ' + '\n- '.join(gamer_list)
            response = discord.Embed(color=0x1ABC9C)
            response.add_field(name=title, value=gamers)
            response.set_footer(
                text=
                f'[Page {page}] Showing {len(gamer_list)} out of {total_gamers} users.'
            )
        else:
            response = GenericResponse(
                f'No users are currently playing {game_title}.').not_found()
    else:
        response = GenericResponse('Nothing inputted.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 14
0
async def marketlist(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    ic = await get_item_core(cmd.db)
    reci_core = await get_recipe_core(cmd.db)
    await check_expiry(cmd.db)
    lookup = get_filter(pld.args)
    entries = []
    title = None
    if lookup:
        item = ic.get_item_by_name(lookup)
        if item:
            title = f'Cheapest {item.rarity_name} {item.name} listings.'
            sort = ('price', -1)
            entries = await MarketEntry.find_all_items(cmd.db,
                                                       item.file_id,
                                                       sort=sort)
    else:
        title = 'Most recent listings.'
        sort = ('stamp', -1)
        entries = await MarketEntry.find_all(cmd.db, sort=sort)
    if entries:
        total_count = len(entries)
        entries, page = PaginatorCore.paginate(entries,
                                               get_page_number(pld.args))
        start_range, end_range = (page - 1) * 10, page * 10
        headers = ['Type', 'Name', 'Price', 'Rarity']
        to_format = []
        for entry in entries:
            item = ic.get_item_by_file_id(entry.item)
            in_rec = '*' if is_ingredient(reci_core.recipes, item) else ''
            to_format.append([
                item.type, f'{item.name}{in_rec}', f'{entry.price}',
                f'{item.rarity_name.title()}'
            ])
        output = boop(to_format, column_names=headers)
        response = discord.Embed(color=0x4289c1)
        inv_text = f'Showing items {start_range}-{end_range}.'
        inv_text += f'\nThere are {total_count} items on the open market.'
        response.add_field(name=f'💶 {title}',
                           value=f'```py\n{inv_text}\n```')
        response.add_field(name=f'📋 Items Currently On Page {page}',
                           value=f'```hs\n{output}\n```',
                           inline=False)
    else:
        response = GenericResponse(
            'I couldn\'t find anything with that name.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 15
0
def parse_incidents(incidents, page):
    """
    :type incidents: list
    :type page: int
    :rtype: str
    """
    incidents = sorted(incidents, key=lambda i: i.order)
    incidents, page = PaginatorCore.paginate(incidents, page, 10)
    outlist = []
    for inc in incidents:
        timestamp = arrow.get(inc.timestamp).format('DD. MMM. YYYY. HH:mm')
        details = f'**#{inc.order}** `{inc.id}` - {inc.variant} incident for **{inc.target.name}** on {timestamp}'
        outlist.append(details)
    return '\n'.join(outlist), page
Ejemplo n.º 16
0
async def disabled(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        perm_name, perm_type, exception_type, item_list = get_perm_type(
            cmd, pld.args[0].lower())
        if perm_name:
            perms = await get_all_perms(cmd.db, pld.msg)
            disabled_items = perms[perm_type]
            overridden_items = perms[exception_type]
            disabled_list = []
            for item_name in disabled_items:
                if item_name in item_list:
                    if item_name in overridden_items:
                        exc = overridden_items.get(item_name)
                        exc_exists = any([
                            exc.get('users'),
                            exc.get('channels'),
                            exc.get('roles')
                        ])
                        if exc_exists:
                            item_name += r'\*'
                    disabled_list.append(item_name)
            if disabled_list:
                disabled_count = len(disabled_list)
                page = pld.args[1] if len(pld.args) > 1 else 1
                disabled_list, page_num = PaginatorCore.paginate(
                    disabled_list, page, 50)
                title = f'{pld.msg.guild.name} Disabled {perm_name.title()}'
                info = f'[Page {page_num}] Showing {len(disabled_list)} out of {disabled_count} disabled {perm_name}.'
                guild_icon = str(
                    pld.msg.guild.icon_url
                ) if pld.msg.guild.icon_url else discord.Embed.Empty
                response = discord.Embed(
                    color=await get_image_colors(guild_icon))
                response.set_author(name=title, icon_url=guild_icon)
                response.description = ', '.join(disabled_list)
                response.set_footer(text=info)
            else:
                response = GenericResponse(
                    f'No disabled {perm_name} found.').not_found()
        else:
            response = GenericResponse('Invalid permission type.').error()
    else:
        response = GenericResponse('Nothing inputted.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 17
0
async def recipes(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    craftable, recipe_type = get_filter(pld.args)
    recipe_core = await get_recipe_core(cmd.db)
    recipe_list = sorted(recipe_core.recipes, key=lambda x: x.name)
    recipe_list = sorted(recipe_list, key=lambda x: x.value, reverse=True)
    target_recipes = []
    user_inv = await cmd.db.get_inventory(pld.msg.author.id)
    for recipe in recipe_list:
        req_satisfied = await check_requirements(user_inv, recipe)
        req_needed = len(recipe.ingredients)
        req_reqs = f'{req_satisfied}/{req_needed}'
        in_rec = '*' if is_ingredient(recipe_core.recipes, recipe) else ''
        if recipe.type.lower() == recipe_type or recipe_type is None:

            if craftable:
                if req_satisfied == req_needed:
                    target_recipes.append([
                        recipe.type, f'{recipe.name}{in_rec}', recipe.value,
                        req_reqs
                    ])
            else:
                target_recipes.append([
                    recipe.type, f'{recipe.name}{in_rec}', recipe.value,
                    req_reqs
                ])
    page = pld.args[0] if pld.args else 1
    sales_data, page = PaginatorCore.paginate(target_recipes, page)
    start_range, end_range = (page - 1) * 10, page * 10
    recipe_icon, recipe_color = choose_recipe(recipe_core, recipe_type)
    if sales_data:
        recipe_boop_head = ['Type', 'Name', 'Value', 'Ingr.']
        recipe_table = boop(sales_data, recipe_boop_head)
        response = discord.Embed(color=recipe_color)
        stats_text = f'Showing recipes: {start_range}-{end_range}.'
        stats_text += f'\nThere are a total of {len(recipe_core.recipes)} recipes.'
        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}',
                           value=f'```hs\n{recipe_table}\n```')
    else:
        response = GenericResponse(
            'No recipes match the given filter.').not_found()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 18
0
async def spouses(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    target = pld.msg.mentions[0] if pld.msg.mentions else pld.msg.author
    profile = await cmd.db[cmd.db.db_nam].Profiles.find_one(
        {'user_id': target.id}) or {}
    splist = profile.get('spouses', [])
    splist = list(sorted(splist, key=lambda x: x.get('time')))
    spcount = len(splist)
    page = pld.args[0] if pld.args else 1
    splist, page = PaginatorCore.paginate(splist, page, 5)
    starter = 'You are' if target.id == pld.msg.author.id else f'{target.name} is'
    mid = 'have' if target.id == pld.msg.author.id else 'has'
    ids_only = pld.args[-1].lower() == '--ids' if pld.args else False
    if splist:
        spdata = []
        for sp in splist:
            spmemb = await cmd.bot.get_user(sp.get('user_id'))
            spmemb = (spmemb.name if spmemb else
                      sp.get('user_id')) if not ids_only else sp.get('user_id')
            sp_profile = await cmd.db[cmd.db.db_nam].Profiles.find_one(
                {'user_id': sp.get('user_id')}) or {}
            sp_spouses = sp_profile.get('spouses') or []
            sp_spouse_ids = [s.get('user_id') for s in sp_spouses]
            if target.id in sp_spouse_ids:
                spdata.append(
                    [spmemb, humanize_time(arrow.get(sp.get('time')))])
        spbody = boop(spdata, ['Name', 'Since'])
        upgrades = await cmd.db.get_profile(target.id, 'upgrades') or {}
        limit = 10 + (upgrades.get('harem') or 0)
        stats = f'[Page {page}] {target.name}\'s harem has {spcount}/{limit} people in it.'
        response = discord.Embed(color=0xf9f9f9)
        response.set_author(name=f'{starter} married to...',
                            icon_url=user_avatar(target))
        response.add_field(name='Stats', value=stats, inline=False)
        response.add_field(name='Spouse List', value=f'```hs\n{spbody}\n```')
    else:
        if page == 1:
            response = discord.Embed(
                color=0xe75a70, title=f'💔 {starter} not married to anyone.')
        else:
            response = discord.Embed(
                color=0xe75a70,
                title=f'💔 {starter.split()[0]} {mid} nobody on page {page}.'
            )
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 19
0
async def viewlist(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        lookup_data = {
            'server_id': pld.msg.guild.id,
            'list_id': pld.args[0].lower()
        }
        list_coll = cmd.db[cmd.db.db_nam].CustomLists
        list_file = await list_coll.find_one(lookup_data)
        if list_file:
            author_id = list_file.get('user_id')
            list_name = list_file.get('name')
            if list_file.get('private'):
                if author_id == pld.msg.author.id:
                    auth = True
                else:
                    auth = False
            else:
                auth = True
            if auth:
                list_lines = []
                for i, line in enumerate(list_file.get('contents')):
                    list_lines.append(f'**{i + 1}** {line}')
                page = pld.args[1] if len(pld.args) > 1 else 1
                list_lines, page = PaginatorCore.paginate(list_lines, page, 20)
                list_out = '\n'.join(list_lines)
                mode, icon = list_file.get('mode'), ''
                if mode in ['private', 'locked']:
                    icon = ' ⛔' if mode == 'private' else ' 🔏'
                empty = f'No contents. Add lines with `{cmd.bot.cfg.pref.prefix}addline`.'
                response = discord.Embed(color=0xF9F9F9,
                                         title=f':bookmark_tabs: {list_name}')
                response.description = empty if list_out == '' else list_out
                response.set_footer(
                    text=f'[{list_file.get("list_id")}]{icon} Page {page}')
            else:
                response = denied('This list is private.')
        else:
            response = not_found('List not found.')
    else:
        response = error('Missing list ID.')
    await pld.msg.channel.send(embed=response)
async def blockedextensions(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    blocked_words = pld.settings.get('blocked_extensions')
    if not blocked_words:
        response = info('There are no blocked extensions.')
    else:
        total_count = len(blocked_words)
        blocked_words, page = PaginatorCore.paginate(blocked_words, pld.args[0] if pld.args else 1, 20)
        blocked_words = [f'.{bw}' for bw in blocked_words]
        showing_count = len(blocked_words)
        response = info(f'Extensions blocked on {pld.msg.guild.name}')
        response.description = ' '.join(blocked_words)
        response.set_footer(text=f'[Page {page}] Total: {total_count} | Showing: {showing_count}')
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 21
0
async def inrole(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        try:
            lookup, state, page = parse_args(pld.args)
        except IndexError:
            response = GenericResponse('Bad input. See usage example.').error()
            await pld.msg.channel.send(embed=response)
            return
        if lookup:
            role_search = discord.utils.find(lambda x: x.name.lower() == lookup, pld.msg.guild.roles)
            if role_search:
                members = []
                for member in pld.msg.guild.members:
                    if role_search in member.roles:
                        if state:
                            if member.status.name == state:
                                members.append([member.name, member.top_role.name])
                        else:
                            members.append([member.name, member.top_role.name])
                if members:
                    count = len(members)
                    members, page = PaginatorCore.paginate(sorted(members), page)
                    response = discord.Embed(color=role_search.color)
                    state = state if state else 'Any'
                    value = f'```py\nShowing 10 of {count} users. Status: {state}. Page {page}\n```'
                    members_table = boop(members, ['Name', 'Top Role'])
                    response.add_field(name='📄 Details', value=value, inline=False)
                    response.add_field(name='👥 Members', value=f'```hs\n{members_table}\n```', inline=False)
                else:
                    response = GenericResponse(f'No users have the {role_search.name} role.').not_found()
            else:
                response = GenericResponse(f'{lookup} not found.').not_found()
        else:
            response = GenericResponse('Missing role name.').error()
    else:
        response = GenericResponse('Nothing inputted.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 22
0
async def customcommands(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    custom_commands = pld.settings.get('custom_commands')
    if custom_commands:
        custom_commands = sorted(list(custom_commands.keys()))
        cmd_count = len(custom_commands)
        page = pld.args[0] if pld.args else 1
        commands, page = PaginatorCore.paginate(custom_commands, page)
        start_range = (page - 1) * 10
        if commands:
            ender = 's' if cmd_count > 1 else ''
            summary = f'Showing **{len(commands)}** command{ender} from Page **#{page}**.'
            summary += f'\n{pld.msg.guild.name} has **{cmd_count}** custom command{ender}.'
            pfx = cmd.db.get_prefix(pld.settings)
            loop_index = start_range
            cmd_list_lines = []
            for key in commands:
                loop_index += 1
                list_line = f'**{loop_index}**: {pfx}{key}'
                cmd_list_lines.append(list_line)
            cmd_list = '\n'.join(cmd_list_lines)
            guild_icon = str(
                pld.msg.guild.icon_url
            ) if pld.msg.guild.icon_url else discord.Embed.Empty
            srv_color = await get_image_colors(guild_icon)
            response = discord.Embed(color=srv_color)
            response.set_author(name='Custom Commands', icon_url=guild_icon)
            response.add_field(name='Summary', value=summary, inline=False)
            response.add_field(name='Command List',
                               value=cmd_list,
                               inline=False)
        else:
            response = GenericResponse('This page is empty.').error()
    else:
        response = GenericResponse(
            'This server has no custom commands.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 23
0
async def reactors(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    reactor_files = pld.settings.get('reactor_triggers')
    if reactor_files:
        reactor_list = sorted(list(reactor_files.keys()))
        reac_count = len(reactor_list)
        page = pld.args[0] if pld.args else 1
        triggers, page = PaginatorCore.paginate(reactor_list, page)
        start_range = (page - 1) * 10
        if triggers:
            ender = 's' if reac_count > 1 else ''
            summary = f'Showing **{len(triggers)}** trigger{ender} from Page **#{page}**.'
            summary += f'\n{pld.msg.guild.name} has **{reac_count}** reactor trigger{ender}.'
            loop_index = start_range
            trg_list_lines = []
            for key in triggers:
                loop_index += 1
                list_line = f'**{loop_index}**: {key.lower()}'
                trg_list_lines.append(list_line)
            trg_list = '\n'.join(trg_list_lines)
            guild_icon = str(
                pld.msg.guild.icon_url
            ) if pld.msg.guild.icon_url else discord.Embed.Empty
            srv_color = await get_image_colors(guild_icon)
            response = discord.Embed(color=srv_color)
            response.set_author(name='Automatic Reaction Triggers',
                                icon_url=guild_icon)
            response.add_field(name='Summary', value=summary, inline=False)
            response.add_field(name='Trigger List',
                               value=trg_list,
                               inline=False)
        else:
            response = GenericResponse('This page is empty.').error()
    else:
        response = GenericResponse(
            'This server has no reaction triggers.').error()
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 24
0
async def whoplays(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    if pld.args:
        if pld.args[0].isdigit():
            game_title = ' '.join(pld.args[1:])
            page = True
        else:
            game_title = ' '.join(pld.args)
            page = False
        game_name = None
        gamer_list = []
        x, y = 0, 0
        for member in pld.msg.guild.members:
            activity = member.activities[-1] if member.activities else None
            if activity:
                if isinstance(activity, discord.CustomActivity):
                    continue
                x += 1
                if activity.name.lower() == game_title.lower():
                    if not game_name:
                        game_name = activity.name
                    gamer_list.append(member.name)
                    y += 1
        title = f'{y}/{x} people are playing {game_name}'
        if gamer_list:
            total_gamers = len(gamer_list)
            page = pld.args[0] if page else 1
            gamer_list, page = PaginatorCore.paginate(sorted(gamer_list), page, 20)
            gamers = '\n- ' + '\n- '.join(gamer_list)
            response = discord.Embed(color=0x1ABC9C)
            response.add_field(name=title, value=gamers)
            response.set_footer(text=f'[Page {page}] Showing {len(gamer_list)} user out of {total_gamers}.')
        else:
            response = not_found(f'No users are currently playing {game_title}.')
    else:
        response = error('Nothing inputted.')
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 25
0
async def listselfroles(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    self_roles = pld.settings.get('self_roles')
    if self_roles is None:
        self_roles = []
    role_list = []
    for srv_role in pld.msg.guild.roles:
        for role in self_roles:
            if role == srv_role.id:
                role_list.append(srv_role.name)
    if not role_list:
        response = info('No self assignable roles set.')
    else:
        role_count = len(role_list)
        role_list = sorted(role_list)
        page = pld.args[0] if pld.args else 1
        role_list, page = PaginatorCore.paginate(role_list, page)
        ender = 's' if role_count > 1 else ''
        summary = f'Showing **{len(role_list)}** role{ender} from Page **#{page}**.'
        summary += f'\n{pld.msg.guild.name} has **{role_count}** self assignable role{ender}.'
        rl_out = ''
        for role in role_list:
            rl_out += '\n- ' + role
        guild_icon = str(pld.msg.guild.icon_url
                         ) if pld.msg.guild.icon_url else discord.Embed.Empty
        response = discord.Embed(color=await get_image_colors(guild_icon))
        response.set_author(name=pld.msg.guild.name, icon_url=guild_icon)
        response.add_field(name='Self Assignable Role Stats',
                           value=summary,
                           inline=False)
        response.add_field(name='List of Self Assignable Roles',
                           value=f'{rl_out}',
                           inline=False)
    await pld.msg.channel.send(embed=response)
async def itemstatistics(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    item_core = await get_item_core(cmd.db)
    if pld.msg.mentions:
        target = pld.msg.mentions[0]
    else:
        target = pld.msg.author
    all_stats = await cmd.db[cmd.db.db_nam].ItemStatistics.find_one(
        {'user_id': target.id}) or {}
    if '_id' in all_stats:
        all_stats.pop('_id')
        all_stats.pop('user_id')
    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)
    page = pld.args[0] if pld.args else 1
    all_stats, page = PaginatorCore.paginate(all_stats, page)
    total_count = len([i for i in item_core.all_items if i.rarity != 0])
    listing = []
    for stat in all_stats:
        item_o = item_core.get_item_by_file_id(stat[0])
        if item_o.rarity != 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'[Page {page}] {target.name} has found {mem_count} out of {total_count} items.'
    )
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 27
0
async def hardblockedwords(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    blocked_words = pld.settings.get('hardblocked_words')
    if not blocked_words:
        response = GenericResponse('There are no hard-blocked words.').info()
    else:
        total_count = len(blocked_words)
        blocked_words, page = PaginatorCore.paginate(
            blocked_words, pld.args[0] if pld.args else 1, 20)
        showing_count = len(blocked_words)
        response = GenericResponse(
            f'Words hard-blocked on {pld.msg.guild.name}').info()
        response.description = ', '.join(blocked_words)
        response.set_footer(
            text=
            f'[Page {page}] Total: {total_count} | Showing: {showing_count}')
    await pld.msg.channel.send(embed=response)
Ejemplo n.º 28
0
async def wfvoidtrader(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    trader = await WorldState().voidtraders
    if trader:
        if trader['active']:
            all_items = trader['items'] or []
            ending_time = arrow.get(trader['end'])
            headers = ['Item', 'Ducats', 'Credits']
            item_list = []
            total_items = len(all_items)
            total_ducats = 0
            total_credits = 0
            for item in all_items:
                item_name = item['name']
                item_ducats = item['ducats']
                total_ducats += item_ducats
                item_credits = item['credits']
                total_credits += item_credits
                item_addition = [
                    item_name, str(item_ducats),
                    str(item_credits)
                ]
                item_list.append(item_addition)
            page = pld.args[0] if pld.args else 1
            item_list, page = PaginatorCore.paginate(item_list, page)
            if item_list:
                out_table = boop(item_list, headers)
                stats_desc = f'Page {page} | Location: {trader["location"]}'
                stats_desc += f'\nItems: {total_items} | Ducats: {total_ducats} | Credits: {total_credits}'
                end_human = ending_time.humanize()
                leaves = f'Trader leaves {end_human}'
                response = discord.Embed(color=0x006666,
                                         timestamp=ending_time.datetime)
                response.set_author(name='Warframe Void Trader',
                                    icon_url=baro_icon)
                response.add_field(name='Total Statistics',
                                   value=stats_desc,
                                   inline=False)
                response.add_field(name='Items For Sale',
                                   value=f'```bat\n{out_table}\n```',
                                   inline=False)
                response.set_footer(text=leaves)
            else:
                response = discord.Embed(color=0x006666)
                response.set_author(name='No items on this page.',
                                    icon_url=baro_icon)
        else:
            start_time = arrow.get(trader['start'])
            offset = start_time.int_timestamp - arrow.get().int_timestamp
            if offset < 86400:
                arrival_time = str(datetime.timedelta(seconds=offset))
            else:
                arrival_time = start_time.humanize()
            response = discord.Embed(color=0x006666)
            response.set_author(
                name=
                f'Void Trader arrives {arrival_time} on {trader["location"]}.',
                icon_url=baro_icon)
    else:
        response = GenericResponse(
            'Could not retrieve Void Trader data.').error()
    await pld.msg.channel.send(embed=response)
 def test_page_size(self):
     nums = list(range(1, 16))
     assert PaginatorCore.paginate(nums, 1) == (nums[0:10], 1)
     assert PaginatorCore.paginate(nums, 3) == (nums[10:20], 2)
     assert PaginatorCore.paginate(nums, 3, 5) == (nums[10:15], 3)
     assert PaginatorCore.paginate(nums, 4, 5) == (nums[10:15], 3)
Ejemplo n.º 30
0
async def queue(cmd, pld):
    """
    :param cmd: The command object referenced in the command.
    :type cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    page_num = False
    if len(pld.args) == 1:
        if pld.args[0].isdigit():
            page_num = int(pld.args[0])
    if pld.args and not page_num:
        if pld.msg.author.voice:
            same_bound = True
            if pld.msg.guild.voice_client:
                if pld.msg.guild.voice_client.channel.id != pld.msg.author.voice.channel.id:
                    same_bound = False
            if same_bound:
                lookup = ' '.join(pld.args)
                if '/watch?' in lookup:
                    lookup = lookup.split('&')[0]
                    playlist_url = False
                    init_response = discord.Embed(color=0xFFCC66, title='💽 Processing URL...')
                elif '/playlist?' in lookup:
                    playlist_url = True
                    init_response = discord.Embed(color=0xFFCC66,
                                                  title='💽 Processing playlist. This might take a long time...')
                else:
                    if lookup.startswith('http'):
                        playlist_url = True
                    else:
                        playlist_url = False
                    init_response = discord.Embed(color=0xFFCC66, title='💽 Searching...')
                init_res_msg = await pld.msg.channel.send(embed=init_response)
                extracted_info = await cmd.bot.music.extract_info(lookup)
                if extracted_info:
                    if '_type' in extracted_info:
                        if extracted_info['_type'] == 'playlist':
                            if not playlist_url:
                                song_item = extracted_info['entries'][0]
                                playlist = False
                            else:
                                song_item = None
                                playlist = True
                        else:
                            song_item = extracted_info
                            playlist = False
                    else:
                        song_item = extracted_info
                        playlist = False
                    if playlist:
                        pl_title = extracted_info['title']
                        entries = extracted_info['entries']
                        for song_entry in entries:
                            if song_entry:
                                queue_item = QueueItem(pld.bot, pld.msg.author, song_entry)
                                queue_container = cmd.bot.music.get_queue(pld.msg.guild.id)
                                await queue_container.put(queue_item)
                        final_resp = discord.Embed(color=0xFFCC66,
                                                   title=f'💽 Added {len(entries)} songs from {pl_title}.')
                    else:
                        if song_item:
                            queue_item = QueueItem(pld.bot, pld.msg.author, song_item)
                            queue_container = cmd.bot.music.get_queue(pld.msg.guild.id)
                            await queue_container.put(queue_item)
                            duration = str(datetime.timedelta(seconds=int(song_item.get('duration', 0))))
                            requester = f'{pld.msg.author.name}#{pld.msg.author.discriminator}'
                            final_resp = discord.Embed(color=0x66CC66)
                            final_resp.add_field(name='✅ Added To Queue', value=song_item.get('title', "No Title"))
                            if 'thumbnail' in song_item:
                                final_resp.set_thumbnail(url=song_item.get('thumbnail'))
                            final_resp.set_author(name=requester, icon_url=user_avatar(pld.msg.author))
                            final_resp.set_footer(text=f'Duration: {duration}')
                        else:
                            final_resp = GenericResponse('Addition returned a null item.').not_found()
                    try:
                        await init_res_msg.edit(embed=final_resp)
                    except discord.NotFound:
                        pass
                else:
                    final_resp = GenericResponse('No results.').not_found()
                    try:
                        await init_res_msg.edit(embed=final_resp)
                    except discord.NotFound:
                        pass
            else:
                if not pld.args:
                    response = GenericResponse('You are not in my voice channel.').error()
                    await pld.msg.channel.send(embed=response)
        else:
            if not pld.args:
                response = GenericResponse('You are not in a voice channel.').error()
                await pld.msg.channel.send(embed=response)
    else:
        music_queue = cmd.bot.music.get_queue(pld.msg.guild.id)
        if not music_queue.empty():
            music_list_all = await cmd.bot.music.listify_queue(music_queue)
            stats_desc = f'There are **{len(music_list_all)}** songs in the queue.'
            if pld.msg.guild.id in cmd.bot.music.currents:
                curr = cmd.bot.music.currents[pld.msg.guild.id]
                stats_desc += f'\nCurrently playing: [{curr.title}]({curr.url})'
            list_desc_list = []
            boop_headers = ['#', 'Title', 'Requester', 'Duration']
            order_num = 0
            page = page_num if page_num else 1
            music_list, page = PaginatorCore.paginate(music_list_all, page, 5)
            for item in music_list:
                order_num += 1
                duration = str(datetime.timedelta(seconds=item.duration))
                title = item.title
                if ' - ' in title:
                    title = ' - '.join(title.split('-')[1:]).strip()
                title = shorten(title, 20, '...')
                req = shorten(item.requester.name, 9, '...')
                list_desc_list.append([order_num, title, req, duration])
            list_desc = boop(list_desc_list, boop_headers)
            list_title = f'Queued Items on Page {page}'
            response = discord.Embed(color=0x3B88C3)
            guild_icon = str(pld.msg.guild.icon_url) if pld.msg.guild.icon_url else discord.Embed.Empty
            response.set_author(name=pld.msg.guild.name, icon_url=guild_icon)
            response.add_field(name='Current Music Queue', value=stats_desc, inline=False)
            response.add_field(name=list_title, value=f'```bat\n{list_desc}\n```', inline=False)
        else:
            response = discord.Embed(color=0x3B88C3, title='🎵 The queue is empty.')
        await pld.msg.channel.send(embed=response)