Edm0nd/edmond/plugins/youtube_parser.py

70 lines
2 KiB
Python
Raw Normal View History

import re
try:
from googleapiclient.errors import Error as GoogleApiError
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
from edmond.plugin import Plugin
class YoutubeParserPlugin(Plugin):
VIDEO_URL_RE = re.compile(
2022-03-06 17:26:48 +01:00
r"https?:\/\/(?:[^/]+/watch\?(?:.*&)?v=(?P<code1>[^&\s]+)"
2021-06-07 10:45:54 +02:00
r"|youtu\.be/(?P<code2>[^&\s]+))"
)
def __init__(self, bot):
super().__init__(bot)
self.priority = -3
self._youtube_plugin = None
@property
def youtube_plugin(self):
if self._youtube_plugin is None:
self._youtube_plugin = self.bot.get_plugin("youtube")
return self._youtube_plugin
def on_welcome(self, _):
if not (self.youtube_plugin and self.youtube_plugin.is_ready):
2021-06-06 19:02:19 +02:00
self.bot.log_w("Youtube plugin is not available.")
self.is_ready = False
def on_pubmsg(self, event):
if not self.respects_handling_conditions():
return False
words = event.arguments[0].split()
for word in words:
matched = self.VIDEO_URL_RE.match(word)
if matched:
return self.handle_match(matched, event.target)
return False
def handle_match(self, matched, target):
groupdict = matched.groupdict()
code = groupdict.get("code1") or groupdict.get("code2")
if not code:
return False
try:
search_response = (
self.youtube_plugin.youtube.videos()
.list(id=code, part="snippet")
.execute()
)
except GoogleApiError:
self.signal_failure(target)
return False
title = ""
for result in search_response.get("items", []):
if result["kind"] == "youtube#video":
title = result["snippet"]["title"]
break
else:
self.signal_failure(target)
return False
self.bot.say(target, title)
return True