async def get_rr_message(query, ctx, bot): # inits spl = query.strip().split(maxsplit=1) # validity checks if not ctx.guild: raise TemplatedError("no_guild") if not spl: raise TemplatedError("no_rr_message_id") # get log message_id = spl[0] new_query = spl[1] log_file = utils.REACTION_ROLE_LOG_DIR + str(ctx.guild.id) + ".json" log = utils.load_json_with_default(log_file) # get message channel for ch in log: if message_id in log[ch]: msg_ch = bot.get_channel(int(ch)) break else: raise TemplatedError("bad_rr_message_id", string=message_id) # fetch message try: msg = await msg_ch.fetch_message(int(message_id)) return msg, new_query except discord.NotFound: raise TemplatedError("deleted_rr_message", string=message_id) except ValueError: raise TemplatedError("rr_message_not_int", string=message_id)
def filter_data(checks, data, keyword_list): ret= [] # get items containing [name] and passing all keyword checks if not checks: raise TemplatedError("no_keywords", keywords=keyword_list) for x in data: if all(chk(x) for chk in checks): ret.append(x) if not ret: raise TemplatedError("no_equip_match", keywords=keyword_list) return ret
async def get_html(link, session): from classes.errors import TemplatedError resp= await session.get(link) if not resp.status == 200: raise TemplatedError("bad_response", link=link, response=resp) else: text= await resp.text(encoding='utf-8', errors='ignore') return text
def parse_message_json(string): string = string.strip() # add brackets # string= "{ " + string if not string.startswith("{") else string # string+= "} " if not string.endswith("}") else "" # if empty if not string: raise TemplatedError("empty_message_json") # convert to yaml (which supports json) try: dct = YAML().load(string) except (ParserError, ScannerError) as e: raise TemplatedError("yaml_to_json", string=string, error=str(e)) # convert yaml to dictionary dct = dict(dct) # get embed embed_dict = {} if "embed" in dct: try: embed = discord.Embed.from_dict(dct["embed"]) embed_dict = embed.to_dict() except Exception as e: raise TemplatedError("bad_embed_json", string=string, error=str(e)) if embed_dict == discord.Embed.from_dict({}).to_dict(): raise TemplatedError("empty_embed_json", string=json.dumps(dct, embed=2)) # get text text = "" if "content" in dct: text = str(dct["content"]) # check non-empty if not text and not embed_dict: raise TemplatedError("empty_message_json") return dict(content=text, embed=embed_dict)
def get_rr_type(query, ctx): # inits spl = str(query).strip().split(maxsplit=1) new_query = spl[1] # check for guild if not ctx.guild: raise TemplatedError("no_guild") # get command type sw = lambda x: spl[0].lower().startswith(x.lower()) if sw("msg") or sw("message"): ret = RR_MESSAGE elif sw("role"): ret = RR_ROLE elif sw("emote") or sw("emoji"): ret = RR_EMOTE else: raise TemplatedError("bad_rr_type", value=spl[0]) return ret, new_query
def get_roles(id_list, bot, ctx, message): ret = [] roles = message.guild.roles for x in id_list: e = discord.utils.get(roles, id=int(x)) if e is None: raise TemplatedError("deleted_rr_role", id=x, ctx=ctx, message=message) else: ret.append(e) return ret
def get_emotes(id_list, bot, ctx, message): ret = [] emotes = bot.emojis for x in id_list: try: e = discord.utils.get(emotes, id=int(x)) if e is None: raise TemplatedError("deleted_rr_emote", id=x, ctx=ctx, message=message) else: ret.append(e) except ValueError: ret.append(x) # unicode emoji return ret
async def get_html(logger, link, session=None): from classes.errors import TemplatedError if session is None: session = get_session() try: resp = await session.get(link) except: # todo: logging session = get_session() resp = await session.get(link) logger.info(f'Visiting {link}') if not resp.status == 200: raise TemplatedError("bad_response", link=link, response=resp) else: text = await resp.text(encoding='utf-8', errors='ignore') return text
async def get_all_rr_messsages(query, ctx, bot): messages = [] # check for guild if not ctx.guild: raise TemplatedError("no_guild") # get log log_file = utils.REACTION_ROLE_LOG_DIR + str(ctx.guild.id) + ".json" log = utils.load_json_with_default(log_file) # return existing messages for ch in log: for m in log[ch]: # fetch message try: msg_ch = bot.get_channel(int(ch)) msg = await msg_ch.fetch_message(int(m)) messages.append(msg) except discord.NotFound: pass return messages
async def item(self, ctx): # inits CONFIG = utils.load_yaml(utils.ITEM_CONFIG)['item'] clean_query, keywords = Parse.parse_keywords(ctx.query, copy.deepcopy(base_keys)) keywords['name'].value = clean_query # enforce minimum query length if not cog_utils.check_query_length( keywords, min_length=CONFIG['min_search_length']): raise TemplatedError("short_query") # search and group item_list = item_utils.find_items(keywords) cats = categorize(item_list, "name") # convert to tables del keywords['name'] tables = [ item_utils.to_table("item", cats[x], keywords, dict(name=x)) for x in cats ] # convert to strings table_strings = cog_utils.stringify_tables( tables, header_func=lambda x: x.name) # add table summary for i, x in enumerate(cats.keys()): total_units = sum(y['quantity'] for y in cats[x]) total_price = sum(y['price'] for y in cats[x]) table_strings[ i] += f"# {''.join(['-']*(sum(x.max_width for x in tables[i].columns)+3*len(tables[i].columns)-2))}\n" table_strings[ i] += f"# Total Units: [{total_units:,}] | Total Price: [{Parse.int_to_price(total_price)}]\n" # return return await cog_utils.pageify_and_send(ctx, table_strings, CONFIG)
async def equip(self, ctx): # inits CONFIG = utils.load_yaml(utils.AUCTION_CONFIG)[COG_ID] # get search parameters clean_query, keywords = Parse.parse_keywords( query=ctx.query, keywords=copy.deepcopy(base_keys)) keywords['name'].value = clean_query buy = keywords['buyer'] sell = keywords['seller'] # enforce minimum query length if not Cgu.check_query_length(keywords, min_length=CONFIG['min_search_length']): raise TemplatedError("short_query") # check for buyer and seller keywords while ignoring bools # (which signal the appearance of a column, but do not affect filtering) has_neither= (not buy.has_value and not sell.has_value) or \ (not buy.value and not sell.value) has_both= (buy.value and sell.value) and \ (buy.value is not True and sell.value is not True) # if neither buyer or seller or both, use regular auction search if has_neither or has_both: return await self.equip_search(ctx) else: eq_list = Auct.find_equips(keywords) cats_b = Cgu.categorize(lst=eq_list, key_name="buyer") cats_s = Cgu.categorize(lst=eq_list, key_name="seller") only_buyer = (keywords['buyer'].has_value and keywords['buyer'].value != True and keywords['seller'].value == True) only_seller = (keywords['seller'].has_value and keywords['seller'].value != True and keywords['buyer'].value == True) # if specific buyer or specific seller, use special printout if len(cats_b.keys()) == 1 or only_buyer: del keywords['buyer'] return await self.buy_sell_search(ctx, "buyer", user=list(cats_b.keys())[0], equips=eq_list, keywords=keywords) elif len(cats_s.keys()) == 1 or only_seller: del keywords['seller'] return await self.buy_sell_search(ctx, "buyer", user=list(cats_s.keys())[0], equips=eq_list, keywords=keywords) # else, resort to regular search else: cats = Cgu.categorize(lst=eq_list, key_name="name") return await self.equip_search(ctx, keywords=keywords, cats=cats)