nxy/bot/plugins/youtube.py

85 lines
2.9 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
import os
import re
2017-06-30 12:09:46 +00:00
import irc3
import requests
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
from . import Plugin
2017-06-01 12:50:35 +00:00
from ..utils import date_from_iso
@irc3.plugin
class YouTube(Plugin):
requires = ['irc3.plugins.command']
URL = 'https://www.googleapis.com/youtube/v3'
API = '{}/videos?part=snippet,statistics,contentDetails'.format(URL)
2017-05-30 12:26:47 +00:00
SEARCH = '{}/search?part=id'.format(URL)
2017-05-30 12:26:47 +00:00
def get_video_data(self, video_id: str):
2017-06-01 12:50:35 +00:00
"""Requests the infos for a video id and formats them."""
2017-05-30 12:26:47 +00:00
data = self._api(self.API, id=video_id)
2017-07-31 13:29:59 +00:00
if not data.get('items'):
2017-05-30 12:26:47 +00:00
return
item = data['items'][0]
date = date_from_iso(item['snippet']['publishedAt'])
2017-05-30 12:26:47 +00:00
length = re.findall('(\d+[DHMS])', item['contentDetails']['duration'])
2017-05-30 12:26:47 +00:00
views = int(item['statistics'].get('viewCount', 0))
likes = int(item['statistics'].get('likeCount', 0))
dislikes = int(item['statistics'].get('dislikeCount', 0))
try:
2017-05-30 12:26:47 +00:00
score = 100 * float(likes) / (likes + dislikes)
except ZeroDivisionError:
score = 0
2017-07-31 13:29:59 +00:00
return '\x02[YouTube]\x0F ' \
'{title} - length {length} -\x033 {likes:,}\x03 /' \
2017-06-01 15:38:34 +00:00
'\x034 {dislikes:,}\x03 ({score:,.1f}%) - {views:,} ' \
'views - {channel} on {date}' \
2017-05-30 12:26:47 +00:00
.format(title=item['snippet']['title'],
channel=item['snippet']['channelTitle'],
length=' '.join([l.lower() for l in length]),
likes=likes,
dislikes=dislikes,
score=score,
views=views,
date=date.strftime('%Y.%m.%d'))
2017-07-31 13:29:59 +00:00
@irc3.event(r'(?i)^:\S+ PRIVMSG (?P<target>\S+) :.*(?:youtube.*?(?:v=|/v/)'
2017-06-01 12:50:35 +00:00
r'|youtu\.be/)(?P<video_id>[-_a-zA-Z0-9]+).*')
def youtube_parser(self, target: str, video_id: str):
2017-05-30 12:26:47 +00:00
data = self.get_video_data(video_id)
if data:
self.bot.privmsg(target, data)
@command
def yt(self, mask: IrcString, target: IrcString, args: DocOptDict):
"""Searches for query on YouTube and returns first result.
%%yt <query>...
"""
2017-05-30 12:26:47 +00:00
data = self._api(self.SEARCH, q=' '.join(args['<query>']))
if 'error' in data:
return '\x02[YouTube]\x02 Error performing search'
elif data['pageInfo']['totalResults'] is 0:
return '\x02[YouTube]\x02 No results found'
else:
2017-05-30 12:26:47 +00:00
video_id = data['items'][0]['id']['videoId']
2017-07-07 00:11:20 +00:00
data = self.get_video_data(video_id)
return '{} - https://youtu.be/{}'.format(data, video_id)
2017-05-30 12:26:47 +00:00
# noinspection PyMethodMayBeStatic
def _api(self, url: str, **kwargs):
2017-06-01 12:50:35 +00:00
"""Wrapper around requests.get which adds the Google API key."""
2017-05-30 12:26:47 +00:00
kwargs['key'] = os.environ['GOOGLE_API_KEY']
return requests.get(url, params=kwargs).json()