Beispiel #1
0
def format_output(item, show_url=False):
    """ takes a voat post and returns a formatted string """
    if not item["Title"]:
        item["Title"] = formatting.truncate(item["Linkdescription"], 70)
    else:
        item["Title"] = formatting.truncate(item["Title"], 70)
    item["link"] = voat_fill_url.format(item["Subverse"], item["Id"])

    raw_time = isodate.parse_date(item['Date'])
    item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True)

    item["comments"] = formatting.pluralize(item["CommentCount"], 'comment')
    item["points"] = formatting.pluralize(item["Likes"], 'point')

    if item["Type"] == 2:
        item["warning"] = " \x02Link\x02"
    else:
        item["warning"] = ""

    if show_url:
        return "\x02{Title} : {Subverse}\x02 - {comments}, {points}" \
               " - \x02{Name}\x02 {timesince} ago - {link}{warning}".format(**item)
    else:
        return "\x02{Title} : {Subverse}\x02 - {comments}, {points}" \
               " - \x02{Name}\x02, {timesince} ago{warning}".format(**item)
Beispiel #2
0
def format_output(item, show_url=False):
    """ takes a voat post and returns a formatted string """
    if not item["Title"]:
        item["Title"] = formatting.truncate(item["Linkdescription"], 70)
    else:
        item["Title"] = formatting.truncate(item["Title"], 70)
    item["link"] = voat_fill_url.format(item["Subverse"], item["Id"])

    raw_time = isodate.parse_date(item["Date"])
    item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True)

    item["comments"] = formatting.pluralize(item["CommentCount"], "comment")
    item["points"] = formatting.pluralize(item["Likes"], "point")

    if item["Type"] == 2:
        item["warning"] = " \x02Link\x02"
    else:
        item["warning"] = ""

    if show_url:
        return (
            "\x02{Title} : {Subverse}\x02 - {comments}, {points}"
            " - \x02{Name}\x02 {timesince} ago - {link}{warning}".format(**item)
        )
    else:
        return (
            "\x02{Title} : {Subverse}\x02 - {comments}, {points}"
            " - \x02{Name}\x02, {timesince} ago{warning}".format(**item)
        )
Beispiel #3
0
def get_video_description(video_id):
    global time_last_request
    time_elapsed = time.time() - time_last_request
    if time_elapsed > 10:

        time_last_request = time.time()
    else:
        #return "This looks like a YouTube video. However, the YT api have been called too much, I'm sorry I won't be able to fetch details for you."
        return None
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get('error'):
        if json['error']['code'] == 403:
            return err_no_api
        else:
            return

    data = json['items']
    snippet = data[0]['snippet']
    statistics = data[0]['statistics']
    content_details = data[0]['contentDetails']

    out = '\x02{}\x02'.format(snippet['title'])

    if not content_details.get('duration'):
        return out

    length = isodate.parse_duration(content_details['duration'])
    out += ' - length \x02{}\x02'.format(timeformat.format_time(int(length.total_seconds()), simple=True))
    total_votes = float(statistics['likeCount']) + float(statistics['dislikeCount'])

    if total_votes != 0:
        # format
        likes = pluralize(int(statistics['likeCount']), "like")
        dislikes = pluralize(int(statistics['dislikeCount']), "dislike")

        percent = 100 * float(statistics['likeCount']) / total_votes
        likes = parse("$(dark_green)" + likes + "$(clear)")
        dislikes = parse("$(dark_red)" + dislikes + "$(clear)")
        out += ' - {}, {} (\x02{:.1f}\x02%)'.format(likes,
                                                    dislikes, percent)

    if 'viewCount' in statistics:
        views = int(statistics['viewCount'])
        out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1:])

    uploader = snippet['channelTitle']

    upload_time = time.strptime(snippet['publishedAt'], "%Y-%m-%dT%H:%M:%S.000Z")
    out += ' - \x02{}\x02 on \x02{}\x02'.format(uploader,
                                                time.strftime("%Y.%m.%d", upload_time))

    if 'contentRating' in content_details:
        out += ' - \x034NSFW\x02'

    # return re.sub(
    #		r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))',
    #		'[URL]', out)

    return out.replace("youtu", "you tu") #nup. No spam please
Beispiel #4
0
def format_output(item, show_url=False):
    """ takes a reddit post and returns a formatted string """
    item["title"] = formatting.truncate(item["title"], 70)
    item["link"] = short_url.format(item["id"])

    raw_time = datetime.fromtimestamp(int(item["created_utc"]))
    item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True)

    item["comments"] = formatting.pluralize(item["num_comments"], "comment")
    item["points"] = formatting.pluralize(item["score"], "point")

    if item["over_18"]:
        item["warning"] = " \x02NSFW\x02"
    else:
        item["warning"] = ""

    if show_url:
        return (
            "\x02{title} : {subreddit}\x02 - {comments}, {points}"
            " - \x02{author}\x02 {timesince} ago - {link}{warning}".format(**item)
        )
    else:
        return (
            "\x02{title} : {subreddit}\x02 - {comments}, {points}"
            " - \x02{author}\x02, {timesince} ago{warning}".format(**item)
        )
Beispiel #5
0
def get_video_description(video_id):
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get('error'):
        if json['error']['code'] == 403:
            return err_no_api
        else:
            return

    data = json['items']
    snippet = data[0]['snippet']
    statistics = data[0]['statistics']
    content_details = data[0]['contentDetails']

    out = '\x02{}\x02'.format(snippet['title'])

    if not content_details.get('duration'):
        return out

    length = isodate.parse_duration(content_details['duration'])
    out += ' - length \x02{}\x02'.format(
        timeformat.format_time(int(length.total_seconds()), simple=True))
    try:
        total_votes = (float(statistics['likeCount']) +
                       float(statistics['dislikeCount']))
    except KeyError:
        total_votes = "N/A"

    if total_votes != 0:
        # format
        try:
            likes = pluralize(int(statistics['likeCount']), "like")
            dislikes = pluralize(int(statistics['dislikeCount']), "dislike")
            percent = 100 * float(statistics['likeCount']) / total_votes

            out += ' - {}, {} (\x02{:.1f}\x02%)'.format(
                likes, dislikes, percent)
        except (KeyError, ValueError):
            out += ' - {}, {}, (\x02{})'.format('N/A', 'N/A', 'N/A')

    if 'viewCount' in statistics:
        views = int(statistics['viewCount'])
        out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1:])

    uploader = snippet['channelTitle']

    upload_time = time.strptime(snippet['publishedAt'],
                                "%Y-%m-%dT%H:%M:%S.000Z")
    out += ' - \x02{}\x02 on \x02{}\x02'.format(
        uploader, time.strftime("%Y.%m.%d", upload_time))

    if 'contentRating' in content_details:
        out += ' - \x034NSFW\x02'

    return out
Beispiel #6
0
def get_video_description(video_id):
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get('error'):
        if json['error']['code'] == 403:
            return err_no_api
        else:
            return

    data = json['items']
    snippet = data[0]['snippet']
    statistics = data[0]['statistics']
    content_details = data[0]['contentDetails']

    out = '\x02{}\x02'.format(snippet['title'])

    if not content_details.get('duration'):
        return out

    length = isodate.parse_duration(content_details['duration'])
    out += ' - length \x02{}\x02'.format(timeformat.format_time(int(length.total_seconds()), simple=True))
    try:
        total_votes = (float(statistics['likeCount']) +
                       float(statistics['dislikeCount']))
    except KeyError:
        total_votes = "N/A"

    if total_votes != 0:
        # format
        try:
            likes = pluralize(int(statistics['likeCount']), "like")
            dislikes = pluralize(int(statistics['dislikeCount']), "dislike")
            percent = 100 * float(statistics['likeCount']) / total_votes

            out += ' - {}, {} (\x02{:.1f}\x02%)'.format(likes,
                                                        dislikes, percent)
        except (KeyError, ValueError):
            out += ' - {}, {}, (\x02{})'.format('N/A', 'N/A', 'N/A')

    if 'viewCount' in statistics:
        views = int(statistics['viewCount'])
        out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1:])

    uploader = snippet['channelTitle']

    upload_time = time.strptime(snippet['publishedAt'], "%Y-%m-%dT%H:%M:%S.000Z")
    out += ' - \x02{}\x02 on \x02{}\x02'.format(uploader,
                                                time.strftime("%Y.%m.%d", upload_time))

    if 'contentRating' in content_details:
        out += ' - \x034NSFW\x02'

    return out
Beispiel #7
0
def karma(text):
    """karma <reddituser> will return the information about the specified reddit username"""
    user = text
    url = user_url + "about.json"
    r = requests.get(url.format(user), headers=agent)
    if r.status_code != 200:
        return statuscheck(r.status_code, user)
    data = r.json()
    out = "$(b){}$(b) ".format(user)
    out += "$(b){:,}$(b) link karma and ".format(data['data']['link_karma'])
    out += "$(b){:,}$(b) comment karma | ".format(
        data['data']['comment_karma'])
    if data['data']['is_gold']:
        out += "has reddit gold | "
    if data['data']['is_mod']:
        out += "is a moderator | "
    if data['data']['has_verified_email']:
        out += "email has been verified | "
    out += "cake day is {} | ".format(
        datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d'))
    account_age = datetime.now() - datetime.fromtimestamp(
        data['data']['created'])
    age = account_age.days
    age_unit = "day"
    if age > 365:
        age //= 365
        age_unit = "year"
    out += "redditor for {}.".format(pluralize(age, age_unit))
    return colors.parse(out)
Beispiel #8
0
def get_video_description(video_id):
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get("error"):
        if json["error"]["code"] == 403:
            return err_no_api
        else:
            return

    data = json["items"]
    snippet = data[0]["snippet"]
    statistics = data[0]["statistics"]
    content_details = data[0]["contentDetails"]

    out = "\x02{}\x02".format(snippet["title"])

    if not content_details.get("duration"):
        return out

    length = isodate.parse_duration(content_details["duration"])
    out += " - length \x02{}\x02".format(timeformat.format_time(int(length.total_seconds()), simple=True))
    total_votes = float(statistics["likeCount"]) + float(statistics["dislikeCount"])

    if total_votes != 0:
        # format
        likes = pluralize(int(statistics["likeCount"]), "like")
        dislikes = pluralize(int(statistics["dislikeCount"]), "dislike")

        percent = 100 * float(statistics["likeCount"]) / total_votes
        out += " - {}, {} (\x02{:.1f}\x02%)".format(likes, dislikes, percent)

    if "viewCount" in statistics:
        views = int(statistics["viewCount"])
        out += " - \x02{:,}\x02 view{}".format(views, "s"[views == 1 :])

    uploader = snippet["channelTitle"]

    upload_time = time.strptime(snippet["publishedAt"], "%Y-%m-%dT%H:%M:%S.000Z")
    out += " - \x02{}\x02 on \x02{}\x02".format(uploader, time.strftime("%Y.%m.%d", upload_time))

    if "contentRating" in content_details:
        out += " - \x034NSFW\x02"

    return out
Beispiel #9
0
def get_video_description(video_id):
    json = requests.get(api_url.format(video_id)).json()

    if json.get('error'):
        return

    data = json['data']

    out = '\x02{}\x02'.format(data['title'])

    if not data.get('duration'):
        return out

    length = data['duration']
    out += ' - length \x02{}\x02'.format(timeformat.format_time(length, simple=True))

    if 'ratingCount' in data:
        # format
        likes = pluralize(int(data['likeCount']), "like")
        dislikes = pluralize(data['ratingCount'] - int(data['likeCount']), "dislike")

        percent = 100 * float(data['likeCount']) / float(data['ratingCount'])
        out += ' - {}, {} (\x02{:.1f}\x02%)'.format(likes,
                                                    dislikes, percent)

    if 'viewCount' in data:
        views = data['viewCount']
        out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1:])

    try:
        json = requests.get(base_url + "users/{}?alt=json".format(data["uploader"])).json()
        uploader = json["entry"]["author"][0]["name"][
            "$t"]
    except:
        uploader = data["uploader"]

    upload_time = time.strptime(data['uploaded'], "%Y-%m-%dT%H:%M:%S.000Z")
    out += ' - \x02{}\x02 on \x02{}\x02'.format(uploader,
                                                time.strftime("%Y.%m.%d", upload_time))

    if 'contentRating' in data:
        out += ' - \x034NSFW\x02'

    return out
Beispiel #10
0
def karma(text, db):
    """k/karma <nick> -- returns karma stats for <nick>"""
    query = db.execute(
        select([karma_table])
        .where(karma_table.c.nick_vote == text.lower())
    ).fetchone()

    if not query:
        return "That user has no karma :("
    else:
        karma_text = formatting.pluralize(query['up_karma'] - query['down_karma'], '\x02karma')
        return "{} has \x02{}\x02 karma!".format(text, query['up_karma'] - query['down_karma'])
Beispiel #11
0
def format_output(item, show_url=False):
    """ takes a reddit post and returns a formatted string """
    item["title"] = formatting.truncate(item["title"], 70)
    item["link"] = short_url.format(item["id"])

    raw_time = datetime.fromtimestamp(int(item["created_utc"]))
    item["timesince"] = timeformat.time_since(raw_time, count=1, simple=True)

    item["comments"] = formatting.pluralize(item["num_comments"], 'comment')
    item["points"] = formatting.pluralize(item["score"], 'point')

    if item["over_18"]:
        item["warning"] = " \x02NSFW\x02"
    else:
        item["warning"] = ""

    if show_url:
        return "\x02{title} : {subreddit}\x02 - {comments}, {points}" \
               " - \x02{author}\x02 {timesince} ago - {link}{warning}".format(**item)
    else:
        return "\x02{title} : {subreddit}\x02 - {comments}, {points}" \
               " - \x02{author}\x02, {timesince} ago{warning}".format(**item)
Beispiel #12
0
def karma(text, chan, db):
    """k/karma <nick> -- returns karma stats for <nick>"""

    if not chan.startswith('#'):
        return

    nick_vote = text

    query = db.execute(
        select([karma_table])
        .where(karma_table.c.nick_vote == nick_vote.lower())
    ).fetchall()

    if not query:
        return "That user has no karma."
    else:
        query = query[0]
        karma_text = formatting.pluralize(query['up_karma'] - query['down_karma'], 'karma point')
        return "{} has {}.".format(nick_vote, karma_text)
Beispiel #13
0
def cake_day(text):
    """cakeday <reddituser> will return the cakeday for the given reddit username."""
    user = text
    url = user_url + "about.json"
    r = requests.get(url.format(user), headers=agent)
    if r.status_code != 200:
        return statuscheck(r.status_code, user)
    data = r.json()
    out = colors.parse("$(b){}'s$(b) ".format(user))
    out += "cake day is {}, ".format(
        datetime.fromtimestamp(data['data']['created_utc']).strftime('%B %d'))
    account_age = datetime.now() - datetime.fromtimestamp(
        data['data']['created'])
    age = account_age.days
    age_unit = "day"
    if age > 365:
        age //= 365
        age_unit = "year"
    out += "they have been a redditor for {}.".format(pluralize(age, age_unit))
    return out
Beispiel #14
0
def karma(text, chan, db):
    """k/karma <nick> | list -- returns karma stats for <nick>. list returns top 5 karma."""

    if not chan.startswith('#'):
        return

    nick_vote = text

    if nick_vote != "list":

        query = db.execute(
            select([
                karma_table
            ]).where(karma_table.c.nick_vote == nick_vote.lower())).fetchall()

        if not query:
            return "That user has no karma."
        else:
            query = query[0]
            karma_text = formatting.pluralize(
                query['up_karma'] - query['down_karma'], 'karma point')
            return "{} has {}.".format(nick_vote, karma_text)
    else:
        query = db.execute(
            select([karma_table]).order_by(
                karma_table.c.total_karma.desc()).limit(5)).fetchall()

        if not query:
            return "No karma registered yet."
        else:
            output = "Five users with most karma:"
            for q in query:
                total_karma = str(q['total_karma'])
                nick_vote = str(q['nick_vote'])
                output += "\n" + nick_vote + " has " + total_karma + " karma."

            return output
Beispiel #15
0
def test_pluralize():
    assert pluralize(test_pluralize_num_a,
                     test_pluralize_text) == test_pluralize_result_a
    assert pluralize(test_pluralize_num_b,
                     test_pluralize_text) == test_pluralize_result_b
def test_pluralize():
    assert pluralize(test_pluralize_num_a, test_pluralize_text) == test_pluralize_result_a
    assert pluralize(test_pluralize_num_b, test_pluralize_text) == test_pluralize_result_b