Exemplo n.º 1
0
def youtime(inp, bot=None):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    key = bot.config.get("api_keys", {}).get("youtube")
    request = http.get_json(search_api_url, key=key, q=inp, type='video')

    if 'error' in request:
        return 'Error performing search.'

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

    video_id = request['items'][0]['id']['videoId']

    request = http.get_json(api_url, key=key, id=video_id)

    data = request['items'][0]

    length = data['contentDetails']['duration']
    timelist = length[2:-1].split('M')
    seconds = 60*int(timelist[0]) + int(timelist[1])

    views = int(data['statistics']['viewCount'])
    total = int(seconds * views)

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

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

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

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

    video_id = request['data']['items'][0]['id']
    request = http.get_json(api_url.format(video_id))

    if request.get('error'):
        return
    data = request['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 u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
           u'a total run time of {}!'.format(data['title'], length_text, views,
                                             total_text)
Exemplo n.º 3
0
def youtime(inp):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    request = http.get_json(search_api_url, q=inp)

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

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

    video_id = request['data']['items'][0]['id']
    request = http.get_json(api_url.format(video_id))

    if request.get('error'):
        return
    data = request['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)
Exemplo n.º 4
0
def youtime(inp, bot=None):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    key = bot.config.get("api_keys", {}).get("youtube")
    request = http.get_json(search_api_url, key=key, q=inp, type='video')

    if 'error' in request:
        return 'Error performing search.'

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

    video_id = request['items'][0]['id']['videoId']

    request = http.get_json(api_url, key=key, id=video_id)

    data = request['items'][0]

    length = data['contentDetails']['duration']
    timelist = length[2:-1].split('M')
    seconds = 60 * int(timelist[0]) + int(timelist[1])

    views = int(data['statistics']['viewCount'])
    total = int(seconds * views)

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

    return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
            'a total run time of {}!'.format(data['snippet']['title'], length_text, views, total_text)
Exemplo n.º 5
0
def get_video_description(key, video_id):
    request = http.get_json(api_url, key=key, id=video_id)

    if request.get('error'):
        return

    data = request['items'][0]

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

    try:
        data['contentDetails'].get('duration')
    except KeyError:
        return out

    length = data['contentDetails']['duration']
    timelist = re.findall('(\d+[DHMS])', length)

    seconds = 0
    for t in timelist:
        t_field = int(t[:-1])
        if t[-1:] == 'D': seconds += 86400 * t_field
        elif t[-1:] == 'H': seconds += 3600 * t_field
        elif t[-1:] == 'M': seconds += 60 * t_field
        elif t[-1:] == 'S': seconds += t_field

    out += u' - length \x02{}\x02'.format(
        timeformat.format_time(seconds, simple=True))

    try:
        data['statistics']
    except KeyError:
        return out

    stats = data['statistics']
    likes = plural(int(stats['likeCount']), "like")
    dislikes = plural(int(stats['dislikeCount']), "dislike")

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

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

    uploader = data['snippet']['channelTitle']

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

    try:
        data['contentDetails']['contentRating']
    except KeyError:
        return out

    out += u' - \x034NSFW\x02'

    return out
Exemplo n.º 6
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'])))
Exemplo n.º 7
0
def get_video_description(key,video_id):
    request = http.get_json(api_url, key=key, id=video_id)

    if request.get('error'):
        return

    data = request['items'][0]

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

    try:
        data['contentDetails'].get('duration')
    except KeyError:
        return out

    length = data['contentDetails']['duration']
    timelist = re.findall('(\d+[DHMS])', length)

    seconds = 0
    for t in timelist:
        t_field = int(t[:-1])
        if   t[-1:] == 'D': seconds += 86400 * t_field
        elif t[-1:] == 'H': seconds += 3600 * t_field
        elif t[-1:] == 'M': seconds += 60 * t_field
        elif t[-1:] == 'S': seconds += t_field

    out += u' - length \x02{}\x02'.format(timeformat.format_time(seconds, simple=True))

    try:
        data['statistics']
    except KeyError:
        return out

    stats = data['statistics']
    likes = plural(int(stats['likeCount']), "like")
    dislikes = plural(int(stats['dislikeCount']), "dislike")

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

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

    uploader = data['snippet']['channelTitle']

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

    try:
        data['contentDetails']['contentRating']
    except KeyError:
        return out

    out += u' - \x034NSFW\x02'

    return out
Exemplo n.º 8
0
def youtime(inp):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    if not yt_load_dev_key(bot):
        return "This command requires a Google Developers Console API key."

    json = requests.get(search_api_url, params={
        "q": inp,
        "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)
Exemplo n.º 9
0
def hulu_search(text):
    """hulu <search> - Search Hulu"""
    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))
Exemplo n.º 10
0
def get_video_description(video_id):
    global yt_dev_key
    if not yt_dev_key:
        return
    json = requests.get(api_url.format(video_id, yt_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
Exemplo n.º 11
0
def hulu_search(inp):
    """hulu <search> - Search Hulu"""
    result = http.get_soup(
        "http://m.hulu.com/search?dp_identifier=hulu&{}&items_per_page=1&page=1"
        .format(urlencode({'query': inp})))
    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))
Exemplo n.º 12
0
def youtime(inp, bot=None):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    key = bot.config.get("api_keys", {}).get("google")
    request = http.get_json(search_api_url, key=key, q=inp, type='video')

    if 'error' in request:
        return 'Error performing search.'

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

    video_id = request['items'][0]['id']['videoId']

    request = http.get_json(api_url, key=key, id=video_id)

    data = request['items'][0]

    length = data['contentDetails']['duration']
    timelist = re.findall('(\d+[DHMS])', length)

    seconds = 0
    for t in timelist:
        t_field = int(t[:-1])
        if   t[-1:] == 'D': seconds += 86400 * t_field
        elif t[-1:] == 'H': seconds += 3600 * t_field
        elif t[-1:] == 'M': seconds += 60 * t_field
        elif t[-1:] == 'S': seconds += t_field

    views = int(data['statistics']['viewCount'])
    total = int(seconds * views)

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

    return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
            'a total run time of {}!'.format(data['snippet']['title'], length_text, views, total_text)
Exemplo n.º 13
0
def youtime(inp, bot=None):
    """youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
    key = bot.config.get("api_keys", {}).get("google")
    request = http.get_json(search_api_url, key=key, q=inp, type='video')

    if 'error' in request:
        return 'Error performing search.'

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

    video_id = request['items'][0]['id']['videoId']

    request = http.get_json(api_url, key=key, id=video_id)

    data = request['items'][0]

    length = data['contentDetails']['duration']
    timelist = re.findall('(\d+[DHMS])', length)

    seconds = 0
    for t in timelist:
        t_field = int(t[:-1])
        if t[-1:] == 'D': seconds += 86400 * t_field
        elif t[-1:] == 'H': seconds += 3600 * t_field
        elif t[-1:] == 'M': seconds += 60 * t_field
        elif t[-1:] == 'S': seconds += t_field

    views = int(data['statistics']['viewCount'])
    total = int(seconds * views)

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

    return u'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
            'a total run time of {}!'.format(data['snippet']['title'], length_text, views, total_text)
Exemplo n.º 14
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])
Exemplo n.º 15
0
def get_video_description(video_id):
    request = http.get_json(api_url.format(video_id))

    if request.get('error'):
        return

    data = request['data']

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

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

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

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

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

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

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

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

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

    return out
Exemplo n.º 16
0
def get_video_description(video_id):
    request = http.get_json(api_url.format(video_id))

    if request.get('error'):
        return

    data = request['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 = plural(int(data['likeCount']), "like")
        dislikes = plural(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:
        uploader = http.get_json(base_url + "users/{}?alt=json".format(data["uploader"]))["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
Exemplo n.º 17
0
def info(id):
    info = request.get_json('http://vimeo.com/api/v2/video/' + id + '.json')

    if not info or len(info) == 0:
        return

    title = info[0]['title']
    length = timeformat.format_time(info[0]["duration"], simple=True)
    likes = format(info[0]['stats_number_of_likes'], ',d')
    views = format(info[0]['stats_number_of_plays'], ',d')
    uploader = info[0]['user_name']
    upload_date = info[0]['upload_date']

    output = []
    output.append('\x02' + title + '\x02')
    output.append('length \x02' + length + '\x02')
    output.append(likes + ' likes')
    output.append(views + ' views')
    output.append('\x02' + uploader + '\x02 on ' + upload_date)

    return ' - '.join(output)
Exemplo n.º 18
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'])))
Exemplo n.º 19
0
def get_video_description(key, video_id, bot):
    try:
        request = http.get_json(api_url, key=key, id=video_id)
    except:
        key = bot.config.get("api_keys", {}).get("public_google_key")
        request = http.get_json(api_url, key=key, id=video_id)

    if request.get('error'):
        return

    data = request['items'][0]

    title = filter(None, data['snippet']['title'].split(' '))
    title = ' '.join(map(lambda s: s.strip(), title))
    out = u'\x02{}\x02'.format(title)

    try:
        data['contentDetails'].get('duration')
    except KeyError:
        return out

    length = data['contentDetails']['duration']
    timelist = re.findall('(\d+[DHMS])', length)

    seconds = 0
    for t in timelist:
        t_field = int(t[:-1])
        if t[-1:] == 'D': seconds += 86400 * t_field
        elif t[-1:] == 'H': seconds += 3600 * t_field
        elif t[-1:] == 'M': seconds += 60 * t_field
        elif t[-1:] == 'S': seconds += t_field

    out += u' - length \x02{}\x02'.format(
        timeformat.format_time(seconds, simple=True))

    try:
        data['statistics']
    except KeyError:
        return out

    stats = data['statistics']
    try:
        likes = u"\u2191{:,}".format(int(stats['likeCount']))
        dislikes = u"\u2193{:,}".format(int(stats['dislikeCount']))
        try:
            percent = 100 * float(stats['likeCount']) / (
                int(stats['likeCount']) + int(stats['dislikeCount']))
        except ZeroDivisionError:
            percent = 0
    except KeyError:
        likes = '\x0304likes disabled\x03'
        dislikes = '\x0304dislikes disabled\x03'
        percent = 0
    if percent >= 50:
        out += u' - \x0309{}\x03, \x0304{}\x03 (\x02\x0309{:.1f}\x03\x02%)'.format(
            likes, dislikes, percent)
    else:
        out += u' - \x0309{}\x03, \x0304{}\x03 (\x0304\x02{:.1f}\x02%\x03)'.format(
            likes, dislikes, percent)

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

    uploader = data['snippet']['channelTitle']

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

    try:
        data['contentDetails']['contentRating']
        if data['contentDetails']['contentRating'] == {}:
            return out
    except KeyError:
        return out

    out += u' - \x034NSFW\x02'

    return out