Пример #1
0
def parse_pob(author, content, minify=False):
    """
    Trigger the parsing of the pastebin link, pass it to the output creating object and send a message back
    :param channel: receiving channel
    :param author: user sending the message
    :param paste_key: pastebin paste key
    :param argument: optional: arguments to determine the output
    :return:
    """
    paste_key = pastebin.fetch_paste_key(content)
    if paste_key:
        xml = None
        log.info("Parsing pastebin with key={}".format(paste_key))

        try:
            xml = pastebin.get_as_xml(paste_key)
        except HTTPError as err:
            log.error("Invalid pastebin-url msg={}".format(err))
        if xml:
            parser = Parser()
            build = parser.parse_build(xml)
            # print(build)

            embed = pob_output.generate_response(author,
                                                 build,
                                                 minified=minify)

            log.debug("embed={}; length={}".format(embed, embed.__sizeof__()))
            return embed
Пример #2
0
def decode_to_xml(enc):
    enc = enc.replace("-", "+").replace("_", "/")
    xml_str = decode_base64_and_inflate(enc)
    log.debug("XML={}".format(xml_str))
    xml = None
    try:
        xml = ET.fromstring(xml_str)
    except TypeError as err:
        log.debug("Could not parse the pastebin as xml msg={}".format(err))

    return xml
Пример #3
0
def _call_sage(endpoint: str, payload: dict) -> Optional[float]:
    log.debug("Calling sage")
    try:
        r = requests.get(
            endpoint,
            auth=(sage_user, sage_password),
            params=payload,
            timeout=sage_timeout,
            verify=False,
        )
    except ConnectTimeout:
        log.error("Connection timeout connecting to Sage")
        raise SageException("Timed out connecting to Sage")
    except TimeoutError:
        log.error("Connection timeout connecting to Sage")
        raise SageException("Timed out communicating with Sage")
    except Exception as e:
        log.error(f"Error communicating with Sage: {e}")
        raise SageException(f"Error communicating with Sage: {e}")

    log.debug(f"Sage returned a status of {r.status_code}")
    if r.status_code != 200:
        log.error(f"Sage returned an error status of: ({r.status_code}) {r.reason}")
        raise SageException(f"Sage returned an error status of: ({r.status_code}) {r.reason}")

    try:
        r.encoding = 'utf-8-sig'
        j = r.json()
    except Exception as e:
        log.error(f"Sage did not return a valid json response: {e}")
        raise SageException(f"Sage did not return a valid json response: {e}")

    try:
        sage_response = SageResponse(**j)
    except ValidationError as e:
        log.error(f"Validation of Sage response failed: {e}")
        raise SageException(f"Validation of Sage response failed: {e}")

    if len(sage_response.resources) == 0:
        return None
    return sage_response.resources[0].cost
Пример #4
0
async def on_message(message):
    """
    Handle message events
    :param message:
    :return: None
    """
    # call bot commands, if not a bot command, check the message for pastebins
    # better way to do this would probably be to create the context, then check if its valid, then invoke it. If its valid,its a command, if not, its not. You could backport this to async pretty ez

    # todo: replace async with rewrite of the bot, then use on_command_completion
    if message.channel.name in config.active_channels \
            and not util.starts_with("!pob", message.content[:4]) \
            and "pastebin.com/" in message.content:
        # check if valid xml
        # send message
        log.debug("A| {}: {}".format(message.channel, message.content))
        embed = parse_pob(message.author, message.content, minify=True)
        if embed:
            await bot.send_message(message.channel, embed=embed)
    else:
        await bot.process_commands(message)
Пример #5
0
def shrink_tree_url(tree):
    """
    Shrink url with poeurl
    :param tree:
    :return:
    """
    # sanitize
    tree = tree.strip()

    # build requesturl
    param = '{"url":"' + tree + '"}'
    url = 'http://poeurl.com/api/?shrink=' + param
    log.debug("Poeurl payload={}".format(url))

    contents = urllib.request.urlopen(url).read().decode('utf-8')
    log.debug("Poeurl contents={}".format(contents))

    contents = json.loads(contents)
    log.debug("Got json content from poeurl ... {}".format(contents))
    if contents['url']:
        return 'http://poeurl.com/' + contents['url']
    else:
        raise ValueError("Unable to retrieve URL")
Пример #6
0
def get_as_xml(paste_key):
    raw_url = 'https://pastebin.com/raw/' + paste_key
    log.debug("Retrieved from raw_url={}".format(raw_url))
    data = get_raw_data(raw_url)
    return decode_to_xml(data)