예제 #1
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"
예제 #2
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 += " Running Time: {}.".format(timeformat.format_time(seconds, simple=True))

        out += " Playlist Type: \x02{}\x02.".format(playlist['type'])

    if show_url:
        out += " - {}".format(web.try_shorten(playlist['permalink_url']))
    return out
예제 #3
0
파일: remind.py 프로젝트: Jakeable/Ralybot
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)
예제 #4
0
파일: youtube.py 프로젝트: Jakeable/Ralybot
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)
예제 #5
0
파일: vimeo.py 프로젝트: Jakeable/Ralybot
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])
예제 #6
0
파일: youtube.py 프로젝트: Jakeable/Ralybot
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 += ' - \x033\x02{}\x02\x0f, \x034\x02{}\x02\x0f ({:.1f}%)'.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