Cleaned jewtube plugin

This commit is contained in:
mrhanky 2017-05-30 14:26:47 +02:00
parent 4edbfe8d5c
commit e7a6501c7d
No known key found for this signature in database
GPG Key ID: 67D772C481CB41B8
2 changed files with 42 additions and 53 deletions

View File

@ -32,5 +32,5 @@ class DatabasePlugin(Plugin):
rows=', '.join(kwargs), rows=', '.join(kwargs),
placeholders=', '.join('?' * len(kwargs)) placeholders=', '.join('?' * len(kwargs))
) )
self.cur.execute(qry, kwargs.values()) self.cur.execute(qry, list(kwargs.values()))
self.cur.commit() self.con.commit()

View File

@ -10,7 +10,7 @@ from irc3.plugins.command import command
from irc3.utils import IrcString from irc3.utils import IrcString
from . import Plugin from . import Plugin
from ..utils import date_from_iso from ..utils import date_from_iso, pp
# TODO: write better code lol # TODO: write better code lol
@ -20,59 +20,45 @@ class YouTube(Plugin):
URL = 'https://www.googleapis.com/youtube/v3' URL = 'https://www.googleapis.com/youtube/v3'
API = '{}/videos?part=snippet,statistics,contentDetails'.format(URL) API = '{}/videos?part=snippet,statistics,contentDetails'.format(URL)
SEARCH = '{}/search?part=id,snippet'.format(URL) SEARCH = '{}/search?part=id'.format(URL)
def __init__(self, bot: IrcBot): def get_video_data(self, video_id: str):
super().__init__(bot) data = self._api(self.API, id=video_id)
self.GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
def get_video_data(self, item: dict): if not data['items']:
return
item = data['items'][0]
date = date_from_iso(item['snippet']['publishedAt']) date = date_from_iso(item['snippet']['publishedAt'])
length = re.findall('(\d+[DHMS])', item['contentDetails']['duration'])
views = int(item['statistics'].get('viewCount', 0))
likes = int(item['statistics'].get('likeCount', 0))
dislikes = int(item['statistics'].get('dislikeCount', 0))
try: try:
length = item['contentDetails']['duration'] score = 100 * float(likes) / (likes + dislikes)
length = [l.lower() for l in re.findall('(\d+[DHMS])', length)] except ZeroDivisionError:
length = ' - length {}'.format(' '.join(length)) score = 0
except KeyError:
length = ''
try: return '{title} - length {length} -\x033 {likes:,}\x0F /\x035 ' \
views = int(item['statistics'].get('viewCount', 0)) '{dislikes:,}\x0F ({score:,.1f}%) - {views:,} views - ' \
likes = int(item['statistics'].get('likeCount', 0)) '{channel} on {date}' \
dislikes = int(item['statistics'].get('dislikeCount', 0)) .format(title=item['snippet']['title'],
channel=item['snippet']['channelTitle'],
try: length=' '.join([l.lower() for l in length]),
score = 100 * float(likes) / (likes + dislikes) likes=likes,
except ZeroDivisionError: dislikes=dislikes,
score = 0 score=score,
views=views,
stats = ' -\x033 {likes:,}\x0F /\x035 ' \ date=date.strftime('%Y.%m.%d'))
'{dislikes:,}\x0F ({score:,.1f}%) ' \
'- {views:,} views'.format(likes=likes,
dislikes=dislikes,
score=score,
views=views)
except KeyError:
stats = ''
return '{title}{length}{stats} - {channel} on {date}'.format(
title=item['snippet']['title'],
channel=item['snippet']['channelTitle'],
length=length,
date=date.strftime('%Y.%m.%d'),
stats=stats,
)
@event(r'(?i)^:.* PRIVMSG (?P<target>.*) :.*(?:youtube.*?(?:v=|/v/)' @event(r'(?i)^:.* PRIVMSG (?P<target>.*) :.*(?:youtube.*?(?:v=|/v/)'
r'|youtu\.be/)(?P<video_id>[-_a-zA-Z0-9]+).*') r'|youtu\.be/)(?P<video_id>[-_a-zA-Z0-9]+).*')
def youtube_parser(self, target: str, video_id: str): def youtube_parser(self, target: str, video_id: str):
req = requests.get(self.API, params={ data = self.get_video_data(video_id)
'key': self.GOOGLE_API_KEY, if data:
'id': video_id}) self.bot.privmsg(target, data)
data = req.json()
if data['items']:
self.bot.privmsg(target, self.get_video_data(data['items'][0]))
@command @command
def yt(self, mask: IrcString, channel: IrcString, args: DocOptDict): def yt(self, mask: IrcString, channel: IrcString, args: DocOptDict):
@ -80,17 +66,20 @@ class YouTube(Plugin):
%%yt <query>... %%yt <query>...
""" """
req = requests.get(self.SEARCH, params={ data = self._api(self.SEARCH, q=' '.join(args['<query>']))
'key': self.GOOGLE_API_KEY,
'q': ' '.join(args['<query>'])})
data = req.json()
if 'error' in data: if 'error' in data:
return '[YouTube] Error performing search' return '[YouTube] Error performing search'
elif data['pageInfo']['totalResults'] is 0: elif data['pageInfo']['totalResults'] is 0:
return '[YouTube] No results found' return '[YouTube] No results found'
else: else:
item = data['items'][0] video_id = data['items'][0]['id']['videoId']
return '{response} - https://youtu.be/{video_id}'.format( return '{response} - https://youtu.be/{video_id}'.format(
response=self.get_video_data(item), response=self.get_video_data(video_id),
video_id=item['id']['videoId']) video_id=video_id,
)
@staticmethod
def _api(url: str, **kwargs):
kwargs['key'] = os.environ['GOOGLE_API_KEY']
return requests.get(url, params=kwargs).json()