Added youtube search functionality, code sucks btw
This commit is contained in:
parent
db8b0a4d4c
commit
b0dafcfef9
|
@ -4,12 +4,16 @@ import os
|
|||
import re
|
||||
import requests
|
||||
|
||||
from docopt import Dict as DocOptDict
|
||||
from irc3 import event, IrcBot
|
||||
from irc3.plugins.command import command
|
||||
from irc3.utils import IrcString
|
||||
|
||||
from . import Plugin
|
||||
from ..utils import fmt, date_from_iso
|
||||
|
||||
|
||||
# TODO: write better code lol
|
||||
@irc3.plugin
|
||||
class YouTube(Plugin):
|
||||
requires = ['irc3.plugins.command']
|
||||
|
@ -22,21 +26,18 @@ class YouTube(Plugin):
|
|||
super().__init__(bot)
|
||||
self.GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
|
||||
|
||||
@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 not data['items']:
|
||||
return
|
||||
|
||||
item = data['items'][0]
|
||||
def get_video_data(self, item: dict):
|
||||
date = date_from_iso(item['snippet']['publishedAt'])
|
||||
|
||||
try:
|
||||
length = item['contentDetails']['duration']
|
||||
length = re.findall('(\d+[DHMS])', length)
|
||||
length = [l.lower() for l in re.findall('(\d+[DHMS])', length)]
|
||||
length = ' - length {}'.format(' '.join(length))
|
||||
except KeyError:
|
||||
length = ''
|
||||
|
||||
try:
|
||||
views = int(item['statistics'].get('viewCount', 0))
|
||||
likes = int(item['statistics'].get('likeCount', 0))
|
||||
dislikes = int(item['statistics'].get('dislikeCount', 0))
|
||||
|
||||
|
@ -45,15 +46,51 @@ class YouTube(Plugin):
|
|||
except ZeroDivisionError:
|
||||
score = 0
|
||||
|
||||
text = fmt('{title} - length {length} -{color}{green} {likes:,}{reset}'
|
||||
' /{color}{maroon} {dislikes:,}{reset} ({score:,.1f}%) - '
|
||||
'{views:,} views - {channel} on {date}',
|
||||
title=item['snippet']['localized']['title'],
|
||||
channel=item['snippet']['channelTitle'],
|
||||
length=' '.join([l.lower() for l in length]),
|
||||
date=date.strftime('%Y.%m.%d'),
|
||||
views=int(item['statistics'].get('viewCount', 0)),
|
||||
stats = fmt(' -{color}{green} {likes:,}{reset} /{color}{maroon} '
|
||||
'{dislikes:,}{reset} ({score:,.1f}%) '
|
||||
'- {views:,} views',
|
||||
likes=likes,
|
||||
dislikes=dislikes,
|
||||
score=score)
|
||||
self.bot.privmsg(target, text)
|
||||
score=score,
|
||||
views=views)
|
||||
except KeyError:
|
||||
stats = ''
|
||||
|
||||
return fmt('{title}{length}{stats} - {channel} on {date}',
|
||||
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/)'
|
||||
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]))
|
||||
|
||||
@command
|
||||
def yt(self, mask: IrcString, channel: IrcString, args: DocOptDict):
|
||||
"""Searches for query on YouTube and returns first result.
|
||||
|
||||
%%yt <query>...
|
||||
"""
|
||||
req = requests.get(self.SEARCH, params={
|
||||
'key': self.GOOGLE_API_KEY,
|
||||
'q': ' '.join(args['<query>'])})
|
||||
data = req.json()
|
||||
|
||||
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]
|
||||
return '{response} - https://youtu.be/{video_id}'.format(
|
||||
response=self.get_video_data(item),
|
||||
video_id=item['id']['videoId'])
|
||||
|
|
Loading…
Reference in New Issue
Block a user