YouTube: set developerKey config to private

This commit is contained in:
oddluck 2020-05-09 02:13:31 +00:00
parent 88f61e0712
commit 13c2d9ef3a
3 changed files with 120 additions and 53 deletions

View File

@ -40,7 +40,7 @@ import supybot.world as world
__version__ = "2020.02.24+git" __version__ = "2020.02.24+git"
# XXX Replace this with an appropriate author or supybot.Author instance. # XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net') __author__ = supybot.Author("oddluck", "oddluck", "oddluck@riseup.net")
__maintainer__ = {} __maintainer__ = {}
# This is a dictionary mapping supybot.Author instances to lists of # This is a dictionary mapping supybot.Author instances to lists of
@ -48,11 +48,12 @@ __maintainer__ = {}
__contributors__ = {} __contributors__ = {}
# This is a url where the most recent plugin package can be downloaded. # This is a url where the most recent plugin package can be downloaded.
__url__ = 'https://github.com/oddluck/limnoria-plugins/' __url__ = "https://github.com/oddluck/limnoria-plugins/"
from . import config from . import config
from . import plugin from . import plugin
from imp import reload from imp import reload
# In case we're being reloaded. # In case we're being reloaded.
reload(config) reload(config)
reload(plugin) reload(plugin)

View File

@ -30,9 +30,11 @@
import supybot.conf as conf import supybot.conf as conf
import supybot.registry as registry import supybot.registry as registry
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('YouTube')
_ = PluginInternationalization("YouTube")
except: except:
# Placeholder that allows to run the plugin on a bot # Placeholder that allows to run the plugin on a bot
# without the i18n module # without the i18n module
@ -45,28 +47,59 @@ def configure(advanced):
# user or not. You should effect your configuration by manipulating the # user or not. You should effect your configuration by manipulating the
# registry as appropriate. # registry as appropriate.
from supybot.questions import expect, anything, something, yn from supybot.questions import expect, anything, something, yn
conf.registerPlugin('YouTube', True)
conf.registerPlugin("YouTube", True)
YouTube = conf.registerPlugin('YouTube') YouTube = conf.registerPlugin("YouTube")
conf.registerGlobalValue(YouTube, 'developerKey', conf.registerGlobalValue(
registry.String("", _("""Google API key. Required."""))) YouTube,
"developerKey",
registry.String("", _("""Google API key. Required."""), private=True),
)
conf.registerChannelValue(YouTube, 'sortOrder', conf.registerChannelValue(
registry.String("relevance", _("""Method used to order API responses: date, rating, relevance, title, viewCount"""))) YouTube,
"sortOrder",
registry.String(
"relevance",
_(
"""
Method used to order API responses: date, rating, relevance, title, viewCount
"""
),
),
)
conf.registerChannelValue(YouTube, 'safeSearch', conf.registerChannelValue(
registry.String("none", _("""Safe search filtering: none, moderate, strict"""))) YouTube,
"safeSearch",
registry.String("none", _("""Safe search filtering: none, moderate, strict""")),
)
conf.registerChannelValue(YouTube, 'logo', conf.registerChannelValue(
registry.String("\x030,4 ► \x031,0YouTube", _("""Logo used with $yt_logo in template"""))) YouTube,
"logo",
registry.String(
"\x030,4 ► \x031,0YouTube", _("""Logo used with $yt_logo in template""")
),
)
conf.registerChannelValue(YouTube, 'template', conf.registerChannelValue(
registry.String("{{logo}} :: {{link}} :: {{title}} :: Duration: {{duration}} :: Views: {{views}} :: Uploader: {{uploader}} :: Uploaded: {{published}} :: {{likes}} likes :: {{dislikes}} dislikes :: {{favorites}} favorites :: {{comments}} comments", _("""Template used for search result replies"""))) YouTube,
"template",
registry.String(
"{{logo}} :: {{link}} :: {{title}} :: Duration: {{duration}} :: Views: {{views}} "
":: Uploader: {{uploader}} :: Uploaded: {{published}} :: {{likes}} likes :: "
"{{dislikes}} dislikes :: {{favorites}} favorites :: {{comments}} comments",
_("""Template used for search result replies"""),
),
)
conf.registerChannelValue(YouTube, 'useBold', conf.registerChannelValue(
registry.Boolean(True, _("""Use bold in replies"""))) YouTube, "useBold", registry.Boolean(True, _("""Use bold in replies"""))
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -43,36 +43,46 @@ from urllib.parse import urlencode
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('YouTube')
_ = PluginInternationalization("YouTube")
except ImportError: except ImportError:
# Placeholder that allows to run the plugin on a bot # Placeholder that allows to run the plugin on a bot
# without the i18n module # without the i18n module
_ = lambda x: x _ = lambda x: x
class YouTube(callbacks.Plugin): class YouTube(callbacks.Plugin):
"""Queries OMDB database for information about YouTube titles""" """Queries OMDB database for information about YouTube titles"""
threaded = True threaded = True
def dosearch(self, query): def dosearch(self, query):
apikey = self.registryValue('developerKey') apikey = self.registryValue("developerKey")
safe_search = self.registryValue("safeSearch", dynamic.channel) safe_search = self.registryValue("safeSearch", dynamic.channel)
sort_order = self.registryValue("sortOrder", dynamic.channel) sort_order = self.registryValue("sortOrder", dynamic.channel)
video_id = None video_id = None
opts = {"q": query, opts = {
"part": "snippet", "q": query,
"maxResults": "1", "part": "snippet",
"order": sort_order, "maxResults": "1",
"key": apikey, "order": sort_order,
"safeSearch": safe_search, "key": apikey,
"type": "video"} "safeSearch": safe_search,
api_url = "https://www.googleapis.com/youtube/v3/search?{0}".format(urlencode(opts)) "type": "video",
}
api_url = "https://www.googleapis.com/youtube/v3/search?{0}".format(
urlencode(opts)
)
try: try:
log.debug("YouTube: requesting %s" % (api_url)) log.debug("YouTube: requesting %s" % (api_url))
request = requests.get(api_url, timeout=10) request = requests.get(api_url, timeout=10)
response = json.loads(request.content) response = json.loads(request.content)
video_id = response["items"][0]["id"]["videoId"] video_id = response["items"][0]["id"]["videoId"]
except Exception: except Exception:
log.error("YouTube: YouTube API HTTP %s: %s" % (request.status_code, request.content.decode())) log.error(
"YouTube: YouTube API HTTP %s: %s"
% (request.status_code, request.content.decode())
)
pass pass
return video_id return video_id
@ -112,7 +122,7 @@ class YouTube(callbacks.Plugin):
"""<search term> """<search term>
Search for YouTube videos Search for YouTube videos
""" """
apikey = self.registryValue('developerKey') apikey = self.registryValue("developerKey")
if not apikey: if not apikey:
irc.reply("Error: You need to set an API key to use this plugin.") irc.reply("Error: You need to set an API key to use this plugin.")
return return
@ -127,7 +137,8 @@ class YouTube(callbacks.Plugin):
"part": "snippet,statistics,contentDetails", "part": "snippet,statistics,contentDetails",
"maxResults": 1, "maxResults": 1,
"key": apikey, "key": apikey,
"id": video_id} "id": video_id,
}
opts = urlencode(opts) opts = urlencode(opts)
api_url = "https://www.googleapis.com/youtube/v3/videos?%s" % (opts) api_url = "https://www.googleapis.com/youtube/v3/videos?%s" % (opts)
log.debug("YouTube: requesting %s" % (api_url)) log.debug("YouTube: requesting %s" % (api_url))
@ -153,50 +164,72 @@ class YouTube(callbacks.Plugin):
if "likeCount" in statistics: if "likeCount" in statistics:
like_count = "{:,}".format(int(statistics["likeCount"])) like_count = "{:,}".format(int(statistics["likeCount"]))
if "dislikeCount" in statistics: if "dislikeCount" in statistics:
dislike_count = "{:,}".format(int(statistics["dislikeCount"])) dislike_count = "{:,}".format(
int(statistics["dislikeCount"])
)
if "favoriteCount" in statistics: if "favoriteCount" in statistics:
favorite_count = "{:,}".format(int(statistics["favoriteCount"])) favorite_count = "{:,}".format(
int(statistics["favoriteCount"])
)
if "commentCount" in statistics: if "commentCount" in statistics:
comment_count = "{:,}".format(int(statistics["commentCount"])) comment_count = "{:,}".format(
int(statistics["commentCount"])
)
channel_title = snippet["channelTitle"] channel_title = snippet["channelTitle"]
video_duration = video["contentDetails"]["duration"] video_duration = video["contentDetails"]["duration"]
duration_seconds = self.get_total_seconds_from_duration(video_duration) duration_seconds = self.get_total_seconds_from_duration(
video_duration
)
if duration_seconds > 0: if duration_seconds > 0:
duration = self.get_duration_from_seconds(duration_seconds) duration = self.get_duration_from_seconds(
duration_seconds
)
else: else:
duration = "LIVE" duration = "LIVE"
published = snippet['publishedAt'] published = snippet["publishedAt"]
published = self.get_published_date(published) published = self.get_published_date(published)
yt_logo = self.get_youtube_logo() yt_logo = self.get_youtube_logo()
link = "https://youtu.be/%s" % (video_id) link = "https://youtu.be/%s" % (video_id)
compiled_template = yt_template.render({ compiled_template = yt_template.render(
"title": title, {
"duration": duration, "title": title,
"views": view_count, "duration": duration,
"likes": like_count, "views": view_count,
"dislikes": dislike_count, "likes": like_count,
"comments": comment_count, "dislikes": dislike_count,
"favorites": favorite_count, "comments": comment_count,
"uploader": channel_title, "favorites": favorite_count,
"link": link, "uploader": channel_title,
"published": published, "link": link,
"logo": yt_logo "published": published,
}) "logo": yt_logo,
}
)
title = compiled_template title = compiled_template
else: else:
log.debug("YouTube: video appears to be private; no results!") log.debug(
"YouTube: video appears to be private; no results!"
)
except IndexError as e: except IndexError as e:
log.error("YouTube: IndexError parsing Youtube API JSON response: %s" % (str(e))) log.error(
"YouTube: IndexError parsing Youtube API JSON response: %s"
% (str(e))
)
else: else:
log.error("YouTube: Error parsing Youtube API JSON response") log.error("YouTube: Error parsing Youtube API JSON response")
else: else:
log.error("YouTube: YouTube API HTTP %s: %s" % (request.status_code, request.content.decode())) log.error(
"YouTube: YouTube API HTTP %s: %s"
% (request.status_code, request.content.decode())
)
if title: if title:
use_bold = self.registryValue("useBold", channel) use_bold = self.registryValue("useBold", channel)
if use_bold: if use_bold:
title = ircutils.bold(title) title = ircutils.bold(title)
irc.reply(title, prefixNick=False) irc.reply(title, prefixNick=False)
yt = wrap(yt, ['text'])
yt = wrap(yt, ["text"])
Class = YouTube Class = YouTube