Ejemplo n.º 1
0
def youtime(text, reply):
    """<query> - Gets the total run time of the first YouTube search result for <query>."""
    video_id, err = get_video_id(reply, text)
    if err:
        return err

    dev_key = bot.config.get_api_key('google_dev_key')
    request = requests.get(api_url.format(video_id, dev_key))
    request.raise_for_status()

    json = request.json()

    if json.get('error'):
        return
    data = json['items']
    snippet = data[0]['snippet']
    content_details = data[0]['contentDetails']
    statistics = data[0]['statistics']

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

    length = isodate.parse_duration(content_details['duration'])
    l_sec = int(length.total_seconds())
    views = int(statistics['viewCount'])
    total = int(l_sec * views)

    length_text = timeformat.format_time(l_sec, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           'a total run time of {}!'.format(snippet['title'], length_text, views,
                                            total_text)
Ejemplo n.º 2
0
def youtime(text):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    json = requests.get(search_api_url, params={"q": text}).json()

    if 'error' in json:
        return 'error performing search'

    if json['data']['totalItems'] == 0:
        return 'no results found'

    video_id = json['data']['items'][0]['id']
    json = requests.get(api_url.format(video_id)).json()

    if json.get('error'):
        return
    data = json['data']

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

    length = data['duration']
    views = data['viewCount']
    total = int(length * views)

    length_text = timeformat.format_time(length, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           'a total run time of {}!'.format(data['title'], length_text, views,
                                            total_text)
Ejemplo n.º 3
0
def test_format_time():
    # basic
    assert format_time(120000) == "1 day, 9 hours and 20 minutes"
    assert format_time(120000, simple=True) == "1d 9h 20m"
    # count
    assert format_time(1200003, count=4) == "13 days, 21 hours, 20 minutes and 3 seconds"
    assert format_time(1200000, count=4) == "13 days, 21 hours and 20 minutes"
    assert format_time(1200000, count=2) == "13 days and 21 hours"
Ejemplo n.º 4
0
def test_format_time():
    # basic
    assert format_time(120000) == "1 day, 9 hours and 20 minutes"
    assert format_time(120000, simple=True) == "1d 9h 20m"
    # count
    assert format_time(1200003, count=4) == "13 days, 21 hours, 20 minutes and 3 seconds"
    assert format_time(1200000, count=4) == "13 days, 21 hours and 20 minutes"
    assert format_time(1200000, count=2) == "13 days and 21 hours"
Ejemplo n.º 5
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
Ejemplo n.º 6
0
def format_playlist(playlist, show_url=True):
    """
    Takes a SoundCloud playlist item and returns a formatted string.
    """
    out = "\x02{}\x02".format(playlist['title'])

    if playlist['description']:
        out += ': "{}"'.format(formatting.truncate(playlist['description']))

    if playlist['genre']:
        out += " - \x02{}\x02".format(playlist['genre'])

    out += " - by \x02{}\x02".format(playlist['user']['username'])

    if not playlist['tracks']:
        out += " - No items"
    else:
        out += " - {} items,".format(len(playlist['tracks']))

        seconds = round(int(playlist['duration'])/1000)
        out += " {}".format(timeformat.format_time(seconds, simple=True))

    if show_url:
        out += " - {}".format(web.try_shorten(playlist['permalink_url']))
    return out
Ejemplo n.º 7
0
def format_playlist(playlist, show_url=True):
    """
    Takes a SoundCloud playlist item and returns a formatted string.
    """
    out = "\x02{}\x02".format(playlist['title'])

    if playlist['description']:
        out += ': "{}"'.format(formatting.truncate(playlist['description']))

    if playlist['genre']:
        out += " - \x02{}\x02".format(playlist['genre'])

    out += " - by \x02{}\x02".format(playlist['user']['username'])

    if not playlist['tracks']:
        out += " - No items"
    else:
        out += " - {} items,".format(len(playlist['tracks']))

        seconds = round(int(playlist['duration']) / 1000)
        out += " {}".format(timeformat.format_time(seconds, simple=True))

    if show_url:
        out += " - {}".format(web.try_shorten(playlist['permalink_url']))
    return out
Ejemplo n.º 8
0
async def remind(text, nick, chan, db, conn, event, async_call):
    """<1 minute, 30 seconds>: <do task> - reminds you to <do task> in <1 minute, 30 seconds>"""

    count = len([
        x for x in reminder_cache
        if x[0] == conn.name and x[3] == nick.lower()
    ])

    if text == "clear":
        if count == 0:
            return "You have no reminders to delete."

        await delete_all(async_call, db, conn.name, nick)
        await load_cache(async_call, db)
        return "Deleted all ({}) reminders for {}!".format(count, nick)

    # split the input on the first ":"
    parts = text.split(":", 1)

    if len(parts) == 1:
        # user didn't add a message, send them help
        event.notice_doc()
        return

    if count > 10:
        return "Sorry, you already have too many reminders queued (10), you will need to wait or " \
               "clear your reminders to add any more."

    time_string = parts[0].strip()
    message = colors.strip_all(parts[1].strip())

    # get the current time in both DateTime and Unix Epoch
    current_epoch = time.time()
    current_time = datetime.fromtimestamp(current_epoch)

    # parse the time input, return error if invalid
    seconds = time_parse(time_string)
    if not seconds:
        return "Invalid input."

    if seconds > 2764800 or seconds < 60:
        return "Sorry, remind input must be more than a minute, and less than one month."

    # work out the time to remind the user, and check if that time is in the past
    remind_time = datetime.fromtimestamp(current_epoch + seconds)
    if remind_time < current_time:  # pragma: no cover
        # This should technically be unreachable because of the previous checks
        return "I can't remind you in the past!"

    # finally, add the reminder and send a confirmation message
    await add_reminder(async_call, db, conn.name, nick, chan, message,
                       remind_time, current_time)
    await load_cache(async_call, db)

    remind_text = format_time(seconds, count=2)
    output = "Alright, I'll remind you \"{}\" in $(b){}$(clear)!".format(
        message, remind_text)

    return colors.parse(output)
Ejemplo n.º 9
0
def remind(text, nick, chan, db, conn, notice, async):
    """<1m30s>: <do task> -- reminds you to <do task> in <1 minute, 30 seconds>.If no colon is given, only the first word will be used to determine the time.
    """

    count = len([x for x in reminder_cache if x[0] == conn.name and x[4].lower() == nick.lower()])

    if text == "clear":
        if count == 0:
            return "You have no reminders to delete."

        yield from delete_all(async, db, conn.name, nick)
        yield from load_cache(async, db)
        return "Deleted all ({}) reminders for {}!".format(count, nick)

    if ":" in text:
        # split the input on the first ":"
        parts = text.split(":", 1)
    else:
        # take only the first word for the time value otherwise
        parts = text.split(" ", 1)

    if len(parts) == 1:
        # user didn't add a message, send them help
        notice(remind.__doc__)
        return

    if count > 10:
        notice("Sorry, you already have too many reminders queued (10), you will need to wait or clear your reminders to add any more")
        return

    time_string = parts[0].strip()
    message = colors.strip_all(parts[1].strip())

    # get the current time in both DateTime and Unix Epoch
    current_epoch = time.time()
    current_time = datetime.fromtimestamp(current_epoch)

    # parse the time input, return error if invalid
    seconds = time_parse(time_string)
    if not seconds:
        notice("Invalid time. Try something like '2m30s', '2 days 3 hours:', or '1:30s'")
        return

    if seconds > 2764800 or seconds < 60:
        return "Sorry, remind input must be more than a minute, and less than one month"

    # work out the time to remind the user, and check if that time is in the past
    remind_time = datetime.fromtimestamp(current_epoch + seconds)
    if remind_time < current_time:
        return "I can't remind you in the past!"

    # finally, add the reminder and send a confirmation message
    yield from add_reminder(async, db, conn.name, nick, chan, message, remind_time, current_time)
    yield from load_cache(async, db)

    remind_text = format_time(seconds, count=2)
    output = "Alright, I'll remind you \"{}\" in $(b){}$(clear)!".format(message, remind_text)
    notice(colors.parse(output))
Ejemplo n.º 10
0
def youtime(text):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    if not dev_key:
        return "This command requires a Google Developers Console API key."

    json = requests.get(search_api_url,
                        params={
                            "q": text,
                            "key": dev_key,
                            "type": "video"
                        }).json()

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

    if json['pageInfo']['totalResults'] == 0:
        return 'No results found.'

    video_id = json['items'][0]['id']['videoId']
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get('error'):
        return
    data = json['items']
    snippet = data[0]['snippet']
    content_details = data[0]['contentDetails']
    statistics = data[0]['statistics']

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

    length = isodate.parse_duration(content_details['duration'])
    l_sec = int(length.total_seconds())
    views = int(statistics['viewCount'])
    total = int(l_sec * views)

    length_text = timeformat.format_time(l_sec, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           'a total run time of {}!'.format(snippet['title'], length_text, views,
                                            total_text)
Ejemplo n.º 11
0
def get_video_description(video_id: str) -> str:
    parts = ["statistics", "contentDetails", "snippet"]
    request = get_video(video_id, parts)
    raise_api_errors(request)

    json = request.json()

    data = json["items"]
    if not data:
        raise NoResultsError()

    item = data[0]
    snippet = item["snippet"]
    statistics = item["statistics"]
    content_details = item["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 (LookupError, ValueError):
        total_votes = 0

    if total_votes != 0:
        # format
        likes = pluralize_suffix(int(statistics["likeCount"]), "like")
        dislikes = pluralize_suffix(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 = isodate.parse_datetime(snippet["publishedAt"])
    out += " - \x02{}\x02 on \x02{}\x02".format(
        uploader, upload_time.strftime("%Y.%m.%d"))

    try:
        yt_rating = content_details["contentRating"]["ytRating"]
    except KeyError:
        pass
    else:
        if yt_rating == "ytAgeRestricted":
            out += colors.parse(" - $(red)NSFW$(reset)")

    return out
Ejemplo n.º 12
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
Ejemplo n.º 13
0
def remind(text, nick, chan, db, conn, notice, async):
    """<1 minute, 30 seconds>: <do task> -- reminds you to <do task> in <1 minute, 30 seconds>"""

    count = len([x for x in reminder_cache if x[0] == conn.name and x[3] == nick.lower()])

    if text == "clear":
        if count == 0:
            return "You have no reminders to delete."

        yield from delete_all(async, db, conn.name, nick)
        yield from load_cache(async, db)
        return "Deleted all ({}) reminders for {}!".format(count, nick)

    # split the input on the first ":"
    parts = text.split(":", 1)

    if len(parts) == 1:
        # user didn't add a message, send them help
        notice(remind.__doc__)
        return

    if count > 10:
        return (
            "Sorry, you already have too many reminders queued (10), you will need to wait or "
            "clear your reminders to add any more."
        )

    time_string = parts[0].strip()
    message = colors.strip_all(parts[1].strip())

    # get the current time in both DateTime and Unix Epoch
    current_epoch = time.time()
    current_time = datetime.fromtimestamp(current_epoch)

    # parse the time input, return error if invalid
    seconds = time_parse(time_string)
    if not seconds:
        return "Invalid input."

    if seconds > 2764800 or seconds < 60:
        return "Sorry, remind input must be more then a minute, and less then one month."

    # work out the time to remind the user, and check if that time is in the past
    remind_time = datetime.fromtimestamp(current_epoch + seconds)
    if remind_time < current_time:
        return "I can't remind you in the past!"

    # finally, add the reminder and send a confirmation message
    yield from add_reminder(async, db, conn.name, nick, chan, message, remind_time, current_time)
    yield from load_cache(async, db)

    remind_text = format_time(seconds, count=2)
    output = 'Alright, I\'ll remind you "{}" in $(b){}$(clear)!'.format(message, remind_text)

    return colors.parse(output)
Ejemplo n.º 14
0
def get_video_description(video_id):
    dev_key = bot.config.get_api_key("google_dev_key")
    request = requests.get(api_url.format(video_id, dev_key))
    json = request.json()

    if json.get('error'):
        if json['error']['code'] == 403:
            raise APIError(err_no_api, json)

        raise APIError("Unknown error", json)

    data = json['items']
    if not data:
        return None

    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 (LookupError, ValueError):
        total_votes = 0

    if total_votes != 0:
        # format
        likes = pluralize_auto(int(statistics['likeCount']), "like")
        dislikes = pluralize_auto(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
Ejemplo n.º 15
0
def youtime(text):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    if not dev_key:
        return "This command requires a Google Developers Console API key."

    json = requests.get(search_api_url, params={"q": text, "key": dev_key}).json()

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

    if json["pageInfo"]["totalResults"] == 0:
        return "No results found."

    video_id = json["items"][0]["id"]["videoId"]
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get("error"):
        return
    data = json["items"]
    snippet = data[0]["snippet"]
    content_details = data[0]["contentDetails"]
    statistics = data[0]["statistics"]

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

    length = isodate.parse_duration(content_details["duration"])
    l_sec = int(length.total_seconds())
    views = int(statistics["viewCount"])
    total = int(l_sec * views)

    length_text = timeformat.format_time(l_sec, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return (
        "The video \x02{}\x02 has a length of {} and has been viewed {:,} times for "
        "a total run time of {}!".format(snippet["title"], length_text, views, total_text)
    )
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def hulu_search(text):
    """<query> - searches Hulu for <query>"""
    result = http.get_soup(
        "http://m.hulu.com/search?dp_identifier=hulu&{}&items_per_page=1&page=1".format(urlencode({'query': text})))
    data = result.find('results').find('videos').find('video')
    showname = data.find('show').find('name').text
    title = data.find('title').text
    duration = timeformat.format_time(int(float(data.find('duration').text)))
    description = data.find('description').text
    rating = data.find('content-rating').text
    return "{}: {} - {} - {} ({}) {}".format(showname, title, description, duration, rating,
                                             "http://www.hulu.com/watch/" + str(data.find('id').text))
Ejemplo n.º 18
0
def youtime(text):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    if not dev_key:
        return "This command requires a Google Developers Console API key."

    json = requests.get(search_api_url, params={"q": text, "key": dev_key, "type": "video"}).json()

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

    if json['pageInfo']['totalResults'] == 0:
        return 'No results found.'

    video_id = json['items'][0]['id']['videoId']
    json = requests.get(api_url.format(video_id, dev_key)).json()

    if json.get('error'):
        return
    data = json['items']
    snippet = data[0]['snippet']
    content_details = data[0]['contentDetails']
    statistics = data[0]['statistics']

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

    length = isodate.parse_duration(content_details['duration'])
    l_sec = int(length.total_seconds())
    views = int(statistics['viewCount'])
    total = int(l_sec * views)

    length_text = timeformat.format_time(l_sec, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           'a total run time of {}!'.format(snippet['title'], length_text, views,
                                            total_text)
Ejemplo n.º 19
0
def remind(text, nick, chan, db, conn, notice, async_call):
    """<1 minute, 30 seconds>: <do task> -- reminds you to <do task> in <1 minute, 30 seconds>"""

    count = len([x for x in reminder_cache if x[0] == conn.name and x[1] == nick.lower()])

    if text == "clear":
        if count == 0:
            return "You have no reminders to delete."

        yield from delete_all(async_call, db, conn.name, nick)
        yield from load_cache(async_call, db)
        return "Deleted all ({}) reminders for {}!".format(count, nick)

    # split the input on the first ":"
    parts = text.split(":", 1)

    if len(parts) == 1:
        # user didn't add a message, send them help
        notice(remind.__doc__)
        return

    if count > 10:
        return "Sorry, you already have too many reminders queued (10), you will need to wait or " \
               "clear your reminders to add any more."

    time_string = parts[0].strip()
    message = parts[1].strip()

    # get the current time in both DateTime and Unix Epoch
    current_epoch = time.time()
    current_time = datetime.fromtimestamp(current_epoch)

    # parse the time input, return error if invalid
    seconds = time_parse(time_string)
    if not seconds:
        return "Invalid timespan format."

    if seconds > 2764800 or seconds < 60:
        return "Sorry, remind input must be more than a minute, and less than one month."

    # work out the time to remind the user, and check if that time is in the past
    remind_time = datetime.fromtimestamp(current_epoch + seconds)
    if remind_time < current_time:
        return "I can't remind you in the past!"

    # finally, add the reminder and send a confirmation message
    yield from add_reminder(async_call, db, conn.name, nick, chan, message, remind_time, current_time)
    yield from load_cache(async_call, db)

    remind_text = format_time(seconds, count=2)
    return "Alright, I'll remind you \"{}\" in {}!".format(message, remind_text)
Ejemplo n.º 20
0
def youtime(text: str, reply) -> str:
    """<query> - Gets the total run time of the first YouTube search result for <query>."""
    parts = ["statistics", "contentDetails", "snippet"]
    try:
        video_id = get_video_id(text)
        request = get_video(video_id, parts)
        raise_api_errors(request)
    except NoResultsError as e:
        return e.message
    except APIError as e:
        reply(e.message)
        raise

    json = request.json()

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

    duration = content_details.get("duration")
    if not duration:
        return "Missing duration in API response"

    length = isodate.parse_duration(duration)
    l_sec = int(length.total_seconds())
    views = int(statistics["viewCount"])
    total = int(l_sec * views)

    length_text = timeformat.format_time(l_sec, simple=True)
    total_text = timeformat.format_time(total, accuracy=8)

    return (
        "The video \x02{}\x02 has a length of {} and has been viewed {:,} times for "
        "a total run time of {}!".format(snippet["title"], length_text, views,
                                         total_text))
Ejemplo n.º 21
0
def vimeo_url(match):
    """vimeo <url> -- returns information on the Vimeo video at <url>"""
    info = http.get_json('http://vimeo.com/api/v2/video/%s.json'
                         % match.group(1))

    if info:
        info[0]["duration"] = timeformat.format_time(info[0]["duration"])
        info[0]["stats_number_of_likes"] = format(
            info[0]["stats_number_of_likes"], ",d")
        info[0]["stats_number_of_plays"] = format(
            info[0]["stats_number_of_plays"], ",d")
        return ("\x02%(title)s\x02 - length \x02%(duration)s\x02 - "
                "\x02%(stats_number_of_likes)s\x02 likes - "
                "\x02%(stats_number_of_plays)s\x02 plays - "
                "\x02%(user_name)s\x02 on \x02%(upload_date)s\x02"
                % info[0])
Ejemplo n.º 22
0
def vimeo_url(match):
    """<url> -- returns information on the Vimeo video at <url>"""
    info = http.get_json('https://vimeo.com/api/v2/video/{}.json'.format(
        match.group(1)))

    if info:
        info[0]["duration"] = timeformat.format_time(info[0]["duration"])
        info[0]["stats_number_of_likes"] = format(
            info[0]["stats_number_of_likes"], ",d")
        info[0]["stats_number_of_plays"] = format(
            info[0]["stats_number_of_plays"], ",d")
        return (
            "[h1]Vimeo:[/h1] {title} [div] {user_name} [div] {duration} [div] "
            "{upload_date} [div] "
            "[h1]Likes:[/h1] {stats_number_of_likes} [div] "
            "[h1]Plays:[/h1] {stats_number_of_plays}".format(**info[0]))
Ejemplo n.º 23
0
def vimeo_url(match):
    """vimeo <url> - returns information on the Vimeo video at <url>"""
    video_id = match.group(1)
    data = http.get_json(api_url.format(id=video_id))

    if not data:
        return

    info = data[0]

    info["duration"] = timeformat.format_time(info["duration"])
    info.setdefault("stats_number_of_likes", 0)

    return ("\x02{title}\x02 - length \x02{duration}\x02 - "
            "\x02{stats_number_of_likes:,d}\x02 likes - "
            "\x02{stats_number_of_plays:,d}\x02 plays - "
            "\x02{user_name}\x02 on \x02{upload_date}\x02".format_map(info))
Ejemplo n.º 24
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
Ejemplo n.º 25
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
Ejemplo n.º 26
0
def remind(text, nick, chan, db, conn, notice, async):
    """<1m30s>: <do task> -- reminds you to <do task> in <1 minute, 30 seconds>.If no colon is given, only the first word will be used to determine the time.
    """

    count = len([
        x for x in reminder_cache
        if x[0] == conn.name and x[4].lower() == nick.lower()
    ])

    if text == "clear":
        if count == 0:
            return "You have no reminders to delete."

        yield from delete_all(async, db, conn.name, nick)
        yield from load_cache(async, db)
        return "Deleted all ({}) reminders for {}!".format(count, nick)

    if ":" in text:
        # split the input on the first ":"
        parts = text.split(":", 1)
    else:
        # take only the first word for the time value otherwise
        parts = text.split(" ", 1)

    if len(parts) == 1:
        # user didn't add a message, send them help
        notice(remind.__doc__)
        return

    if count > 10:
        notice(
            "Sorry, you already have too many reminders queued (10), you will need to wait or clear your reminders to add any more"
        )
        return

    time_string = parts[0].strip()
    message = colors.strip_all(parts[1].strip())

    # get the current time in both DateTime and Unix Epoch
    current_epoch = time.time()
    current_time = datetime.fromtimestamp(current_epoch)

    # parse the time input, return error if invalid
    seconds = time_parse(time_string)
    if not seconds:
        notice(
            "Invalid time. Try something like '2m30s', '2 days 3 hours:', or '1:30s'"
        )
        return

    if seconds > 2764800 or seconds < 60:
        return "Sorry, remind input must be more than a minute, and less than one month"

    # work out the time to remind the user, and check if that time is in the past
    remind_time = datetime.fromtimestamp(current_epoch + seconds)
    if remind_time < current_time:
        return "I can't remind you in the past!"

    # finally, add the reminder and send a confirmation message
    yield from add_reminder(async, db, conn.name, nick, chan, message,
                            remind_time, current_time)
    yield from load_cache(async, db)

    remind_text = format_time(seconds, count=2)
    output = "Alright, I'll remind you \"{}\" in $(b){}$(clear)!".format(
        message, remind_text)
    notice(colors.parse(output))
Ejemplo n.º 27
0
def hulu_url(match):
    data = http.get_json("http://www.hulu.com/api/oembed.json?url=http://www.hulu.com" + match.group(3))
    showname = data['title'].split("(")[-1].split(")")[0]
    title = data['title'].split(" (")[0]
    return "{}: {} - {}".format(showname, title, timeformat.format_time(int(data['duration'])))