youtube: add plugin
This commit is contained in:
parent
f83f7fd011
commit
8773141406
|
@ -83,5 +83,9 @@
|
|||
"ambiguous_response": "It is ambiguous.",
|
||||
"empty_response": "I can't find it."
|
||||
}
|
||||
"youtube": {
|
||||
"commands": ["youtube"],
|
||||
"api_key": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,3 +3,6 @@ wikipedia
|
|||
|
||||
# Journée Mondiale
|
||||
beautifulsoup4
|
||||
|
||||
# Google API (i.e. Youtube)
|
||||
google-api-python-client
|
||||
|
|
71
edmond/plugins/youtube.py
Normal file
71
edmond/plugins/youtube.py
Normal file
|
@ -0,0 +1,71 @@
|
|||
try:
|
||||
from googleapiclient.discovery import build as gapi_discovery_build
|
||||
from googleapiclient.errors import Error as GoogleApiError
|
||||
DEPENDENCIES_FOUND = True
|
||||
except ImportError:
|
||||
DEPENDENCIES_FOUND = False
|
||||
|
||||
from edmond.plugin import Plugin
|
||||
|
||||
|
||||
class YoutubePlugin(Plugin):
|
||||
|
||||
REQUIRED_CONFIGS = ["commands", "api_key"]
|
||||
VIDEO_URL_FMT = "https://www.youtube.com/watch?v={}"
|
||||
CHANNEL_URL_FMT = "https://www.youtube.com/channel/{}"
|
||||
PLAYLIST_URL_FMT = "https://www.youtube.com/playlist?list={}"
|
||||
|
||||
def __init__(self, bot):
|
||||
super().__init__(bot)
|
||||
self._youtube = None
|
||||
|
||||
@property
|
||||
def youtube(self):
|
||||
if self._youtube is None:
|
||||
self._youtube = gapi_discovery_build(
|
||||
"youtube",
|
||||
"v3",
|
||||
developerKey=self.config["api_key"]
|
||||
)
|
||||
return self._youtube
|
||||
|
||||
def has_api_key(self):
|
||||
return self.config["api_key"] != ""
|
||||
|
||||
def on_pubmsg(self, event):
|
||||
if not self.has_api_key():
|
||||
return False
|
||||
if self.should_handle_command(event.arguments[0]):
|
||||
self.handle_commands(event.target)
|
||||
return True
|
||||
return False
|
||||
|
||||
def handle_commands(self, target):
|
||||
if self.command.ident == self.config["commands"][0]:
|
||||
try:
|
||||
search_response = self.youtube.search().list(
|
||||
q=self.command.content,
|
||||
part="id,snippet",
|
||||
maxResults=1,
|
||||
).execute()
|
||||
except GoogleApiError:
|
||||
self.signal_failure(target)
|
||||
return
|
||||
|
||||
link = ""
|
||||
for result in search_response.get("items", []):
|
||||
if result["id"]["kind"] == "youtube#video":
|
||||
video_id = result["id"]["videoId"]
|
||||
link = self.VIDEO_URL_FMT.format(video_id)
|
||||
elif result["id"]["kind"] == "youtube#channel":
|
||||
channel_id = result["id"]["channelId"]
|
||||
link = self.CHANNEL_URL_FMT.format(channel_id)
|
||||
elif result["id"]["kind"] == "youtube#playlist":
|
||||
playlist_id = result["id"]["playlistId"]
|
||||
link = self.PLAYLIST_URL_FMT.format(playlist_id)
|
||||
if link:
|
||||
break
|
||||
else:
|
||||
self.signal_failure(target)
|
||||
return
|
||||
self.bot.say(target, link)
|
Loading…
Reference in a new issue