In Python 3.10 match will become a soft keyword. The program would still work but syntax highlighting is getting weird.
70 lines
2 KiB
Python
70 lines
2 KiB
Python
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(
|
|
r"https?:\/\/(?:[^/]+/watch\?(?:.*&)?v=(?P<code1>[^&\s]+)"
|
|
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):
|
|
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
|