Beispiel #1
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
    """
    try:
        data = http.get_json(API_URL, appids=app_id)
    except Exception as e:
        return "Could not get game info: {}".format(e)

    game = data[app_id]["data"]
    out = []

    # basic info
    out.append(u"\x02{}\x02".format(game["name"]))
    desc = text.strip_html(game["about_the_game"])
    #out.append(text.truncate_str(desc, 70))

    # genres
    out.append(u", ".join([g['description'] for g in game["genres"]]))

    # pricing
    if game['is_free']:
        out.append(u"\x02free\x02")
    elif game.get('price_overview', False):
        price = game['price_overview']

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

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

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

    # url
    if show_url:
        url = web.try_googl(STORE_URL.format(game['steam_appid']))
        out.insert(0, url)

    return u" - ".join(out)
Beispiel #2
0
def horoscope(inp, db=None, notice=None, nick=None):
    """horoscope <sign> -- Get your horoscope."""

    if not db_ready:
        db_init(db)

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

    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, )).fetchone()
        if not sign:
            notice(horoscope.__doc__)
            return
        sign = sign[0]

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

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

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

    if inp and not dontsave:
        db.execute("insert or replace into horoscope(nick, sign) values (?,?)",
                   (nick.lower(), sign))
        db.commit()

    return result
Beispiel #3
0
def extractsms(htmlsms):
    """
    extractsms  --  extract SMS messages from BS4 tree of Google Voice SMS HTML
    Output is a list of dictionaries, one per message.
    """
    msgitems = []  # accum message items here
    # Extract all conversations by searching for a DIV with an ID at top level.
    tree = BeautifulSoup.BeautifulSoup(htmlsms)   # parse HTML into tree
    conversations = tree.findAll("div", attrs={"id": True}, recursive=False)
    for conversation in conversations:
        #   For each conversation, extract each row, which is one SMS message.
        rows = conversation.findAll(attrs={"class": "gc-message-sms-row"})
        for row in rows:  # for all rows
            #   For each row, which is one message, extract all the fields.
            msgitem = {"id": conversation["id"]}  # tag msg with ID
            spans = row.findAll("span", attrs={"class": True},
                                recursive=False)
            for span in spans:  # for all spans in row
                cl = span["class"].replace('gc-message-sms-', '')
                # put text in dict
                msgitem[cl] = (" ".join(span.findAll(text=True))).strip()
            msgitem['text'] = text.strip_html(msgitem['text'])  # convert html
            msgitems.append(msgitem)  # add msg dictionary to list
    return msgitems
Beispiel #4
0
def steamcalc(inp, reply=None):
    """steamcalc <username> [currency] - Gets value of steam account and
       total hours played. Uses steamcommunity.com/id/<nickname>. """

    name = inp.strip()

    try:
        request = get_data(name)
        do_refresh = True
    except (http.HTTPError, http.URLError):
        try:
            reply("Collecting data, this may take a while.")
            refresh_data(name)
            request = get_data(name)
            do_refresh = False
        except (http.HTTPError, http.URLError):
            return "Could not get data for this user."

    csv_data = StringIO.StringIO(request)  # we use StringIO because CSV can't read a string
    reader = unicode_dictreader(csv_data)

    # put the games in a list
    games = []
    for row in reader:
        games.append(row)

    data = {}

    # basic information
    steam_profile = http.get_xml(steam_api_url.format(name))
    try:
        data["name"] = steam_profile.find('steamID').text
        online_state = steam_profile.find('stateMessage').text
    except AttributeError:
        return "Could not get data for this user."

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

    # work out the average metascore for all games
    ms = [float(game["metascore"]) for game in games if is_number(game["metascore"])]
    metascore = float(sum(ms)) / len(ms) if len(ms) > 0 else float('nan')
    data["average_metascore"] = "{0:.1f}".format(metascore)

    # work out the totals
    data["games"] = len(games)

    total_value = sum([float(game["value"]) for game in games if is_number(game["value"])])
    data["value"] = str(int(round(total_value)))

    # work out the total size
    total_size = 0.0

    for game in games:
        if not is_number(game["size"]):
            continue

        if game["unit"] == "GB":
            total_size += float(game["size"])
        else:
            total_size += float(game["size"]) / 1024

    data["size"] = "{0:.1f}".format(total_size)

    reply("{name} ({state}) has {games} games with a total value of ${value}"
           " and a total size of {size}GB! The average metascore for these"
           " games is {average_metascore}.".format(**data))

    if do_refresh:
        refresh_data(name)