aboutsummaryrefslogtreecommitdiff
path: root/plugins/youtube
blob: 1ce5f47785e379468c180917dfa5fd9f5551b012 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python3
#
# ZyklonB YouTube plugin, displaying info about YouTube links
#
# Copyright 2014 Přemysl Janouch
# 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 ('(?::([^! ]*)(?:!([^@]*)@([^ ]*))? +)?'
	'([^ ]+)(?: +(.*))?\r\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")

regexes = list (map (lambda x: re.compile (x), [
	'youtube\\.[a-z]+/[^ ]*[&?]v=([-_A-Za-z0-9]+)',
	'youtube\\.[a-z]+/v/([-_A-Za-z0-9]+)',
	'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 regex in regexes:
		for i in regex.findall (args[1]):
			print_video_info (ctx, i)