Пример #1
0
def other(context):
    warehouse = load_saved(guild=context.user_data.get('guild', ''))
    hours = 3
    responses = []
    now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    if (other := warehouse.get('other', {})) and (age := now - other['timestamp']) < datetime.timedelta(hours=hours):
        output = [f'Based on /g_stock_other data {age.seconds // 60} minutes old:\n']
        page_counter = 0
        value_to_weight = {id: id_lookup.get(id, {}).get('shopSellPrice', 0)/id_lookup.get(id, {}).get('weight', 1) for id in other['data']}
        for id in sorted(value_to_weight, key=value_to_weight.get, reverse=True):
            items = other['data'][id]
            hold_output = []
            sub_output = []
            item_count = 0
            for item in sorted(items):
                item_id, name, count = item
                if item_id.startswith('u') and (match := re.search(r'[╦брхЃрхЄрХюрхѕрхЅ]+', item_id)):
                    split = match.span()[0]
                    item_id = item_id[:split] + 'РђІ' + item_id[split:]  # zero width space
                item_count += count
                sub_output.append(f'<code>  </code>/g_i_{item_id} {name} x {count}')
            hold_output.append(f"<code>{id}</code> {id_lookup.get(id, {}).get('name', 'Assorted')} РѕЉ {item_count} ­Ъњ░{id_lookup.get(id, {}).get('shopSellPrice', '??')}")
            hold_output.append(f"­Ъњ░/Рџќ№ИЈ {value_to_weight[id]:.2f}")
            hold_output.extend(sub_output)
            hold_output.append(' ')
            hold_output = '\n'.join(hold_output)

            page_counter += len(hold_output.encode('utf-8'))
            if page_counter >= 3000:  # tg officially supports messages as long as 4096, but the formatting gives up around 3000
                responses.append('\n'.join(output))
                page_counter = 0
                output = []
            output.append(hold_output)
Пример #2
0
def misc(context):
    warehouse = load_saved(guild=context.user_data.get('guild', ''))
    hours = 5
    responses = []
    now = datetime.datetime.utcnow()
    if (misc := warehouse.get('misc', {})) and (
            age := now - misc['timestamp']) < datetime.timedelta(hours=hours):
        try:
            with open('auctionprices.dict',
                      'rb') as ap, open('stockprices.dict', 'rb') as sp:
                auction_prices = pickle.load(ap)
                stock_prices = pickle.load(sp)
                price_age = min(auction_prices['last_update'],
                                stock_prices['last_update'])
                prices = {**auction_prices, **stock_prices}
                prices['last_update'] = price_age
        except FileNotFoundError:
            prices = {}

        output = [
            f'Based on /g_stock_misc data {age.seconds // 60} minutes old:\n'
        ]
        for id in sorted(misc['data'], key=misc['data'].get, reverse=True):
            price = prices.get(id, '')
            if price:
                currency = '💰' if isinstance(price, int) else '�'
                price = f'{currency}{price}'

            output.append(
                f'<code>{id}</code> {id_lookup.get(id, {}).get("name", "Name Missing")} x {misc["data"][id]} {price}'
            )

        sort_by_weight = {
            id: misc['data'][id] * id_lookup.get(id, {}).get('weight', 1)
            for id in misc['data']
        }
        sort_by_weight = sorted(sort_by_weight,
                                key=sort_by_weight.get,
                                reverse=True)
        x = [
            misc['data'][id] * id_lookup.get(id, {}).get('weight', 1)
            for id in sort_by_weight
        ]
        y = [
            f'{id_lookup.get(id, {}).get("name", "??").lower()} {id}'
            for id in sort_by_weight
        ]
        r = range(len(sort_by_weight))
        plt.clf()  # clear plot, because it doesn't get cleared from last run
        plt.figure(figsize=(6.4, 1.5 + (len(sort_by_weight) * 0.15)))
        plt.barh(r, x)
        plt.yticks(r, y, fontsize='8')
        plt.legend(loc='upper right', labels=['Weight'])
        plt.subplots_adjust(left=0.3)
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        responses.append(buf)

        responses.append('\n'.join(output))
Пример #3
0
def craft(context):
    response = ["Can't craft this"]
    if context.args:
        id = context.args[0]
        info = id_lookup.get(id, {})

        count = 1
        if len(context.args) > 1:
            count = int(context.args[1])

        if info.get('craftable', False):
            recipe = [{
                'name': name,
                'number': int(amount) * count
            } for name, amount in info['recipe'].items() if name != 'Gold']
            recipe_str = '\n'.join([
                f'   {name}: {amount}{(f" x {count} = {int(amount) * count}" if count > 1 else "")}'
                for name, amount in info['recipe'].items()
            ])
            response = [
                f'<b>{info["name"]}{f" x {count}" if count > 1 else ""}</b>  /c_{id}{f"_{count}" if count > 1 else ""}\n'
                f'''   Mana requirement: {info.get("craftMana", "unknown")}💧{(f" x {count} = {info.get('craftMana', 0) * count}💧" if count > 1 else "")}\n'''
                f'{recipe_str}\n\n'
                f'{parts(recipe, context.user_data.get("guild", ""))}'
            ]

    return response
Пример #4
0
                item_count += count
                sub_output.append(f'<code>  </code>/g_i_{item_id} {name} x {count}')
            hold_output.append(f"<code>{id}</code> {id_lookup.get(id, {}).get('name', 'Assorted')} РѕЉ {item_count} ­Ъњ░{id_lookup.get(id, {}).get('shopSellPrice', '??')}")
            hold_output.append(f"­Ъњ░/Рџќ№ИЈ {value_to_weight[id]:.2f}")
            hold_output.extend(sub_output)
            hold_output.append(' ')
            hold_output = '\n'.join(hold_output)

            page_counter += len(hold_output.encode('utf-8'))
            if page_counter >= 3000:  # tg officially supports messages as long as 4096, but the formatting gives up around 3000
                responses.append('\n'.join(output))
                page_counter = 0
                output = []
            output.append(hold_output)

        count_and_weight = {id: sum(list(zip(*other['data'][id]))[2]) * id_lookup.get(id, {}).get('weight', 0) for id in other['data']}
        sort_by_weight = sorted(count_and_weight, key=count_and_weight.get, reverse=True)
        x = [count_and_weight[id] for id in sort_by_weight]
        y = [f"{id_lookup.get(id, {'name': 'assorted'})['name'].lower()} {id}" for id in sort_by_weight]
        r = range(len(x))
        plt.clf()  # clear plot, because it doesn't get cleared from last run
        plt.figure(figsize=(6.4, 1.5+(len(sort_by_weight)*0.15)))
        plt.barh(r, x)
        plt.yticks(r, y, fontsize='8')
        plt.legend(loc='upper right', labels=['Other by Weight'])
        plt.subplots_adjust(left=0.3)
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)

        responses.append('\n'.join(output))
Пример #5
0
def all_stock(context):
    warehouse = load_saved(guild=context.user_data.get('guild', ''))
    hours = 50
    responses = []
    now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    if (res := warehouse.get('res', {})) and \
       (rec := warehouse.get('rec', {})) and \
       (alch := warehouse.get('alch', {})) and \
       (misc := warehouse.get('misc', {})) and \
       (parts := warehouse.get('parts', {})) and \
       (other := warehouse.get('other', {})) and \
       (age_res := now - res['timestamp']) < datetime.timedelta(hours=hours) and \
       (age_rec := now - rec['timestamp']) < datetime.timedelta(hours=hours) and \
       (age_alch := now - alch['timestamp']) < datetime.timedelta(hours=hours) and \
       (age_misc := now - misc['timestamp']) < datetime.timedelta(hours=hours) and \
       (age_parts := now - parts['timestamp']) < datetime.timedelta(hours=hours) and \
       (age_other := now - other['timestamp']) < datetime.timedelta(hours=hours):

        ages = (
            (age_res, '/g_stock_res'),
            (age_rec, '/g_stock_rec'),
            (age_alch, '/g_stock_alch'),
            (age_misc, '/g_stock_misc'),
            (age_parts, '/g_stock_parts'),
            (age_other, '/g_stock_other')
        )
        age, command = max(ages)
        output = [f'Based on {command} data {age.seconds // 60} minutes old:\n']

        items_by_weight = {}
        items_by_category = {}
        for category in warehouse:
            if category != 'other':
                for id, count in warehouse[category]['data'].items():
                    items_by_weight[id] = count * id_lookup.get(id, {}).get('weight', 0)
                    items_by_category[id] = category
            else:
                for id in warehouse[category]['data']:
                    items_by_weight[id] = sum(list(zip(*warehouse[category]['data'][id]))[2]) * id_lookup.get(id, {}).get('weight', 0)
                    items_by_category[id] = category

        total_guild_weight = sum(items_by_weight.values())
        output.append(f'Total guild weight: {total_guild_weight}')

        sorted_by_weight = sorted(items_by_weight, key=items_by_weight.get, reverse=False)

        x = [items_by_weight[id] for id in sorted_by_weight]
        y = [f"{id_lookup.get(id, {'name': 'unidentified object'})['name'].lower()} {id}" for id in sorted_by_weight]
        r = range(len(x))
        colors = [color_lookup[items_by_category[item.rpartition(' ')[2]]] for item in y]

        plt.clf()  # clear plot, because it doesn't get cleared from last run
        fig, ax = plt.subplots()
        ax.xaxis.tick_top()
        plt.figure(figsize=(6.4, (len(x) * 0.15)))

        plt.barh(r, x, color=colors)
        plt.yticks(r, y, fontsize='8', fontname='symbola')

        plt.title('Weight in Guild Stock')
        patches = [mpatches.Patch(color=color, label=category) for category, color in color_lookup.items()]
        plt.legend(handles=patches, ncol=3, title='/g_stock_…')
        plt.subplots_adjust(left=0.3)

        buf = io.BytesIO()
        buf.name = 'weights.pdf'
        plt.savefig(buf, format='pdf')
        buf.seek(0)

        responses.append('\n'.join(output))
        responses.append(buf)