pyircbot/pyircbot/modules/Youtube.py

93 lines
3.6 KiB
Python
Raw Normal View History

2014-10-05 00:56:32 -07:00
#!/usr/bin/env python
"""
.. module:: Youtube
2015-08-31 20:33:13 -07:00
:synopsis: Search youtube with .youtube/.yt
2014-10-05 00:56:32 -07:00
.. moduleauthor:: Dave Pedu <dave@davepedu.com>
"""
2017-11-27 18:58:20 -08:00
from pyircbot.modulebase import ModuleBase, command
from pyircbot.modules.ModInfo import info
from random import shuffle
2014-10-05 00:56:32 -07:00
from requests import get
import time
import re
2014-10-05 00:56:32 -07:00
2017-01-01 14:59:01 -08:00
2014-10-05 00:56:32 -07:00
class Youtube(ModuleBase):
2015-08-31 20:33:13 -07:00
def __init__(self, bot, moduleName):
2017-01-01 14:59:01 -08:00
ModuleBase.__init__(self, bot, moduleName)
def getISOdurationseconds(self, stamp):
ISO_8601_period_rx = re.compile(
'P' # designates a period
2017-01-01 14:59:01 -08:00
'(?:(?P<years>\d+)Y)?' # years
'(?:(?P<months>\d+)M)?' # months
'(?:(?P<weeks>\d+)W)?' # weeks
'(?:(?P<days>\d+)D)?' # days
'(?:T' # time part begins with a T
'(?:(?P<hours>\d+)H)?' # hours
'(?:(?P<minutes>\d+)M)?' # minutes
'(?:(?P<seconds>\d+)S)?' # seconds
')?' # end of time part
2017-01-01 14:59:01 -08:00
) # http://stackoverflow.com/a/16742742
return ISO_8601_period_rx.match(stamp).groupdict()
2017-01-01 14:59:01 -08:00
2017-11-27 18:58:20 -08:00
@info("yt search for youtube videos", cmds=["yt", "youtube"])
@command("yt", "youtube")
def youtube(self, msg, cmd):
j = get("https://www.googleapis.com/youtube/v3/search",
params={"key": self.config["api_key"],
"part": "snippet",
"type": "video",
"maxResults": "25",
"safeSearch": self.config.get("safe_search", "none"),
"q": cmd.args_str}).json()
2017-01-01 14:59:01 -08:00
2017-11-27 18:58:20 -08:00
if 'error' in j or len(j["items"]) == 0:
self.bot.act_PRIVMSG(msg.args[0], "No results found.")
else:
shuffle(j['items'])
vid_id = j["items"][0]['id']['videoId']
self.bot.act_PRIVMSG(msg.args[0], "http://youtu.be/{} :: {}".format(vid_id,
self.get_video_description(vid_id)))
2017-01-01 14:59:01 -08:00
2015-08-31 20:33:13 -07:00
def get_video_description(self, vid_id):
2017-01-01 14:59:01 -08:00
apidata = get('https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=%s'
'&key=%s' % (vid_id, self.config["api_key"])).json()
if not apidata['pageInfo']['totalResults']:
2015-08-31 20:33:13 -07:00
return
2017-01-01 14:59:01 -08:00
video = apidata['items'][0]
snippet = video["snippet"]
duration = self.getISOdurationseconds(video["contentDetails"]["duration"])
2017-01-01 14:59:01 -08:00
out = '\x02\x031,0You\x0f\x030,4Tube\x02\x0f :: \x02%s\x02' % snippet["title"]
2017-01-01 14:59:01 -08:00
out += ' - \x02'
2017-01-01 14:59:01 -08:00
if duration["hours"] is not None:
out += '%dh ' % int(duration["hours"])
2017-01-01 14:59:01 -08:00
if duration["minutes"] is not None:
out += '%dm ' % int(duration["minutes"])
out += "%ds\x02" % int(duration["seconds"])
2017-01-01 14:59:01 -08:00
totalvotes = float(video["statistics"]["dislikeCount"]) + float(video["statistics"]["likeCount"])
rating = float(video["statistics"]["likeCount"]) / totalvotes
2017-01-01 14:59:01 -08:00
out += ' - rated \x02%.2f/5\x02' % round(rating * 5, 1)
out += ' - \x02%s\x02 views' % self.group_int_digits(video["statistics"]["viewCount"])
upload_time = time.strptime(snippet['publishedAt'], "%Y-%m-%dT%H:%M:%S.000Z")
out += ' - by \x02%s\x02 on \x02%s\x02' % (snippet['channelTitle'], time.strftime("%Y.%m.%d", upload_time))
2017-01-01 14:59:01 -08:00
2015-08-31 20:33:13 -07:00
return out
2017-01-01 14:59:01 -08:00
2015-08-31 20:33:13 -07:00
def group_int_digits(self, number, delimiter=',', grouping=3):
base = str(number).strip()
builder = []
while base:
builder.append(base[-grouping:])
base = base[:-grouping]
builder.reverse()
return delimiter.join(builder)