xK/plugins/youtube

95 lines
2.4 KiB
Plaintext
Raw Normal View History

#!/usr/bin/env python3
#
# ZyklonB YouTube plugin, displaying info about YouTube links
#
# Copyright 2014 Přemysl Janouch. All rights reserved.
# See the file LICENSE for licensing information.
#
import sys
import io
import re
import json
import urllib.request
sys.stdin = io.TextIOWrapper (sys.__stdin__.buffer,
encoding = 'iso8859-1', newline = '\r\n', line_buffering = True)
sys.stdout = io.TextIOWrapper (sys.__stdout__.buffer,
encoding = 'iso8859-1', newline = '\r\n', line_buffering = True)
re_msg = re.compile ('(?::([^! ]*)(?:!([^@]*)@([^ ]*))? +)?'
'([^ ]+)(?: +(.*))?\n$')
re_args = re.compile (':?((?<=:).*|[^ ]+) *')
def parse (line):
global re_msg
global re_args
m = re_msg.match (line)
if m == None:
return None
(nick, user, host, command, args) = m.groups ()
if args == None:
args = []
else:
args = re_args.findall (args)
return (nick, user, host, command, args)
def get_config (key):
print ("ZYKLONB get_config :%s" % key)
(_, _, _, _, args) = parse (sys.stdin.readline ())
return args[0]
def bot_print (what):
print ('ZYKLONB print :%s' % what)
youtube_api_key = get_config ('youtube_api_key')
if youtube_api_key == "":
bot_print ("youtube: missing `youtube_api_key'")
print ("ZYKLONB register")
re_link_1 = re.compile ('youtube\\.[a-z]+/[^ ]*[&?]v=([-_A-Za-z0-9]+)')
re_link_2 = re.compile ('youtu\\.be/([-_A-Za-z0-9]+)')
def print_video_info (channel, video_id):
global youtube_api_key
url = 'https://www.googleapis.com/youtube/v3/' \
+ 'videos?id=%s&key=%s&part=snippet,contentDetails,statistics' \
% (video_id, youtube_api_key)
try:
data = json.loads (urllib.request.urlopen
(url, None, 30).read ().decode ('utf-8'))
for x in data['items']:
desc = "YouTube: "
desc += x['snippet']['title'] + ' | '
desc += x['contentDetails']['duration'][2:].lower () + ' | '
desc += x['statistics']['viewCount'] + 'x'
print ("PRIVMSG %s :%s" % (channel,
desc.encode ('utf-8').decode ('iso8859-1')))
except Exception as err:
bot_print ('youtube: %s' % (err))
for line in sys.stdin:
msg = parse (line)
if msg == None:
continue
(nick, user, host, command, args) = msg
if command != 'PRIVMSG' or len (args) < 2:
continue
ctx = args[0]
if not ctx.startswith (('#', '+', '&', '!')):
ctx = nick
for i in re_link_1.findall (args[1]):
print_video_info (ctx, i)
for i in re_link_2.findall (args[1]):
print_video_info (ctx, i)