Example #1
0
def get_info(url, show_url=True):
    """ Takes a SCPWiki URL and returns a formatted string """
    try:
        request = requests.get(url)
        request.raise_for_status()
    except (requests.exceptions.HTTPError,
            requests.exceptions.ConnectionError) as e:
        raise SCPError("Error: Unable to fetch URL. ({})".format(e))
    html = request.text
    contents = formatting.strip_html(html)

    try:
        item_id = re.findall("Item #: (.+?)\n", contents, re.S)[0]
        object_class = re.findall("Object Class: (.+?)\n", contents, re.S)[0]
        description = re.findall("Description: (.+?)\n", contents, re.S)[0]
    except IndexError:
        raise SCPError(
            "Error: Invalid or unreadable SCP. Does this SCP exist?")

    description = formatting.truncate(description, 130)
    short_url = web.try_shorten(url)

    # get the title from our pre-generated cache
    if item_id in scp_cache:
        title = scp_cache[item_id][0]
    else:
        title = "Unknown"

    if show_url:
        return "\x02Item Name:\x02 {}, \x02Item #:\x02 {}, \x02Class\x02: {}," \
               " \x02Description:\x02 {} - {}".format(title, item_id, object_class, description, short_url)
    else:
        return "\x02Item Name:\x02 {}, \x02Item #:\x02 {}, \x02Class\x02: {}," \
               " \x02Description:\x02 {}".format(title, item_id, object_class, description)
Example #2
0
def get_data(user):
    """
    Takes a Steam Community ID of a Steam user and returns a dict of data about that user
    :type user: str
    :return: dict
    """
    data = {}

    # form the request
    params = {'xml': 1}

    # get the page
    try:
        profile = http.get_xml(API_URL.format(user),
                               params=params,
                               headers=headers)
    except Exception as e:
        raise SteamError("Could not get user info: {e}".format(e))

    try:
        data["name"] = profile.find('steamID').text
        data["id_64"] = int(profile.find('steamID64').text)
        online_state = profile.find('stateMessage').text
    except AttributeError:
        raise SteamError("Could not get data for this user.")

    online_state = online_state.replace("<br/>",
                                        ": ")  # will make this pretty later
    data["state"] = formatting.strip_html(online_state)

    data["id_32"] = convert_id32(data["id_64"])
    data["id_3"] = convert_id3(data["id_64"])

    return data
Example #3
0
def suggest(text, reply):
    """<phrase> - Gets suggested phrases for a google search"""
    params = {'output': 'json', 'client': 'hp', 'q': text}

    try:
        request = requests.get('http://google.com/complete/search',
                               params=params)
        request.raise_for_status()
    except (requests.exceptions.HTTPError,
            requests.exceptions.ConnectionError) as e:
        reply("Could not get suggestions: {}".format(e))
        raise

    page = request.text

    page_json = page.split('(', 1)[1][:-1]

    suggestions = json.loads(page_json)[1]
    suggestions = [suggestion[0] for suggestion in suggestions]

    if not suggestions:
        return 'No suggestions found.'

    out = formatting.strip_html(", ".join(suggestions))

    return formatting.truncate(out, 200)
Example #4
0
def get_data(user):
    """
    takes a steam user ID and returns a dict containing info about the user
    :type user: str
    :return: dict
    """
    data = {}

    # form the request
    params = {'xml': 1}

    # get the page
    try:
        request = requests.get(API_URL.format(user), params=params)
        request.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        raise SteamError("Could not get user info: {}".format(e))

    profile = etree.fromstring(request.content)

    try:
        data["name"] = profile.find('steamID').text
        data["id_64"] = int(profile.find('steamID64').text)
        online_state = profile.find('stateMessage').text
    except AttributeError:
        raise SteamError("Could not get data for this user.")

    online_state = online_state.replace("<br/>", ": ")  # will make this pretty later
    data["state"] = formatting.strip_html(online_state)

    data["id_32"] = convert_id32(data["id_64"])
    data["id_3"] = convert_id3(data["id_64"])

    return data
Example #5
0
def get_info(url, show_url=True):
    """ Takes a SCPWiki URL and returns a formatted string """
    try:
        request = requests.get(url)
        request.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        raise SCPError("Error: Unable to fetch URL. ({})".format(e))
    html = request.text
    contents = formatting.strip_html(html)

    try:
        item_id = re.findall("Item #: (.+?)\n", contents, re.S)[0]
        object_class = re.findall("Object Class: (.+?)\n", contents, re.S)[0]
        description = re.findall("Description: (.+?)\n", contents, re.S)[0]
    except IndexError:
        raise SCPError("Error: Invalid or unreadable SCP. Does this SCP exist?")

    description = formatting.truncate(description, 130)
    short_url = web.try_shorten(url)

    # get the title from our pre-generated cache
    if item_id in scp_cache:
        title = scp_cache[item_id][0]
    else:
        title = "Unknown"

    if show_url:
        return "\x02Item Name:\x02 {}, \x02Item #:\x02 {}, \x02Class\x02: {}," \
               " \x02Description:\x02 {} - {}".format(title, item_id, object_class, description, short_url)
    else:
        return "\x02Item Name:\x02 {}, \x02Item #:\x02 {}, \x02Class\x02: {}," \
               " \x02Description:\x02 {}".format(title, item_id, object_class, description)
Example #6
0
def format_game(app_id, show_url=True):
    """
    Takes a Steam Store app ID and returns a formatted string with data about that app ID
    :type app_id: string
    :return: string
    """
    params = {'appids': app_id}

    try:
        data = http.get_json(API_URL, params=params, timeout=15)
    except Exception as e:
        return f"Could not get game info: {e}"

    game = data[app_id]["data"]

    # basic info
    out = ["\x02{}\x02".format(game["name"])]

    desc = " ".join(formatting.strip_html(game["about_the_game"]).split())
    out.append(formatting.truncate(desc, 75))

    # genres
    try:
        genres = ", ".join([g['description'] for g in game["genres"]])
        out.append("\x02{}\x02".format(genres))
    except KeyError:
        # some things have no genre
        pass

    # release date
    if game['release_date']['coming_soon']:
        out.append("coming \x02{}\x02".format(game['release_date']['date']))
    else:
        out.append("released \x02{}\x02".format(game['release_date']['date']))

    # pricing
    if game['is_free']:
        out.append("\x02free\x02")
    elif not game.get("price_overview"):
        # game has no pricing, it's probably not released yet
        pass
    else:
        price = game['price_overview']

        # the steam API sends prices as an int like "9999" for $19.99, we divmod to get the actual price
        if price['final'] == price['initial']:
            out.append("\x02$%d.%02d\x02" % divmod(price['final'], 100))
        else:
            price_now = "$%d.%02d" % divmod(price['final'], 100)
            price_original = "$%d.%02d" % divmod(price['initial'], 100)

            out.append("\x02{}\x02 (was \x02{}\x02)".format(price_now, price_original))

    if show_url:
        url = web.try_shorten(STORE_URL.format(game['steam_appid']))
        out.append(url)

    return " - ".join(out)
Example #7
0
def horoscope(text, db, bot, notice, nick):
    """<sign> - get your horoscope"""

    headers = {'User-Agent': bot.user_agent}

    # check if the user asked us not to save his details
    dontsave = text.endswith(" dontsave")
    if dontsave:
        sign = text[:-9].strip().lower()
    else:
        sign = text

    db.execute("create table if not exists horoscope(nick primary key, sign)")

    if not sign:
        sign = db.execute(
            "select sign from horoscope where "
            "nick=lower(:nick)", {
                'nick': nick
            }).fetchone()
        if not sign:
            notice("horoscope <sign> -- Get your horoscope")
            return
        sign = sign[0]

    url = "http://my.horoscope.com/astrology/free-daily-horoscope-{}.html".format(
        sign)

    try:
        request = requests.get(url, headers=headers)
        request.raise_for_status()
    except (requests.exceptions.HTTPError,
            requests.exceptions.ConnectionError) as e:
        return "Could not get horoscope: {}.".format(e)

    soup = BeautifulSoup(request.text)

    title = soup.find_all('h1', {'class': 'h1b'})
    if not title:
        return "Could not get the horoscope for {}.".format(text)

    title = title[1]
    horoscope_text = soup.find('div', {'class': 'fontdef1'})
    result = "\x02{}\x02 {}".format(title, horoscope_text)
    result = formatting.strip_html(result)

    if text and not dontsave:
        db.execute(
            "insert or replace into horoscope(nick, sign) values (:nick, :sign)",
            {
                'nick': nick.lower(),
                'sign': sign
            })
        db.commit()

    return result
Example #8
0
def format_data(app_id, show_url=True):
    """
    takes a steam appid and returns a formatted string with info
    :param appid: string
    :return: string
    """
    params = {'appids': app_id}

    try:
        request = requests.get(API_URL, params=params)
        request.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        return "Could not get game info: {}".format(e)

    data = request.json()
    game = data[app_id]["data"]

    out = []

    # basic info
    out.append("\x02{}\x02".format(game["name"]))

    desc = formatting.strip_html(game["about_the_game"])
    out.append(formatting.truncate_str(desc, 70))

    # genres
    genres = ", ".join([g['description'] for g in game["genres"]])
    out.append("\x02{}\x02".format(genres))

    # release date
    if game['release_date']['coming_soon']:
        out.append("coming \x02{}\x02".format(game['release_date']['date']))
    else:
        out.append("released \x02{}\x02".format(game['release_date']['date']))

    # pricing
    if game['is_free']:
        out.append("\x02free\x02")
    else:
        price = game['price_overview']

        if price['final'] == price['initial']:
            out.append("\x02$%d.%02d\x02" % divmod(price['final'], 100))
        else:
            price_now = "$%d.%02d" % divmod(price['final'], 100)
            price_original = "$%d.%02d" % divmod(price['initial'], 100)

            out.append("\x02{}\x02 (was \x02{}\x02)".format(price_now, price_original))

    if show_url:
        url = web.try_shorten(STORE_URL.format(game['steam_appid']))
        out.append(url)

    return " - ".join(out)
Example #9
0
def horoscope(text, db, bot, notice, nick):
    """<sign> - get your horoscope"""

    headers = {'User-Agent': bot.user_agent}

    # check if the user asked us not to save his details
    dontsave = text.endswith(" dontsave")
    if dontsave:
        sign = text[:-9].strip().lower()
    else:
        sign = text

    db.execute("create table if not exists horoscope(nick primary key, sign)")

    if not sign:
        sign = db.execute("select sign from horoscope where "
                          "nick=lower(:nick)", {'nick': nick}).fetchone()
        if not sign:
            notice("horoscope <sign> -- Get your horoscope")
            return
        sign = sign[0]

    url = "http://my.horoscope.com/astrology/free-daily-horoscope-{}.html".format(sign)

    try:
        request = requests.get(url, headers=headers)
        request.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        return "Could not get horoscope: {}.".format(e)

    soup = BeautifulSoup(request.text)

    title = soup.find_all('h1', {'class': 'h1b'})
    if not title:
        return "Could not get the horoscope for {}.".format(text)

    title = title[1]
    horoscope_text = soup.find('div', {'class': 'fontdef1'})
    result = "\x02{}\x02 {}".format(title, horoscope_text)
    result = formatting.strip_html(result)

    if text and not dontsave:
        db.execute("insert or replace into horoscope(nick, sign) values (:nick, :sign)",
                   {'nick': nick.lower(), 'sign': sign})
        db.commit()

    return result
Example #10
0
def horoscope(text, db, notice, nick):
    """<sign> - get your horoscope"""

    # check if the user asked us not to save his details
    dontsave = text.endswith(" dontsave")
    if dontsave:
        sign = text[:-9].strip().lower()
    else:
        sign = text

    db.execute("create table if not exists horoscope(nick primary key, sign)")

    if not sign:
        sign = db.execute("select sign from horoscope where "
                          "nick=lower(:nick)", {'nick': nick}).fetchone()
        if not sign:
            notice("horoscope <sign> -- Get your horoscope")
            return
        sign = sign[0]

    url = "http://my.horoscope.com/astrology/free-daily-horoscope-{}.html".format(sign)
    soup = http.get_soup(url)

    title = soup.find_all('h1', {'class': 'h1b'})[1]
    horoscope_text = soup.find('div', {'class': 'fontdef1'})
    result = "\x02{}\x02 {}".format(title, horoscope_text)
    result = formatting.strip_html(result)
    # result = unicode(result, "utf8").replace('flight ','')

    if not title:
        return "Could not get the horoscope for {}.".format(text)

    if text and not dontsave:
        db.execute("insert or replace into horoscope(nick, sign) values (:nick, :sign)",
                   {'nick': nick.lower(), 'sign': sign})
        db.commit()

    return result
Example #11
0
def suggest(text):
    """suggest <term> -- Retrieves a list of suggested terms for a google search"""
    params = {"output": "json", "client": "hp", "q": text}

    try:
        request = requests.get("http://google.com/complete/search", params=params)
        request.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        return "Could not get suggestions: {}".format(e)

    page = request.text

    page_json = page.split("(", 1)[1][:-1]

    suggestions = json.loads(page_json)[1]
    suggestions = [suggestion[0] for suggestion in suggestions]

    if not suggestions:
        return "No suggestions found."

    out = formatting.strip_html(", ".join(suggestions))

    return formatting.truncate(out, 200)
Example #12
0
def suggest(text):
    """suggest <phrase> -- Gets suggested phrases for a google search"""
    params = {'output': 'json', 'client': 'hp', 'q': text}

    try:
        request = requests.get('http://google.com/complete/search',
                               params=params)
        request.raise_for_status()
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        return "Could not get suggestions: {}".format(e)

    page = request.text

    page_json = page.split('(', 1)[1][:-1]

    suggestions = json.loads(page_json)[1]
    suggestions = [suggestion[0] for suggestion in suggestions]

    if not suggestions:
        return 'No suggestions found.'

    out = formatting.strip_html(", ".join(suggestions))

    return formatting.truncate(out, 200)
Example #13
0
def test_strip_html():
    assert strip_html(test_strip_html_input) == test_strip_html_result
def test_strip_html():
    assert strip_html(test_strip_html_input) == test_strip_html_result
Example #15
0
def format_item(item):
    url = web.try_shorten(item.link)
    title = formatting.strip_html(item.title)
    return "{} ({})".format(title, url)
Example #16
0
def format_item(item):
    url = web.try_shorten(item.link)
    title = formatting.strip_html(item.title)
    return "{} ({})".format(
        title, url)