Added youtube parser

This commit is contained in:
mrhanky 2017-05-16 17:32:10 +02:00
parent a79a45f4ab
commit 84a03573b0
No known key found for this signature in database
GPG Key ID: 67D772C481CB41B8
5 changed files with 84 additions and 3 deletions

View File

@ -20,6 +20,7 @@
"nxy.plugins.database",
"nxy.plugins.futures",
"nxy.plugins.mcmaniac",
"nxy.plugins.media",
"nxy.plugins.quotes",
"nxy.plugins.useless"
],

63
nxy/plugins/media.py Normal file
View File

@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
import irc3
import os
import re
import requests
from irc3 import event, IrcBot
from . import Plugin
from ..utils import fmt, date_from_iso
YOUTUBE_URL = 'https://www.googleapis.com/youtube/v3'
YOUTUBE_API = '{}/videos?part=snippet,statistics,contentDetails' \
.format(YOUTUBE_URL)
YOUTUBE_SEARCH = '{}/search?part=id,snippet'.format(YOUTUBE_URL)
@irc3.plugin
class Media(Plugin):
requires = [
'irc3.plugins.command',
]
def __init__(self, bot: IrcBot):
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(self, target: str, video_id: str):
req = requests.get(YOUTUBE_API, params={
'key': self.GOOGLE_API_KEY,
'id': video_id})
data = req.json()
if not data['items']:
return
item = data['items'][0]
stats = item['statistics']
date = date_from_iso(item['snippet']['publishedAt'])
length = item['contentDetails']['duration']
length = re.findall('(\d+[DHMS])', length)
likes = int(stats.get('likeCount', 0))
dislikes = int(stats.get('dislikeCount', 0))
try:
score = 100 * float(likes) / (likes + dislikes)
except ZeroDivisionError:
score = 0
res = 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(stats.get('viewCount', 0)),
likes=likes,
dislikes=dislikes,
score=score)
self.bot.privmsg(target, res)

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import re
from datetime import timedelta
from datetime import datetime, timedelta
from pprint import pprint
# @formatter:off
@ -44,6 +44,10 @@ def fmt(__text: str, **kwargs) -> str:
return __text.format(**kwargs, **FORMATTING)
def date_from_iso(date: str) -> datetime:
return datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
def time_delta(text: str) -> timedelta:
match = re.match(r'(\d+)(s|m|h|mon|w|y)', text)
if match:

14
repl.py Normal file
View File

@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
import requests
import sys
import os
import re
from pprint import pprint
# noinspection PyPackageRequirements
from dotenv import load_dotenv
pp = pprint
load_dotenv('.env')

View File

@ -1,5 +1,4 @@
#irc3==1.0.0
git+https://github.com/gawel/irc3.git
git+https://github.com/gawel/irc3.git#egg=irc3
aiocron==0.6
requests==2.14.2
python_dotenv==0.6.4