Set more config variables private

This commit is contained in:
oddluck 2020-05-09 01:43:09 -04:00
parent 13c2d9ef3a
commit baf3f4823e
18 changed files with 986 additions and 456 deletions

View File

@ -53,7 +53,7 @@ conf.registerGlobalValue(Geo, 'datalastupdated',
registry.PositiveInteger(1, """An integer representing the time since epoch the .dat file was last updated.""")) registry.PositiveInteger(1, """An integer representing the time since epoch the .dat file was last updated."""))
conf.registerGlobalValue(Geo, 'licenseKey', conf.registerGlobalValue(Geo, 'licenseKey',
registry.String('', """MaxMind license key.""")) registry.String('', """MaxMind license key.""", private=True))
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:

View File

@ -40,21 +40,24 @@ 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('butterscotchstallion', 'butterscotchstallion', __author__ = supybot.Author("butterscotchstallion", "butterscotchstallion", "")
'') __maintainer__ = getattr(
__maintainer__ = getattr(supybot.authors, 'oddluck', supybot.authors,
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net')) "oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of # This is a dictionary mapping supybot.Author instances to lists of
# contributions. # contributions.
__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('IMDb')
_ = PluginInternationalization("IMDb")
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,24 +47,55 @@ 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('IMDb', True)
conf.registerPlugin("IMDb", True)
IMDb = conf.registerPlugin('IMDb') IMDb = conf.registerPlugin("IMDb")
conf.registerChannelValue(IMDb, 'template', conf.registerChannelValue(
registry.String("\x02\x031,8 IMDb \x0F\x02 :: $title ($year, $country, [$rated], $genre, $runtime) :: IMDb: $imdbRating | MC: $metascore | RT: $tomatoMeter :: http://imdb.com/title/$imdbID :: $plot :: Director: $director :: Cast: $actors :: Writer: $writer", _("""Template for the output of a search query."""))) IMDb,
"template",
registry.String(
"\x02\x031,8 IMDb \x0F\x02 :: $title ($year, $country, [$rated], $genre, "
"$runtime) :: IMDb: $imdbRating | MC: $metascore | RT: $tomatoMeter :: "
"http://imdb.com/title/$imdbID :: $plot :: Director: $director :: Cast: "
"$actors :: Writer: $writer",
_("""Template for the output of a search query."""),
),
)
conf.registerChannelValue(IMDb, 'noResultsMessage', conf.registerChannelValue(
registry.String("No results for that query.", _("""This message is sent when there are no results"""))) IMDb,
"noResultsMessage",
registry.String(
"No results for that query.",
_("""This message is sent when there are no results"""),
),
)
conf.registerGlobalValue(IMDb, 'omdbAPI', conf.registerGlobalValue(
registry.String('', _("""OMDB API Key"""))) IMDb, "omdbAPI", registry.String("", _("""OMDB API Key"""), private=True)
)
conf.registerChannelValue(IMDb, 'googleSearch', conf.registerChannelValue(
registry.Boolean(True, _("""Use google to perform searches for better results."""))) IMDb,
"googleSearch",
registry.Boolean(True, _("""Use google to perform searches for better results.""")),
)
conf.registerGlobalValue(IMDb, 'userAgents', conf.registerGlobalValue(
registry.CommaSeparatedListOfStrings(["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"], _("""Reported user agent when fetching links"""))) IMDb,
"userAgents",
registry.CommaSeparatedListOfStrings(
[
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
"Mozilla/5.0 (Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0",
"Mozilla/5.0 (Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0",
],
_("""Reported user agent when fetching links"""),
),
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -43,14 +43,17 @@ import re
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('IMDb')
_ = PluginInternationalization("IMDb")
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 IMDb(callbacks.Plugin): class IMDb(callbacks.Plugin):
"""Queries OMDB database for information about IMDb titles""" """Queries OMDB database for information about IMDb titles"""
threaded = True threaded = True
def dosearch(self, query): def dosearch(self, query):
@ -60,12 +63,13 @@ class IMDb(callbacks.Plugin):
searchurl += "{0} site:imdb.com/title/".format(query) searchurl += "{0} site:imdb.com/title/".format(query)
agents = self.registryValue("userAgents") agents = self.registryValue("userAgents")
ua = random.choice(agents) ua = random.choice(agents)
header = {'User-Agent': ua} header = {"User-Agent": ua}
data = requests.get(searchurl, headers=header, timeout=10) data = requests.get(searchurl, headers=header, timeout=10)
data.raise_for_status() data.raise_for_status()
soup = BeautifulSoup(data.content) soup = BeautifulSoup(data.content)
elements = soup.select('.r a') url = soup.find(
url = elements[0]['href'] "a", attrs={"href": re.compile(r"https://www.imdb.com/title/tt\d+/$")}
)["href"]
except Exception: except Exception:
pass pass
return url return url
@ -77,21 +81,27 @@ class IMDb(callbacks.Plugin):
channel = msg.channel channel = msg.channel
url = result = None url = result = None
id = stop = False id = stop = False
apikey = self.registryValue('omdbAPI') apikey = self.registryValue("omdbAPI")
if not apikey: if not apikey:
irc.reply("Error: You must set an API key to use this plugin.") irc.reply("Error: You must set an API key to use this plugin.")
return return
if re.match('tt\d+', query.strip()): if re.match(r"tt\d+", query.strip()):
id = True id = True
url = "http://imdb.com/title/{0}".format(query.strip()) url = "http://imdb.com/title/{0}".format(query.strip())
if not id and self.registryValue("googleSearch", channel): if not id and self.registryValue("googleSearch", channel):
url = self.dosearch(query) url = self.dosearch(query)
if url and 'imdb.com/title/' in url: if url and "imdb.com/title/" in url:
imdb_id = url.split("/title/")[1].rstrip("/") imdb_id = url.split("/title/")[1].rstrip("/")
omdb_url = "http://www.omdbapi.com/?i=%s&plot=short&r=json&apikey=%s" % (imdb_id, apikey) omdb_url = "http://www.omdbapi.com/?i=%s&plot=short&r=json&apikey=%s" % (
imdb_id,
apikey,
)
log.debug("IMDb: requesting %s" % omdb_url) log.debug("IMDb: requesting %s" % omdb_url)
else: else:
omdb_url = "http://www.omdbapi.com/?t=%s&plot=short&r=json&apikey=%s" % (query, apikey) omdb_url = "http://www.omdbapi.com/?t=%s&plot=short&r=json&apikey=%s" % (
query,
apikey,
)
try: try:
request = requests.get(omdb_url, timeout=10) request = requests.get(omdb_url, timeout=10)
if request.status_code == requests.codes.ok: if request.status_code == requests.codes.ok:
@ -99,11 +109,14 @@ class IMDb(callbacks.Plugin):
not_found = "Error" in response not_found = "Error" in response
unknown_error = response["Response"] != "True" unknown_error = response["Response"] != "True"
if not_found or unknown_error: if not_found or unknown_error:
match = re.match('(.*) \(*(\d\d\d\d)\)*$', query.strip()) match = re.match(r"(.*) \(*(\d\d\d\d)\)*$", query.strip())
if match: if match:
query = match.group(1).strip() query = match.group(1).strip()
year = match.group(2).strip() year = match.group(2).strip()
omdb_url = "http://www.omdbapi.com/?t=%s&y=%s&plot=short&r=json&apikey=%s" % (query, year, apikey) omdb_url = (
"http://www.omdbapi.com/?t=%s&y=%s&plot=short&r=json&apikey=%s"
% (query, year, apikey)
)
request = requests.get(omdb_url, timeout=10) request = requests.get(omdb_url, timeout=10)
if request.status_code == requests.codes.ok: if request.status_code == requests.codes.ok:
response = json.loads(request.content) response = json.loads(request.content)
@ -112,11 +125,17 @@ class IMDb(callbacks.Plugin):
if not_found or unknown_error: if not_found or unknown_error:
log.debug("IMDb: OMDB error for %s" % (omdb_url)) log.debug("IMDb: OMDB error for %s" % (omdb_url))
else: else:
log.error("IMDb OMDB API %s - %s" % (request.status_code, request.content.decode())) log.error(
"IMDb OMDB API %s - %s"
% (request.status_code, request.content.decode())
)
else: else:
log.debug("IMDb: OMDB error for %s" % (omdb_url)) log.debug("IMDb: OMDB error for %s" % (omdb_url))
query = re.sub('\d\d\d\d', '', query) query = re.sub(r"\d\d\d\d", "", query)
omdb_url = "http://www.omdbapi.com/?s=%s&plot=short&r=json&apikey=%s" % (query, apikey) omdb_url = (
"http://www.omdbapi.com/?s=%s&plot=short&r=json&apikey=%s"
% (query, apikey)
)
request = requests.get(omdb_url, timeout=10) request = requests.get(omdb_url, timeout=10)
if request.status_code == requests.codes.ok: if request.status_code == requests.codes.ok:
response = json.loads(request.content) response = json.loads(request.content)
@ -124,42 +143,78 @@ class IMDb(callbacks.Plugin):
unknown_error = response["Response"] != "True" unknown_error = response["Response"] != "True"
if not_found or unknown_error: if not_found or unknown_error:
log.debug("IMDb: OMDB error for %s" % (omdb_url)) log.debug("IMDb: OMDB error for %s" % (omdb_url))
elif response.get("Search") and len(response.get("Search")) == 1: elif (
response.get("Search")
and len(response.get("Search")) == 1
):
imdb_id = response["Search"][0]["imdbID"] imdb_id = response["Search"][0]["imdbID"]
omdb_url = "http://www.omdbapi.com/?i=%s&plot=short&r=json&apikey=%s" % (imdb_id, apikey) omdb_url = (
"http://www.omdbapi.com/?i=%s&plot=short&r=json&apikey=%s"
% (imdb_id, apikey)
)
request = requests.get(omdb_url, timeout=10) request = requests.get(omdb_url, timeout=10)
if request.status_code == requests.codes.ok: if request.status_code == requests.codes.ok:
response = json.loads(request.content) response = json.loads(request.content)
not_found = "Error" in response not_found = "Error" in response
unknown_error = response["Response"] != "True" unknown_error = response["Response"] != "True"
if not_found or unknown_error: if not_found or unknown_error:
log.debug("IMDb: OMDB error for %s" % (omdb_url)) log.debug(
"IMDb: OMDB error for %s" % (omdb_url)
)
else: else:
log.error("IMDb OMDB API %s - %s" % (request.status_code, request.content.decode())) log.error(
elif response.get("Search") and len(response.get("Search")) > 1: "IMDb OMDB API %s - %s"
% (
request.status_code,
request.content.decode(),
)
)
elif (
response.get("Search")
and len(response.get("Search")) > 1
):
reply = "No title found. Did you mean:" reply = "No title found. Did you mean:"
for item in response["Search"]: for item in response["Search"]:
reply += " {0} ({1}) [{2}],".format(item["Title"], item["Year"], item["imdbID"]) reply += " {0} ({1}) [{2}],".format(
irc.reply(reply.rstrip(',')) item["Title"], item["Year"], item["imdbID"]
)
irc.reply(reply.rstrip(","))
not_found = stop = True not_found = stop = True
return return
else: else:
log.error("IMDb OMDB API %s - %s" % (request.status_code, request.content.decode())) log.error(
"IMDb OMDB API %s - %s"
% (request.status_code, request.content.decode())
)
if not not_found or not unknown_error: if not not_found or not unknown_error:
meta = tomato = None meta = tomato = None
imdb_template = self.registryValue("template", channel) imdb_template = self.registryValue("template", channel)
imdb_template = imdb_template.replace("$title", str(response.get("Title"))) imdb_template = imdb_template.replace(
imdb_template = imdb_template.replace("$year", str(response.get("Year"))) "$title", str(response.get("Title"))
imdb_template = imdb_template.replace("$country", str(response.get("Country"))) )
imdb_template = imdb_template.replace("$director", str(response.get("Director"))) imdb_template = imdb_template.replace(
imdb_template = imdb_template.replace("$plot", str(response.get("Plot"))) "$year", str(response.get("Year"))
imdb_template = imdb_template.replace("$imdbID", str(response.get("imdbID"))) )
imdb_template = imdb_template.replace("$imdbRating", str(response.get("imdbRating"))) imdb_template = imdb_template.replace(
"$country", str(response.get("Country"))
)
imdb_template = imdb_template.replace(
"$director", str(response.get("Director"))
)
imdb_template = imdb_template.replace(
"$plot", str(response.get("Plot"))
)
imdb_template = imdb_template.replace(
"$imdbID", str(response.get("imdbID"))
)
imdb_template = imdb_template.replace(
"$imdbRating", str(response.get("imdbRating"))
)
for rating in response["Ratings"]: for rating in response["Ratings"]:
if rating["Source"] == "Rotten Tomatoes": if rating["Source"] == "Rotten Tomatoes":
tomato = rating.get("Value") tomato = rating.get("Value")
if rating["Source"] == "Metacritic": if rating["Source"] == "Metacritic":
meta = "{0}%".format(rating.get("Value").split('/')[0]) meta = "{0}%".format(rating.get("Value").split("/")[0])
if meta: if meta:
imdb_template = imdb_template.replace("$metascore", meta) imdb_template = imdb_template.replace("$metascore", meta)
else: else:
@ -168,22 +223,51 @@ class IMDb(callbacks.Plugin):
imdb_template = imdb_template.replace("$tomatoMeter", tomato) imdb_template = imdb_template.replace("$tomatoMeter", tomato)
else: else:
imdb_template = imdb_template.replace("$tomatoMeter", "N/A") imdb_template = imdb_template.replace("$tomatoMeter", "N/A")
imdb_template = imdb_template.replace("$released", str(response.get("Released"))) imdb_template = imdb_template.replace(
imdb_template = imdb_template.replace("$genre", str(response.get("Genre"))) "$released", str(response.get("Released"))
imdb_template = imdb_template.replace("$released", str(response.get("Released"))) )
imdb_template = imdb_template.replace("$awards", str(response.get("Awards"))) imdb_template = imdb_template.replace(
imdb_template = imdb_template.replace("$actors", str(response.get("Actors"))) "$genre", str(response.get("Genre"))
imdb_template = imdb_template.replace("$rated", str(response.get("Rated"))) )
imdb_template = imdb_template.replace("$runtime", str(response.get("Runtime"))) imdb_template = imdb_template.replace(
imdb_template = imdb_template.replace("$writer", str(response.get("Writer"))) "$released", str(response.get("Released"))
imdb_template = imdb_template.replace("$votes", str(response.get("imdbVotes"))) )
imdb_template = imdb_template.replace("$boxOffice", str(response.get("BoxOffice"))) imdb_template = imdb_template.replace(
imdb_template = imdb_template.replace("$production", str(response.get("Production"))) "$awards", str(response.get("Awards"))
imdb_template = imdb_template.replace("$website", str(response.get("Website"))) )
imdb_template = imdb_template.replace("$poster", str(response.get("Poster"))) imdb_template = imdb_template.replace(
"$actors", str(response.get("Actors"))
)
imdb_template = imdb_template.replace(
"$rated", str(response.get("Rated"))
)
imdb_template = imdb_template.replace(
"$runtime", str(response.get("Runtime"))
)
imdb_template = imdb_template.replace(
"$writer", str(response.get("Writer"))
)
imdb_template = imdb_template.replace(
"$votes", str(response.get("imdbVotes"))
)
imdb_template = imdb_template.replace(
"$boxOffice", str(response.get("BoxOffice"))
)
imdb_template = imdb_template.replace(
"$production", str(response.get("Production"))
)
imdb_template = imdb_template.replace(
"$website", str(response.get("Website"))
)
imdb_template = imdb_template.replace(
"$poster", str(response.get("Poster"))
)
result = imdb_template result = imdb_template
else: else:
log.error("IMDb OMDB API %s - %s" % (request.status_code, request.content.decode())) log.error(
"IMDb OMDB API %s - %s"
% (request.status_code, request.content.decode())
)
except requests.exceptions.Timeout as e: except requests.exceptions.Timeout as e:
log.error("IMDb Timeout: %s" % (str(e))) log.error("IMDb Timeout: %s" % (str(e)))
except requests.exceptions.ConnectionError as e: except requests.exceptions.ConnectionError as e:
@ -195,7 +279,9 @@ class IMDb(callbacks.Plugin):
irc.reply(result, prefixNick=False) irc.reply(result, prefixNick=False)
elif not stop: elif not stop:
irc.error(self.registryValue("noResultsMessage", channel)) irc.error(self.registryValue("noResultsMessage", channel))
imdb = wrap(imdb, ['text'])
imdb = wrap(imdb, ["text"])
Class = IMDb Class = IMDb

View File

@ -39,19 +39,19 @@ 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', __author__ = supybot.Author("oddluck", "oddluck", "oddluck@riseup.net")
'oddluck@riseup.net')
# This is a dictionary mapping supybot.Author instances to lists of # This is a dictionary mapping supybot.Author instances to lists of
# contributions. # contributions.
__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

@ -29,9 +29,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('Lyrics')
_ = PluginInternationalization("Lyrics")
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
@ -44,12 +46,28 @@ 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('Lyrics', True)
Lyrics = conf.registerPlugin('Lyrics') conf.registerPlugin("Lyrics", True)
conf.registerChannelValue(Lyrics, 'googleSearch',
registry.Boolean(True, _("""Use google to perform searches for better results.""")))
conf.registerGlobalValue(Lyrics, 'userAgents', Lyrics = conf.registerPlugin("Lyrics")
registry.CommaSeparatedListOfStrings(["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"], _("""Reported user agent when fetching links""")))
conf.registerChannelValue(
Lyrics,
"googleSearch",
registry.Boolean(True, _("""Use google to perform searches for better results.""")),
)
conf.registerGlobalValue(
Lyrics,
"userAgents",
registry.CommaSeparatedListOfStrings(
[
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
"Mozilla/5.0 (Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0",
"Mozilla/5.0 (Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0",
],
_("""Reported user agent when fetching links"""),
),
)

View File

@ -42,14 +42,17 @@ import random
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Weed')
_ = PluginInternationalization("Weed")
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 Lyrics(callbacks.Plugin): class Lyrics(callbacks.Plugin):
"""Retrieves song lyrics""" """Retrieves song lyrics"""
threaded = True threaded = True
def dosearch(self, lyric): def dosearch(self, lyric):
@ -60,33 +63,33 @@ class Lyrics(callbacks.Plugin):
searchurl += "{0} site:lyrics.fandom.com/wiki/".format(lyric) searchurl += "{0} site:lyrics.fandom.com/wiki/".format(lyric)
agents = self.registryValue("userAgents") agents = self.registryValue("userAgents")
ua = random.choice(agents) ua = random.choice(agents)
header = {'User-Agent': ua} header = {"User-Agent": ua}
data = requests.get(searchurl, headers=header, timeout=10) data = requests.get(searchurl, headers=header, timeout=10)
data.raise_for_status() data.raise_for_status()
log.debug(data.content.decode()) log.debug(data.content.decode())
soup = BeautifulSoup(data.content) soup = BeautifulSoup(data.content)
elements = soup.select('.r a') elements = soup.select(".r a")
title = soup.find("h3").getText().replace(":", " - ").split('|')[0] title = soup.find("h3").getText().replace(":", " - ").split("|")[0]
url = elements[0]['href'] url = elements[0]["href"]
except Exception: except Exception:
pass pass
return title, url return title, url
def getlyrics(self, query): def getlyrics(self, query):
lyrics = None lyrics = None
if 'lyrics.fandom.com/wiki/' in query: if "lyrics.fandom.com/wiki/" in query:
try: try:
log.debug("Lyrics: requesting {0}".format(query)) log.debug("Lyrics: requesting {0}".format(query))
lyrics = pylyrics3.get_lyrics_from_url(query) lyrics = pylyrics3.get_lyrics_from_url(query)
lyrics = re.sub('(?<!\.|\!|\?)\s\\n', '.', lyrics).replace(" \n", "") lyrics = re.sub(r"(?<!\.|\!|\?)\s\\n", ".", lyrics).replace(" \n", "")
except Exception: except Exception:
pass pass
else: else:
try: try:
log.debug("Lyrics: requesting {0}".format(query)) log.debug("Lyrics: requesting {0}".format(query))
query = query.split(',', 1) query = query.split(",", 1)
lyrics = pylyrics3.get_song_lyrics(query[0].strip(), query[1].strip()) lyrics = pylyrics3.get_song_lyrics(query[0].strip(), query[1].strip())
lyrics = re.sub('(?<!\.|\!|\?)\s\\n', '.', lyrics).replace(" \n", "") lyrics = re.sub(r"(?<!\.|\!|\?)\s\\n", ".", lyrics).replace(" \n", "")
except Exception: except Exception:
pass pass
return lyrics return lyrics
@ -100,7 +103,7 @@ class Lyrics(callbacks.Plugin):
url = None url = None
if self.registryValue("googleSearch", channel): if self.registryValue("googleSearch", channel):
title, url = self.dosearch(lyric) title, url = self.dosearch(lyric)
if url and title and 'lyrics.fandom.com/wiki/' in url: if url and title and "lyrics.fandom.com/wiki/" in url:
try: try:
lyrics = self.getlyrics(url) lyrics = self.getlyrics(url)
if lyrics: if lyrics:
@ -113,7 +116,7 @@ class Lyrics(callbacks.Plugin):
irc.reply("Unable to retrieve lyrics from {0}".format(url)) irc.reply("Unable to retrieve lyrics from {0}".format(url))
return return
else: else:
if ',' in lyric: if "," in lyric:
try: try:
lyrics = self.getlyrics(lyric) lyrics = self.getlyrics(lyric)
if lyrics: if lyrics:
@ -127,6 +130,8 @@ class Lyrics(callbacks.Plugin):
else: else:
irc.reply("Searches must be formatted as <artist>, <song title>") irc.reply("Searches must be formatted as <artist>, <song title>")
return return
lyric = wrap(lyric, ['text'])
lyric = wrap(lyric, ["text"])
Class = Lyrics Class = Lyrics

View File

@ -486,7 +486,9 @@ conf.registerChannelValue(
# Twitch API Key # Twitch API Key
conf.registerGlobalValue( conf.registerGlobalValue(
SpiffyTitles.twitch, "clientID", registry.String("", _("""Twitch API Client_ID""")) SpiffyTitles.twitch,
"clientID",
registry.String("", _("""Twitch API Client_ID"""), private=True),
) )
# Twitch Logo # Twitch Logo
@ -579,7 +581,9 @@ conf.registerChannelValue(
# OMDB API Key # OMDB API Key
conf.registerGlobalValue( conf.registerGlobalValue(
SpiffyTitles.imdb, "omdbAPI", registry.String("", _("""OMDB API Key""")) SpiffyTitles.imdb,
"omdbAPI",
registry.String("", _("""OMDB API Key"""), private=True),
) )
# IMDB Logo # IMDB Logo

View File

@ -49,10 +49,10 @@ def configure(advanced):
TextArt = conf.registerPlugin('TextArt') TextArt = conf.registerPlugin('TextArt')
conf.registerGlobalValue(TextArt, 'pasteAPI', conf.registerGlobalValue(TextArt, 'pasteAPI',
registry.String('', _("""Paste.ee API Key"""))) registry.String('', _("""Paste.ee API Key"""), private=True))
conf.registerGlobalValue(TextArt, 'imgurAPI', conf.registerGlobalValue(TextArt, 'imgurAPI',
registry.String('', _("""Imgur Client ID"""))) registry.String('', _("""Imgur Client ID"""), private=True))
conf.registerChannelValue(TextArt, 'pasteEnable', conf.registerChannelValue(TextArt, 'pasteEnable',
registry.Boolean(False, _("""Turns on and off paste.ee support"""))) registry.Boolean(False, _("""Turns on and off paste.ee support""")))

View File

@ -40,20 +40,24 @@ 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('reticulatingspline', 'spline', 'spline') __author__ = supybot.Author("reticulatingspline", "spline", "spline")
__maintainer__ = getattr(supybot.authors, 'oddluck', __maintainer__ = getattr(
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net')) supybot.authors,
"oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of # This is a dictionary mapping supybot.Author instances to lists of
# contributions. # contributions.
__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
reload(plugin) # In case we're being reloaded. reload(plugin) # In case we're being reloaded.
reload(config) reload(config)
# Add more reloads here if you add third-party modules and want them to be # Add more reloads here if you add third-party modules and want them to be

View File

@ -31,30 +31,103 @@
import supybot.conf as conf import supybot.conf as conf
import supybot.registry as registry import supybot.registry as registry
def configure(advanced): def configure(advanced):
# This will be called by supybot to configure this module. advanced is # This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced # a bool that specifies whether the user identified himself as an 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('Tweety', True)
conf.registerPlugin("Tweety", True)
Tweety = conf.registerPlugin('Tweety') Tweety = conf.registerPlugin("Tweety")
conf.registerGlobalValue(Tweety,'consumerKey',registry.String('', """The consumer key of the application.""")) conf.registerGlobalValue(
conf.registerGlobalValue(Tweety,'consumerSecret',registry.String('', """The consumer secret of the application.""", private=True)) Tweety,
conf.registerGlobalValue(Tweety,'accessKey',registry.String('', """The Twitter Access Token key for the bot's account""")) "consumerKey",
conf.registerGlobalValue(Tweety,'accessSecret',registry.String('', """The Twitter Access Token secret for the bot's account""", private=True)) registry.String("", """The consumer key of the application.""", private=True),
conf.registerChannelValue(Tweety,'hideRealName',registry.Boolean(False, """Do not show real name when displaying tweets.""")) )
conf.registerChannelValue(Tweety,'addShortUrl',registry.Boolean(False, """Whether or not to add a short URL to the tweets.""")) conf.registerGlobalValue(
conf.registerChannelValue(Tweety,'woeid',registry.Integer(1, """Where On Earth ID. World Wide is 1. USA is 23424977.""")) Tweety,
conf.registerChannelValue(Tweety,'defaultSearchResults',registry.Integer(3, """Default number of results to return on searches.""")) "consumerSecret",
conf.registerChannelValue(Tweety,'maxSearchResults',registry.Integer(10, """Maximum number of results to return on searches""")) registry.String("", """The consumer secret of the application.""", private=True),
conf.registerChannelValue(Tweety,'defaultResults',registry.Integer(1, """Default number of results to return on timelines.""")) )
conf.registerChannelValue(Tweety,'maxResults',registry.Integer(10, """Maximum number of results to return on timelines.""")) conf.registerGlobalValue(
conf.registerChannelValue(Tweety,'outputColorTweets',registry.Boolean(False, """When outputting Tweets, display them with some color.""")) Tweety,
conf.registerChannelValue(Tweety,'hideHashtagsTrends',registry.Boolean(False, """When displaying trends, should we display #hashtags? Default is no.""")) "accessKey",
conf.registerChannelValue(Tweety,'requireVoiceOrAbove',registry.Boolean(False, """Only allows a user with voice or above on a channel to use commands.""")) registry.String(
conf.registerChannelValue(Tweety,'colorTweetURLs',registry.Boolean(False, """Try and color URLs (red) in Tweets?""")) "", """The Twitter Access Token key for the bot's account""", private=True
),
)
conf.registerGlobalValue(
Tweety,
"accessSecret",
registry.String(
"", """The Twitter Access Token secret for the bot's account""", private=True
),
)
conf.registerChannelValue(
Tweety,
"hideRealName",
registry.Boolean(False, """Do not show real name when displaying tweets."""),
)
conf.registerChannelValue(
Tweety,
"addShortUrl",
registry.Boolean(False, """Whether or not to add a short URL to the tweets."""),
)
conf.registerChannelValue(
Tweety,
"woeid",
registry.Integer(1, """Where On Earth ID. World Wide is 1. USA is 23424977."""),
)
conf.registerChannelValue(
Tweety,
"defaultSearchResults",
registry.Integer(3, """Default number of results to return on searches."""),
)
conf.registerChannelValue(
Tweety,
"maxSearchResults",
registry.Integer(10, """Maximum number of results to return on searches"""),
)
conf.registerChannelValue(
Tweety,
"defaultResults",
registry.Integer(1, """Default number of results to return on timelines."""),
)
conf.registerChannelValue(
Tweety,
"maxResults",
registry.Integer(10, """Maximum number of results to return on timelines."""),
)
conf.registerChannelValue(
Tweety,
"outputColorTweets",
registry.Boolean(
False, """When outputting Tweets, display them with some color."""
),
)
conf.registerChannelValue(
Tweety,
"hideHashtagsTrends",
registry.Boolean(
False, """When displaying trends, should we display #hashtags? Default is no."""
),
)
conf.registerChannelValue(
Tweety,
"requireVoiceOrAbove",
registry.Boolean(
False,
"""Only allows a user with voice or above on a channel to use commands.""",
),
)
conf.registerChannelValue(
Tweety,
"colorTweetURLs",
registry.Boolean(False, """Try and color URLs (red) in Tweets?"""),
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=250: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=250:

File diff suppressed because it is too large Load Diff

View File

@ -39,19 +39,19 @@ 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', __author__ = supybot.Author("oddluck", "oddluck", "oddluck@riseup.net")
'oddluck@riseup.net')
# This is a dictionary mapping supybot.Author instances to lists of # This is a dictionary mapping supybot.Author instances to lists of
# contributions. # contributions.
__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('Weed')
_ = PluginInternationalization("Weed")
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,14 +47,15 @@ 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('Weed', True)
conf.registerPlugin("Weed", True)
Weed = conf.registerPlugin('Weed') Weed = conf.registerPlugin("Weed")
conf.registerGlobalValue(Weed, 'strain_api', conf.registerGlobalValue(
registry.String('', _("""Strain API Key"""))) Weed, "strain_api", registry.String("", _("""Strain API Key"""), private=True)
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -39,14 +39,17 @@ import re
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Weed')
_ = PluginInternationalization("Weed")
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 Weed(callbacks.Plugin): class Weed(callbacks.Plugin):
"""Uses API to retrieve information""" """Uses API to retrieve information"""
threaded = True threaded = True
def strain(self, irc, msg, args, strain): def strain(self, irc, msg, args, strain):
@ -56,53 +59,68 @@ class Weed(callbacks.Plugin):
response1 = None response1 = None
response2 = None response2 = None
channel = msg.args[0] channel = msg.args[0]
strain = re.sub('[^\w\:\"\#\-\.\' ]', '', strain).casefold() strain = re.sub("[^\w\:\"\#\-\.' ]", "", strain).casefold()
strain_api = self.registryValue('strain_api') strain_api = self.registryValue("strain_api")
if not strain_api: if not strain_api:
irc.reply("Error: You must set an API key to use this plugin.") irc.reply("Error: You must set an API key to use this plugin.")
return return
url = "http://strainapi.evanbusse.com/{0}/strains/search/name/{1}".format(strain_api, strain) url = "http://strainapi.evanbusse.com/{0}/strains/search/name/{1}".format(
strain_api, strain
)
request = requests.get(url) request = requests.get(url)
ok = request.status_code == requests.codes.ok ok = request.status_code == requests.codes.ok
if not ok: if not ok:
irc.reply("Error: Unable to retrieve data. Did you set an API key?") irc.reply("Error: Unable to retrieve data. Did you set an API key?")
log.error("IMDB: API Error %s: %s" % (request.status_code, request.content.decode())) log.error(
"IMDB: API Error %s: %s"
% (request.status_code, request.content.decode())
)
return return
data = json.loads(request.content) data = json.loads(request.content)
for item in data: for item in data:
if item['desc'] is not None and item['name'].casefold() == strain: if item["desc"] is not None and item["name"].casefold() == strain:
id = item['id'] id = item["id"]
name = ircutils.bold(item['name']) name = ircutils.bold(item["name"])
type = ircutils.bold(item['race']) type = ircutils.bold(item["race"])
desc = item['desc'] desc = item["desc"]
url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(strain_api, id) url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(
strain_api, id
)
data2 = requests.get(url2) data2 = requests.get(url2)
data2 = json.loads(data2.content) data2 = json.loads(data2.content)
flavor1 = data2[0] flavor1 = data2[0]
flavor2 = data2[1] flavor2 = data2[1]
flavor3 = data2[2] flavor3 = data2[2]
response1 = "{0} | {1} | Flavors: {2}, {3}, {4} | {5}".format(name, type, flavor1, flavor2, flavor3, desc) response1 = "{0} | {1} | Flavors: {2}, {3}, {4} | {5}".format(
name, type, flavor1, flavor2, flavor3, desc
)
break break
for item in data: for item in data:
if item['desc'] is not None and item['name'].casefold() != strain: if item["desc"] is not None and item["name"].casefold() != strain:
id = item['id'] id = item["id"]
name = ircutils.bold(item['name']) name = ircutils.bold(item["name"])
type = ircutils.bold(item['race']) type = ircutils.bold(item["race"])
desc = item['desc'] desc = item["desc"]
url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(strain_api, id) url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(
strain_api, id
)
data2 = requests.get(url2) data2 = requests.get(url2)
data2 = json.loads(data2.content) data2 = json.loads(data2.content)
flavor1 = data2[0] flavor1 = data2[0]
flavor2 = data2[1] flavor2 = data2[1]
flavor3 = data2[2] flavor3 = data2[2]
response2 = "{0} | {1} | Flavors: {2}, {3}, {4} | {5}".format(name, type.title(), flavor1, flavor2, flavor3, desc) response2 = "{0} | {1} | Flavors: {2}, {3}, {4} | {5}".format(
name, type.title(), flavor1, flavor2, flavor3, desc
)
break break
if response1 != None: if response1 != None:
irc.reply(response1) irc.reply(response1)
elif response1 == None and response2 != None: elif response1 == None and response2 != None:
irc.reply(response2) irc.reply(response2)
else: else:
irc.reply('No results found, what have you been smoking?') irc.reply("No results found, what have you been smoking?")
strain = wrap(strain, ['text'])
strain = wrap(strain, ["text"])
Class = Weed Class = Weed

View File

@ -41,20 +41,24 @@ import importlib
__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('reticulatingspline', 'spline', '') __author__ = supybot.Author("reticulatingspline", "spline", "")
__maintainer__ = getattr(supybot.authors, 'oddluck', __maintainer__ = getattr(
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net')) supybot.authors,
"oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of # This is a dictionary mapping supybot.Author instances to lists of
# contributions. # contributions.
__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__ = '' # 'http://supybot.com/Members/yourname/WorldTime/download' __url__ = "" # 'http://supybot.com/Members/yourname/WorldTime/download'
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.
importlib.reload(config) importlib.reload(config)
importlib.reload(plugin) importlib.reload(plugin)

View File

@ -30,13 +30,16 @@
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('WorldTime')
_ = PluginInternationalization("WorldTime")
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
_ = lambda x:x _ = lambda x: x
def configure(advanced): def configure(advanced):
# This will be called by supybot to configure this module. advanced is # This will be called by supybot to configure this module. advanced is
@ -44,13 +47,31 @@ 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('WorldTime', True)
conf.registerPlugin("WorldTime", True)
WorldTime = conf.registerPlugin('WorldTime') WorldTime = conf.registerPlugin("WorldTime")
# This is where your configuration variables (if any) should go. For example: # This is where your configuration variables (if any) should go. For example:
conf.registerChannelValue(WorldTime, 'disableANSI', registry.Boolean(False, _("""Disable color/bolding for WorldTime output in channel."""))) conf.registerChannelValue(
conf.registerChannelValue(WorldTime, 'format', registry.String('%a, %H:%M', _("""Sets the output time format (using an strftime-formatted string)."""))) WorldTime,
conf.registerGlobalValue(WorldTime, 'mapsAPIkey', registry.String('', """Sets the Google Maps Places API key""")) "disableANSI",
registry.Boolean(
False, _("""Disable color/bolding for WorldTime output in channel.""")
),
)
conf.registerChannelValue(
WorldTime,
"format",
registry.String(
"%a, %H:%M",
_("""Sets the output time format (using an strftime-formatted string)."""),
),
)
conf.registerGlobalValue(
WorldTime,
"mapsAPIkey",
registry.String("", """Sets the Google Maps Places API key""", private=True),
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -44,23 +44,28 @@ import supybot.callbacks as callbacks
import supybot.world as world import supybot.world as world
import supybot.conf as conf import supybot.conf as conf
import supybot.log as log import supybot.log as log
try: try:
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('WorldTime')
_ = PluginInternationalization("WorldTime")
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
filename = conf.supybot.directories.data.dirize('WorldTime.db') filename = conf.supybot.directories.data.dirize("WorldTime.db")
HEADERS = { HEADERS = {
'User-agent': 'Mozilla/5.0 (compatible; Supybot/Limnoria %s; WorldTime plugin)' % conf.version "User-agent": "Mozilla/5.0 (compatible; Supybot/Limnoria %s; WorldTime plugin)"
% conf.version
} }
class WorldTime(callbacks.Plugin): class WorldTime(callbacks.Plugin):
"""Add the help for "@plugin help WorldTime" here """Add the help for "@plugin help WorldTime" here
This should describe *how* to use this plugin.""" This should describe *how* to use this plugin."""
threaded = True threaded = True
############################### ###############################
@ -78,19 +83,19 @@ class WorldTime(callbacks.Plugin):
"""Loads the (flatfile) database mapping ident@hosts to timezones.""" """Loads the (flatfile) database mapping ident@hosts to timezones."""
try: try:
with open(filename, 'rb') as f: with open(filename, "rb") as f:
self.db = pickle.load(f) self.db = pickle.load(f)
except Exception as e: except Exception as e:
self.log.debug('WorldTime: Unable to load pickled database: %s', e) self.log.debug("WorldTime: Unable to load pickled database: %s", e)
def _flushDb(self): def _flushDb(self):
"""Flushes the (flatfile) database mapping ident@hosts to timezones.""" """Flushes the (flatfile) database mapping ident@hosts to timezones."""
try: try:
with open(filename, 'wb') as f: with open(filename, "wb") as f:
pickle.dump(self.db, f, 2) pickle.dump(self.db, f, 2)
except Exception as e: except Exception as e:
self.log.warning('WorldTime: Unable to write pickled database: %s', e) self.log.warning("WorldTime: Unable to write pickled database: %s", e)
def die(self): def die(self):
self._flushDb() self._flushDb()
@ -117,9 +122,12 @@ class WorldTime(callbacks.Plugin):
############## ##############
def _getlatlng(self, location): def _getlatlng(self, location):
api_key = self.registryValue('mapsAPIkey') api_key = self.registryValue("mapsAPIkey")
location = utils.web.urlquote(location) location = utils.web.urlquote(location)
url = 'https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&key=%s' % (location, api_key) url = (
"https://maps.googleapis.com/maps/api/geocode/json?"
"address=%s&sensor=false&key=%s" % (location, api_key)
)
# try and fetch url # try and fetch url
try: try:
@ -130,21 +138,28 @@ class WorldTime(callbacks.Plugin):
# wrap in a big try/except # wrap in a big try/except
try: try:
result = json.loads(response.decode()) result = json.loads(response.decode())
if result['status'] == 'OK': if result["status"] == "OK":
lat = str(result['results'][0]['geometry']['location']['lat']) lat = str(result["results"][0]["geometry"]["location"]["lat"])
lng = str(result['results'][0]['geometry']['location']['lng']) lng = str(result["results"][0]["geometry"]["location"]["lng"])
place = (result['results'][0]['formatted_address']) place = result["results"][0]["formatted_address"]
ll = '%s,%s' % (lat, lng) # lat+long into a single string. ll = "%s,%s" % (lat, lng) # lat+long into a single string.
return {'place':place, 'll':ll} return {"place": place, "ll": ll}
else: else:
self.log.info("ERROR: _getlatlng: status result NOT ok. Result: {0}".format(result)) self.log.info(
"ERROR: _getlatlng: status result NOT ok. Result: {0}".format(
result
)
)
except Exception as e: except Exception as e:
self.log.info("ERROR: _getlatlng: {0}".format(e)) self.log.info("ERROR: _getlatlng: {0}".format(e))
def _gettime(self, latlng): def _gettime(self, latlng):
api_key = self.registryValue('mapsAPIkey') api_key = self.registryValue("mapsAPIkey")
latlng = utils.web.urlquote(latlng) latlng = utils.web.urlquote(latlng)
url = 'https://maps.googleapis.com/maps/api/timezone/json?location=%s&sensor=false&timestamp=%s&key=%s' % (latlng, time.time(), api_key) url = (
"https://maps.googleapis.com/maps/api/timezone/json?location="
"%s&sensor=false&timestamp=%s&key=%s" % (latlng, time.time(), api_key)
)
# try and fetch url # try and fetch url
try: try:
@ -154,11 +169,15 @@ class WorldTime(callbacks.Plugin):
# wrap in a big try/except # wrap in a big try/except
try: try:
result = json.loads(response.decode('utf-8')) result = json.loads(response.decode("utf-8"))
if result['status'] == 'OK': if result["status"] == "OK":
return result return result
else: else:
self.log.info("WorldTime: _gettime: status result NOT ok. Result: {0}".format(result)) self.log.info(
"WorldTime: _gettime: status result NOT ok. Result: {0}".format(
result
)
)
except Exception as e: except Exception as e:
self.log.info("WorldTime: _gettime: {0}".format(e)) self.log.info("WorldTime: _gettime: {0}".format(e))
@ -176,58 +195,80 @@ class WorldTime(callbacks.Plugin):
opts = dict(opts) opts = dict(opts)
if not location: if not location:
try: try:
if 'nick' in opts: if "nick" in opts:
host = irc.state.nickToHostmask(opts['nick']) host = irc.state.nickToHostmask(opts["nick"])
else: else:
host = msg.prefix host = msg.prefix
ih = host.split('!')[1] ih = host.split("!")[1]
location = self.db[ih] location = self.db[ih]
except KeyError: except KeyError:
irc.error("No location for %s is set. Use the 'set' command " irc.error(
"No location for %s is set. Use the 'set' command "
"to set a location for your current hostmask, or call 'worldtime' " "to set a location for your current hostmask, or call 'worldtime' "
"with <location> as an argument." % ircutils.bold('*!'+ih), Raise=True) "with <location> as an argument." % ircutils.bold("*!" + ih),
Raise=True,
)
# first, grab lat and long for user location # first, grab lat and long for user location
gc = self._getlatlng(location) gc = self._getlatlng(location)
if not gc: if not gc:
irc.error("I could not find the location for: {0}. Bad location? Spelled wrong?".format(location), Raise=True) irc.error(
"I could not find the location for: {0}. Bad location? "
"Spelled wrong?".format(location),
Raise=True,
)
# next, lets grab the localtime for that location w/lat+long. # next, lets grab the localtime for that location w/lat+long.
ll = self._gettime(gc['ll']) ll = self._gettime(gc["ll"])
if not ll: if not ll:
irc.error("I could not find the local timezone for: {0}. Bad location? Spelled wrong?".format(location), Raise=True) irc.error(
"I could not find the local timezone for: {0}. Bad location? "
"Spelled wrong?".format(location),
Raise=True,
)
# if we're here, we have localtime zone. # if we're here, we have localtime zone.
lt = self._converttz(msg, ll['timeZoneId']) lt = self._converttz(msg, ll["timeZoneId"])
if lt: # make sure we get it back. if lt: # make sure we get it back.
if sys.version_info[0] <= 2: if sys.version_info[0] <= 2:
s = "{0} :: Current local time is: {1} ({2})".format(ircutils.bold(gc['place'].encode('utf-8')), lt, ll['timeZoneName'].encode('utf-8')) s = "{0} :: Current local time is: {1} ({2})".format(
ircutils.bold(gc["place"].encode("utf-8")),
lt,
ll["timeZoneName"].encode("utf-8"),
)
else: else:
s ="{0} :: Current local time is: {1} ({2})".format(ircutils.bold(gc['place']), lt, ll['timeZoneName']) s = "{0} :: Current local time is: {1} ({2})".format(
if self.registryValue('disableANSI', msg.args[0]): ircutils.bold(gc["place"]), lt, ll["timeZoneName"]
)
if self.registryValue("disableANSI", msg.args[0]):
s = ircutils.stripFormatting(s) s = ircutils.stripFormatting(s)
irc.reply(s) irc.reply(s)
else: else:
irc.error("Something went wrong during conversion to timezone. Check the logs.", Raise=True) irc.error(
"Something went wrong during conversion to timezone. Check the logs.",
Raise=True,
)
worldtime = wrap(worldtime, [getopts({'nick': 'nick'}), additional('text')]) worldtime = wrap(worldtime, [getopts({"nick": "nick"}), additional("text")])
def set(self, irc, msg, args, timezone): def set(self, irc, msg, args, timezone):
"""<location> """<location>
Sets the location for your current ident@host to <location>.""" Sets the location for your current ident@host to <location>."""
ih = msg.prefix.split('!')[1] ih = msg.prefix.split("!")[1]
self.db[ih] = timezone self.db[ih] = timezone
irc.replySuccess() irc.replySuccess()
set = wrap(set, ['text'])
set = wrap(set, ["text"])
def unset(self, irc, msg, args): def unset(self, irc, msg, args):
"""takes no arguments. """takes no arguments.
Unsets the location for your current ident@host.""" Unsets the location for your current ident@host."""
ih = msg.prefix.split('!')[1] ih = msg.prefix.split("!")[1]
try: try:
del self.db[ih] del self.db[ih]
irc.replySuccess() irc.replySuccess()
except KeyError: except KeyError:
irc.error("No entry for %s exists." % ircutils.bold('*!'+ih), Raise=True) irc.error("No entry for %s exists." % ircutils.bold("*!" + ih), Raise=True)
Class = WorldTime Class = WorldTime