Esempio n. 1
0
File: market.py Progetto: AXAz0r/Kon
async def ex(args, message, bot, invoke):
    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
    headers = ['Num', 'Item', 'Price', 'Qty']
    m_list = sorter()
    m_sorted = sorted(m_list, key=lambda x: int(x[0]))
    inv = m_sorted[start_range:end_range]
    if inv:
        output = boop(inv, column_names=headers)
        response = discord.Embed(color=0xC16A4F)
        response.add_field(
            name=f'📋 Items currently for sale | Page {page_number}',
            value=f'```hs\n{output}\n```',
            inline=False)
        response.set_footer(
            text='Use the buyitem command to purchase something')
    else:
        response = discord.Embed(title='🔍 Just an empty page', color=0x696969)
    await message.channel.send(embed=response)
Esempio n. 2
0
async def topcookies(cmd, message, args):
    all_cookies = cmd.db[cmd.db.db_cfg.database].Cookies.find({}).sort(
        'Cookies', pymongo.DESCENDING).limit(20)
    cookie_count = cmd.db[cmd.db.db_cfg.database].Cookies.aggregate([{
        '$group': {
            '_id': 'cookie_counter_cursor',
            'cookie_count': {
                '$sum': '$Cookies'
            }
        }
    }])
    cookie_count = list(cookie_count)
    cookie_count = cookie_count[0]['cookie_count']
    cookie_list = []
    for cookie_file in all_cookies:
        user = discord.utils.find(lambda x: x.id == cookie_file['UserID'],
                                  cmd.bot.get_all_members())
        if user:
            unam = user.name
        else:
            unam = '{Unknown}'
        cookie_list.append([unam, cookie_file['Cookies']])
    cookie_table = boop(cookie_list, ['User', 'Cookies'])
    top_text = f'A total of {cookie_count} cookies have been given.'
    response = discord.Embed(color=0xd99e82)
    response.add_field(name='Cookie Count', value=top_text, inline=False)
    response.add_field(name='Cookie Leaderboard',
                       value=f'```bat\n{cookie_table}\n```',
                       inline=False)
    await message.channel.send(embed=response)
Esempio n. 3
0
async def topexperience(cmd: SigmaCommand, message: discord.Message, args: list):
    value_name = 'Experience'
    sort_key = 'global'
    lb_icon = cmd.bot.user.avatar_url
    lb_category = 'Global'
    if args:
        if args[0].lower() == 'local':
            sort_key = f'guilds.{message.guild.id}'
            lb_icon = message.guild.icon_url or lb_icon
            lb_category = message.guild.name
        elif args[0].lower() == 'total':
            sort_key = 'total'
            lb_category = 'Total'
    all_docs = await cmd.db[cmd.db.db_cfg.database].ExperienceSystem.find({}).sort(sort_key, -1).limit(50).to_list(None)
    leader_docs = []
    all_members = list(cmd.bot.get_all_members())
    for data_doc in all_docs:
        if sort_key == 'global' or sort_key == 'total':
            user_value = data_doc.get(sort_key) or 0
        else:
            user_value = data_doc.get('guilds').get(str(message.guild.id)) or 0
        user_level = int(user_value / 13266.85)
        user_object = discord.utils.find(lambda usr: usr.id == data_doc.get('UserID'), all_members)
        if user_object:
            leader_docs.append([user_object, user_level, user_value])
            if len(leader_docs) >= 20:
                break
    table_data = [[clean_name(doc[0].name, 'Unknown')[:12], str(doc[1]), str(doc[2])] for doc in leader_docs]
    table_body = boop(table_data, ['User Name', 'Level', value_name])
    response = discord.Embed(color=await get_image_colors(lb_icon))
    response.set_author(name=f'{lb_category} {value_name} Leaderboard', icon_url=lb_icon)
    response.description = f'```hs\n{table_body}\n```'
    await message.channel.send(embed=response)
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 = not_found('No statuses found.')
    await pld.msg.channel.send(embed=response)
Esempio n. 5
0
 def describe(self, awoken=False):
     """
     Returns a text block meant for embed information.
     :type awoken: bool
     :rtype: str
     """
     out_proto = [['Health', 'health'], ['Armor', 'armor'],
                  ['Reload', 'reload'], ['Speed', 'speed'],
                  ['Firepower', 'firepower'], ['Torpedo', 'torpedo'],
                  ['Aviation', 'aviation'], ['Oil Cost', 'oil_consumption'],
                  ['Accuracy', 'accuracy'], ['Evasion', 'evasion'],
                  ['Luck', 'luck'], ['Anti-Air', 'anti_air'],
                  ['Anti-Sub', 'anti_submarine']]
     out_list = []
     lvconts = [self.base, self.maxed
                ] if not awoken else [self.maxed, self.awake]
     for proto_data in out_proto:
         out_sub = [proto_data[0]]
         for lvcont in lvconts:
             out_sub.append(str(getattr(lvcont, proto_data[1])))
         out_list.append(out_sub)
     out_list.append(
         ['Average',
          str(self.base.average),
          str(self.maxed.average)])
     out = boop(out_list, ['Stat', 'Base', 'Lv. 100'])
     return out
Esempio n. 6
0
async def logsettings(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.permissions_in(pld.msg.channel).manage_guild:
        settings = []
        for log_key in log_keys:
            if log_key == 'log_modules':
                enabled = pld.settings.get('logged_modules')
            else:
                enabled = pld.settings.get(log_key)
            channel_id = pld.settings.get(f'{log_key}_channel')
            channel = await cmd.bot.get_channel(channel_id)
            chn = channel.name if channel else 'Not Set'
            state = 'Enabled' if enabled else 'Disabled'
            log_line = [log_key[4:].title(), chn, state]
            settings.append(log_line)
        headers = ['Type', 'Channel', 'State']
        output = boop(settings, column_names=headers)
        response = discord.Embed(color=0xC1694F)
        enabled_count = len([opt for opt in settings if opt[2] == 'Enabled'])
        details = f'```py\n{enabled_count} out of {len(log_keys)} logs enabled.\n```'
        response.add_field(name='📋 Log settings',
                           value=details,
                           inline=False)
        response.add_field(name='📄 Details',
                           value=f'```\n{output}\n```',
                           inline=False)
    else:
        response = GenericResponse(
            'Access Denied. Manage Server needed.').denied()
    await pld.msg.channel.send(embed=response)
Esempio n. 7
0
async def inventory(cmd, message, args):
    
    if message.mentions: target = message.mentions[0]
    else: target = message.author
    
    inv = cmd.db.get_inv(target)
    if not inv:
        response = discord.Embed(color=0xc6e4b5, title='💸 Totally empty...')
        await message.channel.send(embed=response)    
        
    size = len(inv)
    bordered_inv = inv[:20]
    headers = ['Item', 'Value']
    to_format = []
    
    for item in bordered_inv:
        to_format.append([item['name'], f'{item["value"]}'])
    
    output = boop(to_format,column_names=headers)
    inv_text = f'Showing the first {len(bordered_inv)} items.'
    inv_text += f'\nYou have a total of {size} items in your inventory.'
    
    response = discord.Embed(color=0xc16a4f)
    response.set_author(name=f'{target.name}#{target.discriminator}', icon_url=user_avatar(target))
    response.add_field(name='📦 Inventory Stats', value=f'```py\n{inv_text}\n```')
    response.add_field(name='📋 Items Currently In It', value=f'```hs\n{output}\n```', inline=False)
    await message.channel.send(embed=response)    
Esempio n. 8
0
async def itemstatistics(cmd: SigmaCommand, message: discord.Message,
                         args: list):
    item_core = await get_item_core(cmd.db)
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    all_stats = await cmd.db[cmd.db.db_nam].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)
    page = args[0] if args else 1
    all_stats, page = 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 message.channel.send(embed=response)
async def liststatuses(cmd: SigmaCommand, message: discord.Message,
                       args: list):
    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 = args[0] if args else 1
        status_list, page = paginate(status_list, page)
        status_block = boop(status_list, ['ID', 'Text'])
        response = discord.Embed(
            color=await get_image_colors(cmd.bot.user.avatar_url))
        response.set_author(
            name=f'{cmd.bot.user.name}\'s Status Rotation Items',
            icon_url=user_avatar(cmd.bot.user))
        response.add_field(
            name='Info',
            value=
            f'Showing {len(status_list)} items out of {total_status} on page {page}.'
        )
        response.add_field(name="List",
                           value=f'```\n{status_block}\n```',
                           inline=False)
    else:
        response = discord.Embed(color=0x696969, title='🔍 No statuses found.')
    await message.channel.send(embed=response)
Esempio n. 10
0
async def apikeys(cmd, message, args):
    if message.author.id in permitted_id:
        out_list = []
        for option in dir(config):
            if not option.startswith('__'):
                option_value = getattr(config, option)
                if option_value == '':
                    option_state = '✖'
                else:
                    option_state = '✔'
                out_list.append([option.upper(), option_state])
        out_text = '```haskell\n' + boop(out_list) + '\n```'
        try:
            await cmd.bot.start_private_message(message.author)
            await cmd.bot.send_message(message.author, out_text)
        except Exception as e:
            cmd.log.error(e)
            await cmd.bot.send_message(message.channel, str(e))
        status = await cmd.bot.send_message(
            message.channel, 'The API Key List has been sent to your DM.')
    else:
        status = await cmd.bot.send_message(message.channel,
                                            'Insufficient permissions. :x:')
    await asyncio.sleep(10)
    await cmd.bot.delete_message(message)
    await cmd.bot.delete_message(status)
Esempio n. 11
0
async def apikeys(cmd, message, args):
    if message.author.id in permitted_id:
        out_list = []
        for option in dir(config):
            if not option.startswith('__'):
                option_value = getattr(config, option)
                if option_value == '':
                    option_state = '✖'
                else:
                    option_state = '✔'
                out_list.append([option.upper(), option_state])
        out_text = '```haskell\n' + boop(out_list) + '\n```'
        try:
            await cmd.bot.start_private_message(message.author)
            await cmd.bot.send_message(message.author, out_text)
            status = discord.Embed(type='rich', color=0x66cc66,
                                   title='✅ The API Key List has been sent to your DM.')
        except Exception as e:
            cmd.log.error(e)
            await cmd.bot.send_message(message.channel, str(e))
            return
    else:
        status = discord.Embed(type='rich', color=0xDB0000,
                               title='⛔ Insufficient Permissions. Bot Owner Only.')
    await cmd.bot.send_message(message.channel, None, embed=status)
Esempio n. 12
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)
Esempio n. 13
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)
Esempio n. 14
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)
Esempio n. 15
0
async def topcurrency(cmd: SigmaCommand, message: discord.Message, args: list):
    value_name = cmd.bot.cfg.pref.currency
    resource = cache_key = 'currency'
    sort_key = f'resources.{resource}.ranked'
    lb_category = 'This Month\'s'
    localed = False
    if args:
        if args[0].lower() == 'total':
            sort_key = f'resources.{resource}.total'
            lb_category = 'Total'
        elif args[0].lower() == 'local':
            sort_key = f'resources.{resource}.origins.guilds.{message.guild.id}'
            localed = True
            lb_category = message.guild.name
    now = arrow.utcnow().timestamp
    leader_docs, leader_timer = tcrlb_cache.get_cache(
        sort_key), tcrlb_cache.get_cache(f'{sort_key}_stamp') or now
    if not leader_docs or leader_timer + 180 < now:
        coll = cmd.db[cmd.db.db_nam].Profiles
        search = {
            '$and': [{
                sort_key: {
                    '$exists': True
                }
            }, {
                sort_key: {
                    '$gt': 0
                }
            }]
        }
        all_docs = await coll.find(search).sort(sort_key,
                                                -1).limit(50).to_list(None)
        leader_docs = []
        all_members = cmd.bot.get_all_members()
        for data_doc in all_docs:
            user_value = await get_user_value(cmd.db, data_doc.get('user_id'),
                                              message.guild.id, cache_key,
                                              resource, localed)
            user_object = discord.utils.find(
                lambda usr: usr.id == data_doc.get('user_id'), all_members)
            if user_object:
                if user_value:
                    leader_docs.append([user_object, user_value])
                    if len(leader_docs) >= 20:
                        break
        tcrlb_cache.set_cache(sort_key, leader_docs)
        tcrlb_cache.set_cache(f'{sort_key}_stamp', now)
    table_data = [[
        pos + 1 if not doc[0].id == message.author.id else f'{pos + 1} <',
        clean_name(doc[0].name, 'Unknown')[:12],
        str(doc[1])
    ] for pos, doc in enumerate(leader_docs)]
    table_body = boop(table_data, ['#', 'User Name', value_name])
    curr_icon = cmd.bot.cfg.pref.currency_icon
    response = f'{curr_icon} **{lb_category} {value_name} Leaderboard**'
    response += f'\n```hs\n{table_body}\n```'
    response += f'\nLeaderboard last updated {arrow.get(leader_timer).humanize()}.'
    await message.channel.send(response)
Esempio n. 16
0
async def weather(cmd, message, args):
    
    if not args:
        await message.channel.send(cmd.help())
        return

    if OpenMapsAPIKey == '':
        embed = discord.Embed(color=0xDB0000)
        embed.add_field(name='API key OpenMapsAPIKey not found.', value='Please ask the bot owner to add it.')
        await message.channel.send(None, embed=embed)
        return

    location = ' '.join(args)
    
   ##try:
    if True:
        try:
            loc_element = Geolocator().geocode(location)
            latitude = loc_element.latitude
            longitude = loc_element.longitude
        except Exception as e:
            cmd.log.error(e)
            await message.channel.send('Unable to retrieve coordinates for ' + location)
            return

        openWeatherURL = 'http://api.openweathermap.org/data/2.5/weather?lat=' + str(latitude) + '&lon=' + str(longitude) + "&cnt=1&units=imperial&APPID=" + OpenMapsAPIKey
        async with aiohttp.ClientSession() as session:
            async with session.get(openWeatherURL) as data:
                data = await data.json()

        temp_f = data['main']['temp']
        humidity = data['main']['humidity']
        pressure = data['main']['pressure']
        wind_speed_mph = data['wind']['speed']
        wind_bearing = data['wind']['deg']
        cloud_cover = data['clouds']['all']
        
        wind_speed_kph = wind_speed_mph * 1.609344
        temp_c = (temp_f - 32) / 1.8    
        
        # Data Output
        out_list = []

        out_list.append(['Temperature', str(format(temp_c, '.2f')) + '°C (' + str(temp_f) + '°F)'])
        out_list.append(['Humidity', str(humidity) + '%'])
        out_list.append(['Wind Speed', str(format(wind_speed_kph, '.2f')) + ' KPH (' + str(wind_speed_mph) + ' MPH)'])
        out_list.append(['Wind Direction', str(wind_bearing) + '°'])
        out_list.append(['Cloud Cover', str(cloud_cover) + '%'])
        out_list.append(['Pressure', str(pressure) + ' mb'])

        out_pretty_list = boop(out_list)

        out_text = 'Weather data for **' + location.title() + '**\nLocation: *(Lat: ' + str(latitude) + ', Long: ' + str(longitude) + ')*'
        out_text += '\n```haskell\n' + out_pretty_list + '\n```'
#        forecasts = '```haskell\nUpcoming: \"' + today_forecast + '\"\nThis Week: \"' + week_forecast + '\"\n```\n'
#       out_text += '\nForecasts:\n' + forecasts
        await message.channel.send(out_text)
Esempio n. 17
0
async def topcurrency(cmd, message, args):
    coll = cmd.db[cmd.db.db_cfg.database].CurrencySystem
    currency = cmd.bot.cfg.pref.currency
    if args:
        mode = ' '.join(args)
        if mode.lower() == 'current':
            title = f'{currency} Leaderboard by Current Amount.'
            key_look = 'current'
        elif mode.lower() == 'global':
            title = f'{currency} Leaderboard by Globally Earned.'
            key_look = 'global'
        elif mode.lower() == 'local':
            title = f'{currency} Leaderboard on {message.guild.name}.'
            key_look = None
        else:
            title = f'{currency} Leaderboard on {message.guild.name}.'
            key_look = None
    else:
        title = f'{currency} Leaderboard on {message.guild.name}.'
        key_look = None
    if key_look:
        kud_list = await coll.find().sort([(key_look, pymongo.DESCENDING)]
                                          ).limit(10).to_list(None)
    else:
        kud_list = await coll.find({
            f'guilds.{message.guild.id}': {
                '$exists': True
            }
        }).sort([(f'guilds.{message.guild.id}', pymongo.DESCENDING)]
                ).limit(10).to_list(None)
    user_list = []
    list_headers = ['Username', currency]
    for kud_item in kud_list:
        usr = discord.utils.find(lambda x: x.id == kud_item['UserID'],
                                 cmd.bot.get_all_members())
        if usr:
            usr_name = usr.name
        else:
            usr_name = '{Unknown User}'
        if len(usr_name) > 32:
            usr_name = usr_name[:29] + '...'
        if key_look:
            user_list.append([usr_name, kud_item[key_look]])
        else:
            user_list.append(
                [usr_name, kud_item['guilds'][str(message.guild.id)]])
    lb_table = boop(user_list, list_headers)
    strip_clr = await get_image_colors(message.guild.icon_url)
    response = discord.Embed(color=strip_clr)
    if not key_look:
        response.set_author(name=message.guild.name,
                            icon_url=message.guild.icon_url)
    response.add_field(name='Kud Criteria', value=title, inline=False)
    response.add_field(name='User List',
                       value=f'```bat\n{lb_table}\n```',
                       inline=False)
    await message.channel.send(embed=response)
Esempio n. 18
0
async def notify_system(db, res, table_data):
    table = boop(table_data, ['PLC', 'USR', 'VAL'])
    data = {
        'reported': False,
        'title': f'📊 {res.title()} Resource Leaderboard Awarded',
        'color': 0xf9f9f9,
        'content': f'```hs\n{table}\n```'
    }
    await db[db.db_nam].SystemMessages.insert_one(data)
async def topcurrency(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
    """
    gu = cmd.bot.get_user
    value_name = cmd.bot.cfg.pref.currency
    resource = 'currency'
    sort_key = 'ranked'
    lb_category = 'This Month\'s'
    if pld.args:
        if pld.args[0].lower() == 'total':
            sort_key = 'total'
            lb_category = 'Total'
        elif pld.args[0].lower() == 'current':
            sort_key = 'current'
            lb_category = 'Current'
        elif pld.args[0].lower() == 'local':
            sort_key = f'origins.guilds.{pld.msg.guild.id}'
            lb_category = pld.msg.guild.name
    now = arrow.utcnow().timestamp
    leader_docs = await cmd.db.cache.get_cache(f'{resource}_{sort_key}')
    leader_timer = await cmd.db.cache.get_cache(f'{resource}_{sort_key}_stamp'
                                                ) or now
    if not leader_docs or leader_timer + 180 < now:
        coll = cmd.db[cmd.db.db_nam][f'{resource.title()}Resource']
        search = {
            '$and': [{
                sort_key: {
                    '$exists': True
                }
            }, {
                sort_key: {
                    '$gt': 0
                }
            }]
        }
        all_docs = await coll.find(search).sort(sort_key,
                                                -1).limit(100).to_list(None)
        leader_docs = await get_leader_docs(cmd.db, all_docs, sort_key)
        await cmd.db.cache.set_cache(f'{resource}_{sort_key}', leader_docs)
        await cmd.db.cache.set_cache(f'{resource}_{sort_key}_stamp', now)
        leader_timer = now
    table_data = [[
        pos + 1 if not doc[0] == pld.msg.author.id else f'{pos + 1} <',
        clean_name((await gu(doc[0])).name if await gu(doc[0]) else doc[0],
                   'Unknown')[:18],
        str(doc[1])
    ] for pos, doc in enumerate(leader_docs)]
    table_body = boop(table_data, ['#', 'User Name', value_name])
    curr_icon = cmd.bot.cfg.pref.currency_icon
    response = f'{curr_icon} **{lb_category} {value_name} Leaderboard**'
    response += f'\n```hs\n{table_body}\n```'
    response += f'\nLeaderboard last updated **{arrow.get(leader_timer).humanize()}**.'
    await pld.msg.channel.send(response)
Esempio n. 20
0
async def inventory(cmd: SigmaCommand, message: discord.Message, args: list):
    item_core = await get_item_core(cmd.db)
    reci_core = await get_recipe_core(cmd.db)
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    upgrade_file = await cmd.db[cmd.db.db_nam].Upgrades.find_one(
        {'user_id': target.id}) or {}
    storage = upgrade_file.get('storage', 0)
    inv_limit = 64 + (8 * storage)
    inv = await cmd.db.get_inventory(target)
    total_inv = len(inv)
    item_o_list = []
    item_filter = get_filter(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)
    page = args[0] if args else 1
    inv, page = paginate(item_o_list, page)
    start_range, end_range = (page - 1) * 10, page * 10
    if inv:
        all_reci = reci_core.recipes
        headers = ['Type', 'Item', '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 == message.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:
        response = discord.Embed(color=0xc6e4b5, title='💸 Totally empty...')
    response.set_author(name=f'{target.name}#{target.discriminator}',
                        icon_url=user_avatar(target))
    await message.channel.send(embed=response)
Esempio n. 21
0
async def bhranking(cmd, message, args):
    regions = ['global', 'us-e', 'eu', 'sea', 'br2', 'aus', 'us-w']
    url_base = 'http://www.brawlhalla.com/rankings/1v1/'
    if not args:
        region = 'global'
    else:
        region = args[0].lower()
        if region not in regions:
            embed = discord.Embed(color=0xBE1931)
            embed.add_field(
                name='❗ Invalid Region',
                value=f'```\nRegions: {", ".join(regions).upper()}\n```')
            await message.channel.send(None, embed=embed)
            return
    if region == 'global':
        lb_url = url_base
    else:
        lb_url = url_base + region + '/'
    async with aiohttp.ClientSession() as session:
        async with session.get(lb_url) as data:
            page = await data.text()
    root = html.fromstring(page)
    table = root.cssselect('#content')[0][0][0]
    rankings = []
    for row in table:
        if len(row) == 8:
            if row[1].text == 'Rank':
                pass
            else:
                rank_data = {
                    'Rank': row[1].text,
                    'Region': row[2].text,
                    'Name': row[3].text,
                    'WL': row[5].text,
                    'Season': row[6].text,
                    'Peak': row[7].text
                }
                if len(rank_data['Name']) > 10:
                    rank_data.update({'Name': rank_data['Name'][:10] + '...'})
                rankings.append(rank_data)
    embed = discord.Embed(color=0xFF3300)
    to_format = []
    for x in range(0, 10):
        data = rankings[x]
        to_format.append(
            [data['Region'], data['Name'], data['Season'], data['Peak']])
    player_list = boop(to_format,
                       column_names=['Region', 'Name', 'Season', 'Peak'])
    embed.add_field(name='Region',
                    value='```\n' + region.upper() + '\n```',
                    inline=False)
    embed.add_field(name='Brawhalla 1v1 Top 10 Ranked Players',
                    value='```\n' + player_list + '\n```',
                    inline=False)
    await message.channel.send(None, embed=embed)
Esempio n. 22
0
async def rolepopulation(cmd: SigmaCommand, message: discord.Message,
                         args: list):
    if args:
        rl_qry = ' '.join(args)
        role_search = discord.utils.find(
            lambda x: x.name.lower() == rl_qry.lower(), message.guild.roles)
        if role_search:
            counter = 0
            for member in message.guild.members:
                member_role_search = discord.utils.find(
                    lambda x: x.id == role_search.id, member.roles)
                if member_role_search:
                    counter += 1
            response = discord.Embed(color=role_search.color)
            response.set_author(name=message.guild.name,
                                icon_url=message.guild.icon_url)
            response.add_field(name=f'{role_search.name} Population',
                               value=f'```[y\n{counter}\n```')
        else:
            response = discord.Embed(color=0x696969,
                                     title=f'🔍 {rl_qry} not found.')
    else:
        role_dict = {}
        for role in message.guild.roles:
            if role.name != '@everyone':
                role_key = role.name
                role_count = 0
                for member in message.guild.members:
                    member_role_search = discord.utils.find(
                        lambda x: x.id == role.id, member.roles)
                    if member_role_search:
                        role_count += 1
                role_dict.update({role_key: role_count})
        sorted_roles = sorted(role_dict.items(),
                              key=operator.itemgetter(1),
                              reverse=True)
        output = []
        for srole in sorted_roles[:20]:
            output.append([
                srole[0], srole[1],
                f'{str(percentify(srole[1], len(message.guild.members)))}%'
            ])
        out_text = boop(output)
        response = discord.Embed(color=0x3B88C3)
        response.set_author(name=message.guild.name,
                            icon_url=message.guild.icon_url)
        response.add_field(
            name='Statistics',
            value=
            f'```py\nShowing {len(output)} roles out of {len(message.guild.roles)}\n```',
            inline=False)
        response.add_field(name=f'Role Population',
                           value=f'```haskell\n{out_text}\n```',
                           inline=False)
    await message.channel.send(embed=response)
Esempio n. 23
0
async def permissions(cmd, message, args):
    perm_list = []
    col_nam = ['Permission', 'Active']
    if args:
        user_q = message.mentions[0]
    else:
        user_q = message.author
    for permission in user_q.server_permissions:
        perm_list.append(permission)
    out_text = '\n```\n' + boop(perm_list, col_nam).replace('_', ' ').title() + '\n```'
    await cmd.bot.send_message(message.channel, 'Permissions For ' + user_q.name + out_text)
Esempio n. 24
0
async def ingame(cmd: SigmaCommand, message: discord.Message, args: list):
    games = {}
    online_count = 0
    playing_count = 0
    total_count = 0
    for member in message.guild.members:
        total_count += 1
        status = str(member.status)
        if status != 'offline':
            online_count += 1
        if not member.bot:
            if member.activity:
                game_name = str(member.activity)
                repl_name = game_name.replace(' ', '')
                if repl_name != '':
                    playing_count += 1
                    if game_name not in games:
                        games.update({game_name: 1})
                    else:
                        curr_count = games[game_name]
                        new_count = curr_count + 1
                        games.update({game_name: new_count})
    embed = discord.Embed(color=0x1ABC9C)
    sorted_games = sorted(games.items(), key=operator.itemgetter(1))
    n = 0
    out_table_list = []
    game_count = len(sorted_games)
    for key, value in reversed(sorted_games):
        if n < 5:
            n += 1
            if len(key) > 32:
                key = key[:32] + '...'
            out_table_list.append(
                [str(n), key.title(), value, str(((value / playing_count) * 10000) // 100).split('.')[0] + '%'])
    out = boop(out_table_list)
    general_stats_list = [['Online', online_count], ['In-Game', playing_count], ['Unique Games', game_count]]
    general_stats_out = boop(general_stats_list)
    embed.add_field(name='👾 Current Gaming Statistics on ' + message.guild.name,
                    value='```haskell\n' + general_stats_out + '\n```', inline=False)
    embed.add_field(name='🎮 By Game...', value='```haskell\n' + out + '\n```', inline=False)
    await message.channel.send(None, embed=embed)
Esempio n. 25
0
async def inventory(cmd, message, args):
    global item_core
    if not item_core:
        item_core = ItemCore(cmd.resource('data'))
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    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 = 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 {len(inv)}/{total_inv} 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)
Esempio n. 26
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)
Esempio n. 27
0
async def wfsales(cmd: SigmaCommand, message: discord.Message, args: list):
    sales_api = 'https://deathsnacks.com/wf/data/flashsales_raw.txt'
    async with aiohttp.ClientSession() as session:
        async with session.get(sales_api) as data:
            sales_text = await data.text()
    discount_only = True
    title = 'List of Warframe Items on Sale'
    if args:
        if args[-1].lower() == 'all':
            discount_only = False
            title = 'List of Promoted Warframe Items'
    if args:
        try:
            page = int(args[0]) - 1
            if page < 0:
                page = 0
        except ValueError:
            page = 0
    else:
        page = 0
    sales_data_all = parse_sales_data(sales_text, discount_only)
    total_item = len(sales_data_all)
    sales_data = sales_data_all[page * 10:(page + 1) * 10]
    no_discounts = True
    for item in sales_data:
        if item.get('discount') != 0:
            no_discounts = False
            break
    if no_discounts:
        headers = ['Name', 'Platinum']
    else:
        headers = ['Name', 'Platinum', 'Discount']
    if sales_data:
        total_plat = sum([x.get('platinum') for x in sales_data_all])
        sales_data = sorted(sales_data, key=lambda x: x.get('name'))
        stat_block = f'Showing {len(sales_data)} items out of {total_item}.'
        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('name'), sale_item.get('platinum')])
            else:
                item_list.append([sale_item.get('name'), sale_item.get('platinum'), f"-{sale_item.get('discount')}%"])
        item_table = boop(item_list, headers)
        response = discord.Embed(color=0x336699)
        response.set_author(name='Warframe Promotions', icon_url=wf_logo)
        response.description = stat_block
        response.add_field(name=title, value=f'```hs\n{item_table}\n```')
    else:
        response = discord.Embed(color=0x336699, title=f'No items found, try adding the "all" argument.')
    await message.channel.send(embed=response)
Esempio n. 28
0
async def spouses(cmd: SigmaCommand, message: discord.Message, args: list):
    if message.mentions:
        target = message.mentions[0]
    else:
        target = message.author
    profile = await cmd.db[cmd.db.db_nam].Profiles.find_one(
        {'user_id': target.id}) or {}
    splist = profile.get('spouses', [])
    spcount = len(splist)
    page = args[0] if args else 1
    splist, page = paginate(splist, page, 5)
    starter = 'You are' if target.id == message.author.id else f'{target.name} is'
    mid = 'have' if target.id == message.author.id else 'has'
    if splist:
        spdata = []
        all_members = cmd.bot.get_all_members()
        for sp in splist:
            spmemb = discord.utils.find(lambda m: m.id == sp.get('user_id'),
                                        all_members)
            spmemb = spmemb.name if spmemb 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]
            sp_status = 'Married' if target.id in sp_spouse_ids else 'Proposed'
            spdata.append([
                spmemb, sp_status,
                arrow.get(sp.get('time')).humanize().title()
            ])
        spbody = boop(spdata, ['Name', 'Status', 'Since'])
        upgrades = await cmd.db[cmd.db.db_nam].Upgrades.find_one(
            {'user_id': target.id}) 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, nor {mid} proposed, to anyone.')
        else:
            response = discord.Embed(
                color=0xe75a70,
                title=f'💔 {starter.split()[0]} {mid} nobody on page {page}.'
            )
    await message.channel.send(embed=response)
Esempio n. 29
0
async def allitems(cmd: SigmaCommand, message: discord.Message, args: list):
    item_core = await get_item_core(cmd.db)
    reci_core = await get_recipe_core(cmd.db)
    item_o_list = item_core.all_items
    special = False
    if args:
        types = ['animals', 'animal', 'plants', 'plant', 'fish']
        selection = 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)
    if special:
        page = args[1] if len(args) > 1 else 1
    else:
        page = args[0] if args else 1
    inv, page = paginate(item_o_list, page)
    start_range, end_range = (page - 1) * 10, page * 10
    if inv:
        all_reci = reci_core.recipes
        headers = ['Type', 'Item', '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 = discord.Embed(color=0xBE1931,
                                 title=f'❗ Could not retrieve Item Core data.')
    await message.channel.send(embed=response)
Esempio n. 30
0
async def topexperience(cmd: SigmaCommand, message: discord.Message,
                        args: list):
    value_name = 'Experience'
    sort_key = 'global'
    lb_category = 'Global'
    search = {}
    if args:
        if args[0].lower() == 'local':
            sort_key = f'guilds.{message.guild.id}'
            search = {sort_key: {'$exists': True}}
            lb_category = message.guild.name
        elif args[0].lower() == 'total':
            sort_key = 'total'
            lb_category = 'Total'
    now = arrow.utcnow().timestamp
    leader_docs, leader_timer = txplb_cache.get_cache(
        sort_key), txplb_cache.get_cache(f'{sort_key}_stamp') or now
    if not leader_docs or leader_timer < now + 180:
        coll = cmd.db[cmd.db.db_nam].ExperienceSystem
        all_docs = await coll.find(search).sort(sort_key,
                                                -1).limit(50).to_list(None)
        leader_docs = []
        all_members = cmd.bot.get_all_members()
        for data_doc in all_docs:
            if sort_key == 'global' or sort_key == 'total':
                user_value = data_doc.get(sort_key) or 0
            else:
                user_value = data_doc.get('guilds').get(str(
                    message.guild.id)) or 0
            user_level = int(user_value / 13266.85)
            user_object = discord.utils.find(
                lambda usr: usr.id == data_doc.get('UserID'), all_members)
            if user_object:
                if user_value:
                    leader_docs.append([user_object, user_level, user_value])
                    if len(leader_docs) >= 20:
                        break
        txplb_cache.set_cache(sort_key, leader_docs)
        txplb_cache.set_cache(f'{sort_key}_stamp', now)
    table_data = [[
        pos + 1 if not doc[0].id == message.author.id else f'{pos + 1} <',
        clean_name(doc[0].name, 'Unknown')[:12],
        str(doc[1]),
        str(doc[2])
    ] for pos, doc in enumerate(leader_docs)]
    table_body = boop(table_data, ['#', 'User Name', 'Level', value_name])
    response = f'🔰 **{lb_category} {value_name} Leaderboard**'
    response += f'\n```hs\n{table_body}\n```'
    response += f'\nLeaderboard last updated {arrow.get(leader_timer).humanize()}.'
    await message.channel.send(response)