Cleaned jewtube plugin
This commit is contained in:
parent
4edbfe8d5c
commit
e7a6501c7d
@ -32,5 +32,5 @@ class DatabasePlugin(Plugin):
|
||||
rows=', '.join(kwargs),
|
||||
placeholders=', '.join('?' * len(kwargs))
|
||||
)
|
||||
self.cur.execute(qry, kwargs.values())
|
||||
self.cur.commit()
|
||||
self.cur.execute(qry, list(kwargs.values()))
|
||||
self.con.commit()
|
||||
|
@ -10,7 +10,7 @@ from irc3.plugins.command import command
|
||||
from irc3.utils import IrcString
|
||||
|
||||
from . import Plugin
|
||||
from ..utils import date_from_iso
|
||||
from ..utils import date_from_iso, pp
|
||||
|
||||
|
||||
# TODO: write better code lol
|
||||
@ -20,59 +20,45 @@ class YouTube(Plugin):
|
||||
|
||||
URL = 'https://www.googleapis.com/youtube/v3'
|
||||
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):
|
||||
super().__init__(bot)
|
||||
self.GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
|
||||
def get_video_data(self, video_id: str):
|
||||
data = self._api(self.API, id=video_id)
|
||||
|
||||
def get_video_data(self, item: dict):
|
||||
if not data['items']:
|
||||
return
|
||||
|
||||
item = data['items'][0]
|
||||
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:
|
||||
length = item['contentDetails']['duration']
|
||||
length = [l.lower() for l in re.findall('(\d+[DHMS])', length)]
|
||||
length = ' - length {}'.format(' '.join(length))
|
||||
except KeyError:
|
||||
length = ''
|
||||
score = 100 * float(likes) / (likes + dislikes)
|
||||
except ZeroDivisionError:
|
||||
score = 0
|
||||
|
||||
try:
|
||||
views = int(item['statistics'].get('viewCount', 0))
|
||||
likes = int(item['statistics'].get('likeCount', 0))
|
||||
dislikes = int(item['statistics'].get('dislikeCount', 0))
|
||||
|
||||
try:
|
||||
score = 100 * float(likes) / (likes + dislikes)
|
||||
except ZeroDivisionError:
|
||||
score = 0
|
||||
|
||||
stats = ' -\x033 {likes:,}\x0F /\x035 ' \
|
||||
'{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,
|
||||
)
|
||||
return '{title} - length {length} -\x033 {likes:,}\x0F /\x035 ' \
|
||||
'{dislikes:,}\x0F ({score:,.1f}%) - {views:,} views - ' \
|
||||
'{channel} on {date}' \
|
||||
.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'))
|
||||
|
||||
@event(r'(?i)^:.* PRIVMSG (?P<target>.*) :.*(?:youtube.*?(?:v=|/v/)'
|
||||
r'|youtu\.be/)(?P<video_id>[-_a-zA-Z0-9]+).*')
|
||||
def youtube_parser(self, target: str, video_id: str):
|
||||
req = requests.get(self.API, params={
|
||||
'key': self.GOOGLE_API_KEY,
|
||||
'id': video_id})
|
||||
data = req.json()
|
||||
|
||||
if data['items']:
|
||||
self.bot.privmsg(target, self.get_video_data(data['items'][0]))
|
||||
data = self.get_video_data(video_id)
|
||||
if data:
|
||||
self.bot.privmsg(target, data)
|
||||
|
||||
@command
|
||||
def yt(self, mask: IrcString, channel: IrcString, args: DocOptDict):
|
||||
@ -80,17 +66,20 @@ class YouTube(Plugin):
|
||||
|
||||
%%yt <query>...
|
||||
"""
|
||||
req = requests.get(self.SEARCH, params={
|
||||
'key': self.GOOGLE_API_KEY,
|
||||
'q': ' '.join(args['<query>'])})
|
||||
data = req.json()
|
||||
data = self._api(self.SEARCH, q=' '.join(args['<query>']))
|
||||
|
||||
if 'error' in data:
|
||||
return '[YouTube] Error performing search'
|
||||
elif data['pageInfo']['totalResults'] is 0:
|
||||
return '[YouTube] No results found'
|
||||
else:
|
||||
item = data['items'][0]
|
||||
video_id = data['items'][0]['id']['videoId']
|
||||
return '{response} - https://youtu.be/{video_id}'.format(
|
||||
response=self.get_video_data(item),
|
||||
video_id=item['id']['videoId'])
|
||||
response=self.get_video_data(video_id),
|
||||
video_id=video_id,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _api(url: str, **kwargs):
|
||||
kwargs['key'] = os.environ['GOOGLE_API_KEY']
|
||||
return requests.get(url, params=kwargs).json()
|
||||
|
Loading…
Reference in New Issue
Block a user