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."""))
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:

View File

@ -40,21 +40,24 @@ import supybot.world as world
__version__ = "2020.02.24+git"
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.Author('butterscotchstallion', 'butterscotchstallion',
'')
__maintainer__ = getattr(supybot.authors, 'oddluck',
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net'))
__author__ = supybot.Author("butterscotchstallion", "butterscotchstallion", "")
__maintainer__ = getattr(
supybot.authors,
"oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# 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 plugin
from imp import reload
# In case we're being reloaded.
reload(config)
reload(plugin)

View File

@ -30,9 +30,11 @@
import supybot.conf as conf
import supybot.registry as registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('IMDb')
_ = PluginInternationalization("IMDb")
except:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
@ -45,24 +47,55 @@ def configure(advanced):
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
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',
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,
"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',
registry.String("No results for that query.", _("""This message is sent when there are no results""")))
conf.registerChannelValue(
IMDb,
"noResultsMessage",
registry.String(
"No results for that query.",
_("""This message is sent when there are no results"""),
),
)
conf.registerGlobalValue(IMDb, 'omdbAPI',
registry.String('', _("""OMDB API Key""")))
conf.registerGlobalValue(
IMDb, "omdbAPI", registry.String("", _("""OMDB API Key"""), private=True)
)
conf.registerChannelValue(IMDb, 'googleSearch',
registry.Boolean(True, _("""Use google to perform searches for better results.""")))
conf.registerChannelValue(
IMDb,
"googleSearch",
registry.Boolean(True, _("""Use google to perform searches for better results.""")),
)
conf.registerGlobalValue(IMDb, 'userAgents',
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.registerGlobalValue(
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:

View File

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

View File

@ -39,19 +39,19 @@ import supybot.world as world
__version__ = "2020.02.24+git"
# 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")
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# 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 plugin
from imp import reload
# In case we're being reloaded.
reload(config)
reload(plugin)

View File

@ -29,9 +29,11 @@
import supybot.conf as conf
import supybot.registry as registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Lyrics')
_ = PluginInternationalization("Lyrics")
except:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
@ -44,12 +46,28 @@ def configure(advanced):
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
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',
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""")))
Lyrics = conf.registerPlugin("Lyrics")
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:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Weed')
_ = PluginInternationalization("Weed")
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x: x
class Lyrics(callbacks.Plugin):
"""Retrieves song lyrics"""
threaded = True
def dosearch(self, lyric):
@ -60,33 +63,33 @@ class Lyrics(callbacks.Plugin):
searchurl += "{0} site:lyrics.fandom.com/wiki/".format(lyric)
agents = self.registryValue("userAgents")
ua = random.choice(agents)
header = {'User-Agent': ua}
header = {"User-Agent": ua}
data = requests.get(searchurl, headers=header, timeout=10)
data.raise_for_status()
log.debug(data.content.decode())
soup = BeautifulSoup(data.content)
elements = soup.select('.r a')
title = soup.find("h3").getText().replace(":", " - ").split('|')[0]
url = elements[0]['href']
elements = soup.select(".r a")
title = soup.find("h3").getText().replace(":", " - ").split("|")[0]
url = elements[0]["href"]
except Exception:
pass
return title, url
def getlyrics(self, query):
lyrics = None
if 'lyrics.fandom.com/wiki/' in query:
if "lyrics.fandom.com/wiki/" in query:
try:
log.debug("Lyrics: requesting {0}".format(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:
pass
else:
try:
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 = re.sub('(?<!\.|\!|\?)\s\\n', '.', lyrics).replace(" \n", "")
lyrics = re.sub(r"(?<!\.|\!|\?)\s\\n", ".", lyrics).replace(" \n", "")
except Exception:
pass
return lyrics
@ -100,7 +103,7 @@ class Lyrics(callbacks.Plugin):
url = None
if self.registryValue("googleSearch", channel):
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:
lyrics = self.getlyrics(url)
if lyrics:
@ -113,7 +116,7 @@ class Lyrics(callbacks.Plugin):
irc.reply("Unable to retrieve lyrics from {0}".format(url))
return
else:
if ',' in lyric:
if "," in lyric:
try:
lyrics = self.getlyrics(lyric)
if lyrics:
@ -127,6 +130,8 @@ class Lyrics(callbacks.Plugin):
else:
irc.reply("Searches must be formatted as <artist>, <song title>")
return
lyric = wrap(lyric, ['text'])
lyric = wrap(lyric, ["text"])
Class = Lyrics

View File

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

View File

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

View File

@ -40,21 +40,25 @@ import supybot.world as world
__version__ = "2020.02.24+git"
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.Author('reticulatingspline', 'spline', 'spline')
__maintainer__ = getattr(supybot.authors, 'oddluck',
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net'))
__author__ = supybot.Author("reticulatingspline", "spline", "spline")
__maintainer__ = getattr(
supybot.authors,
"oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# 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 plugin
from imp import reload
reload(plugin) # In case we're being reloaded.
reload(plugin) # In case we're being reloaded.
reload(config)
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!

View File

@ -31,30 +31,103 @@
import supybot.conf as conf
import supybot.registry as registry
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Tweety', True)
conf.registerPlugin("Tweety", True)
Tweety = conf.registerPlugin('Tweety')
conf.registerGlobalValue(Tweety,'consumerKey',registry.String('', """The consumer key of the application."""))
conf.registerGlobalValue(Tweety,'consumerSecret',registry.String('', """The consumer secret of the application.""", private=True))
conf.registerGlobalValue(Tweety,'accessKey',registry.String('', """The Twitter Access Token key for the bot's account"""))
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?"""))
Tweety = conf.registerPlugin("Tweety")
conf.registerGlobalValue(
Tweety,
"consumerKey",
registry.String("", """The consumer key of the application.""", private=True),
)
conf.registerGlobalValue(
Tweety,
"consumerSecret",
registry.String("", """The consumer secret of the application.""", private=True),
)
conf.registerGlobalValue(
Tweety,
"accessKey",
registry.String(
"", """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:

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"
# 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")
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# 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 plugin
from imp import reload
# In case we're being reloaded.
reload(config)
reload(plugin)

View File

@ -30,9 +30,11 @@
import supybot.conf as conf
import supybot.registry as registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Weed')
_ = PluginInternationalization("Weed")
except:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
@ -45,14 +47,15 @@ def configure(advanced):
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
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',
registry.String('', _("""Strain API Key""")))
conf.registerGlobalValue(
Weed, "strain_api", registry.String("", _("""Strain API Key"""), private=True)
)
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:

View File

@ -39,14 +39,17 @@ import re
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('Weed')
_ = PluginInternationalization("Weed")
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x: x
class Weed(callbacks.Plugin):
"""Uses API to retrieve information"""
threaded = True
def strain(self, irc, msg, args, strain):
@ -56,53 +59,68 @@ class Weed(callbacks.Plugin):
response1 = None
response2 = None
channel = msg.args[0]
strain = re.sub('[^\w\:\"\#\-\.\' ]', '', strain).casefold()
strain_api = self.registryValue('strain_api')
strain = re.sub("[^\w\:\"\#\-\.' ]", "", strain).casefold()
strain_api = self.registryValue("strain_api")
if not strain_api:
irc.reply("Error: You must set an API key to use this plugin.")
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)
ok = request.status_code == requests.codes.ok
if not ok:
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
data = json.loads(request.content)
for item in data:
if item['desc'] is not None and item['name'].casefold() == strain:
id = item['id']
name = ircutils.bold(item['name'])
type = ircutils.bold(item['race'])
desc = item['desc']
url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(strain_api, id)
if item["desc"] is not None and item["name"].casefold() == strain:
id = item["id"]
name = ircutils.bold(item["name"])
type = ircutils.bold(item["race"])
desc = item["desc"]
url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(
strain_api, id
)
data2 = requests.get(url2)
data2 = json.loads(data2.content)
flavor1 = data2[0]
flavor2 = data2[1]
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
for item in data:
if item['desc'] is not None and item['name'].casefold() != strain:
id = item['id']
name = ircutils.bold(item['name'])
type = ircutils.bold(item['race'])
desc = item['desc']
url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(strain_api, id)
if item["desc"] is not None and item["name"].casefold() != strain:
id = item["id"]
name = ircutils.bold(item["name"])
type = ircutils.bold(item["race"])
desc = item["desc"]
url2 = "http://strainapi.evanbusse.com/{0}/strains/data/flavors/{1}".format(
strain_api, id
)
data2 = requests.get(url2)
data2 = json.loads(data2.content)
flavor1 = data2[0]
flavor2 = data2[1]
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
if response1 != None:
irc.reply(response1)
elif response1 == None and response2 != None:
irc.reply(response2)
else:
irc.reply('No results found, what have you been smoking?')
strain = wrap(strain, ['text'])
irc.reply("No results found, what have you been smoking?")
strain = wrap(strain, ["text"])
Class = Weed

View File

@ -41,20 +41,24 @@ import importlib
__version__ = "2020.02.24+git"
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.Author('reticulatingspline', 'spline', '')
__maintainer__ = getattr(supybot.authors, 'oddluck',
supybot.Author('oddluck', 'oddluck', 'oddluck@riseup.net'))
__author__ = supybot.Author("reticulatingspline", "spline", "")
__maintainer__ = getattr(
supybot.authors,
"oddluck",
supybot.Author("oddluck", "oddluck", "oddluck@riseup.net"),
)
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# 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 plugin
from imp import reload
# In case we're being reloaded.
importlib.reload(config)
importlib.reload(plugin)

View File

@ -30,13 +30,16 @@
import supybot.conf as conf
import supybot.registry as registry
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('WorldTime')
_ = PluginInternationalization("WorldTime")
except:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x:x
_ = lambda x: x
def configure(advanced):
# 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
# registry as appropriate.
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:
conf.registerChannelValue(WorldTime, '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"""))
conf.registerChannelValue(
WorldTime,
"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:

View File

@ -44,23 +44,28 @@ import supybot.callbacks as callbacks
import supybot.world as world
import supybot.conf as conf
import supybot.log as log
try:
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization('WorldTime')
_ = PluginInternationalization("WorldTime")
except ImportError:
# Placeholder that allows to run the plugin on a bot
# 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 = {
'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):
"""Add the help for "@plugin help WorldTime" here
This should describe *how* to use this plugin."""
threaded = True
###############################
@ -75,27 +80,27 @@ class WorldTime(callbacks.Plugin):
world.flushers.append(self._flushDb)
def _loadDb(self):
"""Loads the (flatfile) database mapping ident@hosts to timezones."""
"""Loads the (flatfile) database mapping ident@hosts to timezones."""
try:
with open(filename, 'rb') as f:
self.db = pickle.load(f)
except Exception as e:
self.log.debug('WorldTime: Unable to load pickled database: %s', e)
try:
with open(filename, "rb") as f:
self.db = pickle.load(f)
except Exception as e:
self.log.debug("WorldTime: Unable to load pickled database: %s", e)
def _flushDb(self):
"""Flushes the (flatfile) database mapping ident@hosts to timezones."""
"""Flushes the (flatfile) database mapping ident@hosts to timezones."""
try:
with open(filename, 'wb') as f:
pickle.dump(self.db, f, 2)
except Exception as e:
self.log.warning('WorldTime: Unable to write pickled database: %s', e)
try:
with open(filename, "wb") as f:
pickle.dump(self.db, f, 2)
except Exception as e:
self.log.warning("WorldTime: Unable to write pickled database: %s", e)
def die(self):
self._flushDb()
world.flushers.remove(self._flushDb)
self.__parent.die()
self._flushDb()
world.flushers.remove(self._flushDb)
self.__parent.die()
##################
# TIME FUNCTIONS #
@ -117,9 +122,12 @@ class WorldTime(callbacks.Plugin):
##############
def _getlatlng(self, location):
api_key = self.registryValue('mapsAPIkey')
api_key = self.registryValue("mapsAPIkey")
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:
@ -130,21 +138,28 @@ class WorldTime(callbacks.Plugin):
# wrap in a big try/except
try:
result = json.loads(response.decode())
if result['status'] == 'OK':
lat = str(result['results'][0]['geometry']['location']['lat'])
lng = str(result['results'][0]['geometry']['location']['lng'])
place = (result['results'][0]['formatted_address'])
ll = '%s,%s' % (lat, lng) # lat+long into a single string.
return {'place':place, 'll':ll}
if result["status"] == "OK":
lat = str(result["results"][0]["geometry"]["location"]["lat"])
lng = str(result["results"][0]["geometry"]["location"]["lng"])
place = result["results"][0]["formatted_address"]
ll = "%s,%s" % (lat, lng) # lat+long into a single string.
return {"place": place, "ll": ll}
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:
self.log.info("ERROR: _getlatlng: {0}".format(e))
def _gettime(self, latlng):
api_key = self.registryValue('mapsAPIkey')
api_key = self.registryValue("mapsAPIkey")
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:
@ -154,11 +169,15 @@ class WorldTime(callbacks.Plugin):
# wrap in a big try/except
try:
result = json.loads(response.decode('utf-8'))
if result['status'] == 'OK':
result = json.loads(response.decode("utf-8"))
if result["status"] == "OK":
return result
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:
self.log.info("WorldTime: _gettime: {0}".format(e))
@ -176,58 +195,80 @@ class WorldTime(callbacks.Plugin):
opts = dict(opts)
if not location:
try:
if 'nick' in opts:
host = irc.state.nickToHostmask(opts['nick'])
if "nick" in opts:
host = irc.state.nickToHostmask(opts["nick"])
else:
host = msg.prefix
ih = host.split('!')[1]
ih = host.split("!")[1]
location = self.db[ih]
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' "
"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
gc = self._getlatlng(location)
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.
ll = self._gettime(gc['ll'])
ll = self._gettime(gc["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.
lt = self._converttz(msg, ll['timeZoneId'])
lt = self._converttz(msg, ll["timeZoneId"])
if lt: # make sure we get it back.
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:
s ="{0} :: Current local time is: {1} ({2})".format(ircutils.bold(gc['place']), lt, ll['timeZoneName'])
if self.registryValue('disableANSI', msg.args[0]):
s = "{0} :: Current local time is: {1} ({2})".format(
ircutils.bold(gc["place"]), lt, ll["timeZoneName"]
)
if self.registryValue("disableANSI", msg.args[0]):
s = ircutils.stripFormatting(s)
irc.reply(s)
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):
"""<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
irc.replySuccess()
set = wrap(set, ['text'])
set = wrap(set, ["text"])
def unset(self, irc, msg, args):
"""takes no arguments.
Unsets the location for your current ident@host."""
ih = msg.prefix.split('!')[1]
ih = msg.prefix.split("!")[1]
try:
del self.db[ih]
irc.replySuccess()
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