style: run Black over the whole project

This commit is contained in:
dece 2022-08-09 23:47:28 +02:00
parent 4beead146f
commit 895b0dec47
26 changed files with 222 additions and 156 deletions

View file

@ -5,7 +5,7 @@ import time
import signal
from pathlib import Path
import irc.client
import irc.client # type: ignore
from irc.client import NickMask
from edmond.log import Logger
@ -52,8 +52,10 @@ class Bot(irc.client.SimpleIRCClient, Logger):
return storage
except (OSError, json.decoder.JSONDecodeError) as exc:
self.log_e(f"Could not load storage file: {exc}")
self.log_w("If it's not the first time Edm0nd is run, you may lose"
" data when closing the program.")
self.log_w(
"If it's not the first time Edm0nd is run, you may lose"
" data when closing the program."
)
return {}
def __save_storage(self):
@ -129,7 +131,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
plugin_files = os.listdir(Path(__file__).parent / "plugins")
plugin_names = map(
lambda f: os.path.splitext(f)[0],
filter(lambda f: f.endswith(".py"), plugin_files)
filter(lambda f: f.endswith(".py"), plugin_files),
)
for plugin_name in plugin_names:
module = importlib.import_module(f"edmond.plugins.{plugin_name}")
@ -138,10 +140,10 @@ class Bot(irc.client.SimpleIRCClient, Logger):
self.log_e(f"Dependencies not found for plugin {plugin_name}.")
continue
# Get plugin class name from its module name.
class_name = "".join(map(
lambda w: w.capitalize(),
plugin_name.split("_")
)) + "Plugin"
class_name = (
"".join(map(lambda w: w.capitalize(), plugin_name.split("_")))
+ "Plugin"
)
plugin_class = getattr(module, class_name)
self.plugins.append(plugin_class(self))
self.values[plugin_name] = {}

View file

@ -9,11 +9,11 @@ import ctypes.util
class _AnsiColorStreamHandler(logging.StreamHandler):
DEFAULT = '\x1b[0m'
RED = '\x1b[31m'
GREEN = '\x1b[32m'
YELLOW = '\x1b[33m'
CYAN = '\x1b[36m'
DEFAULT = "\x1b[0m"
RED = "\x1b[31m"
GREEN = "\x1b[32m"
YELLOW = "\x1b[33m"
CYAN = "\x1b[36m"
CRITICAL = RED
ERROR = RED
@ -116,13 +116,16 @@ class _WinColorStreamHandler(logging.StreamHandler):
return cls.DEFAULT
def _set_color_code(self, code):
ctypes.windll.kernel32.SetConsoleTextAttribute(self.output_handle, code)
ctypes.windll.kernel32.SetConsoleTextAttribute(
self.output_handle, code
)
if platform.system() == "Windows":
ColorStreamHandler = _WinColorStreamHandler
else:
ColorStreamHandler = _AnsiColorStreamHandler
ColorStreamHandler = (
_WinColorStreamHandler
if platform.system() == "Windows"
else _AnsiColorStreamHandler
)
_LOG_LEVEL = logging.DEBUG
@ -130,9 +133,14 @@ _FORMAT = "%(asctime)s %(levelname)-8s %(message)s"
_DATE_FORMAT = "%H:%M:%S"
def get_logger( name="pyshgck", level=_LOG_LEVEL
, log_format=_FORMAT, date_format=_DATE_FORMAT
, into_stderr=True, into_log_file=None ):
def get_logger(
name="pyshgck",
level=_LOG_LEVEL,
log_format=_FORMAT,
date_format=_DATE_FORMAT,
into_stderr=True,
into_log_file=None,
):
logger = logging.getLogger(name)
logger.setLevel(level)
formatter = logging.Formatter(fmt=log_format, datefmt=date_format)
@ -153,7 +161,6 @@ def get_logger( name="pyshgck", level=_LOG_LEVEL
class Logger:
def log_d(self, message):
self.logger.debug(message)

View file

@ -310,7 +310,7 @@ class Plugin:
If it causes an issue with a plugin requiring the original target even
on private message, override this method.
"""
if (on_pubmsg := getattr(self, "on_pubmsg", None)):
if on_pubmsg := getattr(self, "on_pubmsg", None):
event.target = NickMask(event.source).nick
return on_pubmsg(event)
return False

View file

@ -78,10 +78,9 @@ class AmbiencePlugin(Plugin):
return "".join(item * reps for item in random_items)
def apply_effect(self, chunk, word):
return {
1: self.insert_word,
2: self.interleave_word,
}[random.randint(1, 2)](chunk, word)
return {1: self.insert_word, 2: self.interleave_word,}[
random.randint(1, 2)
](chunk, word)
def insert_word(self, chunk, word):
index = random.randint(0, len(chunk))
@ -89,6 +88,5 @@ class AmbiencePlugin(Plugin):
def interleave_word(self, chunk, word):
return "".join(
a + b
for a, b in zip_longest(chunk, word, fillvalue='')
a + b for a, b in zip_longest(chunk, word, fillvalue="")
)

View file

@ -22,8 +22,7 @@ class BeersPlugin(Plugin):
beer = random.choice(self.config["beers"])
opening_text = self.config["opening_text"].format(
beer=beer,
target=target
beer=beer, target=target
)
self.bot.say(event.target, opening_text)
return True

View file

@ -9,7 +9,10 @@ from edmond.utils import proc
class CapturePlugin(Plugin):
REQUIRED_CONFIGS = [
"rate", "things", "capture_sentence", "captured_sentence"
"rate",
"things",
"capture_sentence",
"captured_sentence",
]
def __init__(self, bot):
@ -43,8 +46,7 @@ class CapturePlugin(Plugin):
def capture(self, winner, target):
congratz = self.config["captured_sentence"].format(
winner=winner,
thing=self.current_thing
winner=winner, thing=self.current_thing
)
self.bot.say(target, congratz)

View file

@ -41,9 +41,7 @@ class CaptureGivePlugin(Plugin):
# Check the sender has the thing they attempt to give.
collections = self.get_storage_value(
"collections",
default={},
ns="capture"
"collections", default={}, ns="capture"
)
source = event.source.nick
source_collection = collections.get(source, [])

View file

@ -19,16 +19,14 @@ class CaptureListPlugin(Plugin):
collec_target = self.command.content or event.source.nick
collections = self.get_storage_value(
"collections",
default={},
ns="capture"
"collections", default={}, ns="capture"
)
collection = collections.get(collec_target, [])
if collection:
reply = self.config["reply"].format(
target=collec_target,
num=len(collection),
things="".join(collection)
things="".join(collection),
)
else:
reply = self.config["empty_reply"].format(target=collec_target)

View file

@ -9,8 +9,12 @@ class CaretakerPlugin(Plugin):
"""Say hello and farewall on people joining/parting."""
REQUIRED_CONFIGS = [
"warm_welcome", "cold_welcome", "nice_farewell", "bad_farewell",
"welcome_rate", "farewell_rate"
"warm_welcome",
"cold_welcome",
"nice_farewell",
"bad_farewell",
"welcome_rate",
"farewell_rate",
]
def __init__(self, bot):

View file

@ -34,9 +34,8 @@ class JourneeMondialePlugin(Plugin):
today_obs = map(
lambda line: line.split(maxsplit=1)[1],
filter(
lambda line: line.startswith(date_tag),
self.config["dates"]
)
lambda line: line.startswith(date_tag), self.config["dates"]
),
)
reply = ", ".join(today_obs)
if not reply:

View file

@ -2,6 +2,7 @@ import time
try:
import meteofrance_api as mf
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
@ -12,9 +13,14 @@ from edmond.plugin import Plugin
class MeteoFrancePlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "result_message", "nearest_message", "temp_format",
"rain_chance_format", "all_rain_format", "today_message",
"minmax_temp_format"
"commands",
"result_message",
"nearest_message",
"temp_format",
"rain_chance_format",
"all_rain_format",
"today_message",
"minmax_temp_format",
]
def __init__(self, bot):
@ -54,7 +60,8 @@ class MeteoFrancePlugin(Plugin):
return
result = self.config["result_message"].format(
nearest_s=nearest_s, today_s=today_s)
nearest_s=nearest_s, today_s=today_s
)
self.bot.say(event.target, result)
def format_nearest_forecast(self, nearest, place):
@ -65,43 +72,52 @@ class MeteoFrancePlugin(Plugin):
wind = self.format_wind(nearest["wind"])
rain = self.format_rain_perc(nearest["rain"])
return self.config["nearest_message"].format(
city=city, hour=hour, weather=weather, temp=temp, wind=wind,
rain=rain
city=city,
hour=hour,
weather=weather,
temp=temp,
wind=wind,
rain=rain,
)
def format_temperature(self, temperature):
temp_c = temperature.get("value", "?")
temp_wc = temperature.get("windchill", "?")
return self.config["temp_format"].format(
temp_c=temp_c, temp_wc=temp_wc)
temp_c=temp_c, temp_wc=temp_wc
)
def format_rain_perc(self, rain_percs):
perc_fmt = self.config["rain_chance_format"]
all_percs = ', '.join(
perc_fmt.format(p=p, h=h)
for h, p in rain_percs.items()
all_percs = ", ".join(
perc_fmt.format(p=p, h=h) for h, p in rain_percs.items()
)
return self.config["all_rain_format"].format(all_percs=all_percs)
def format_wind(self, wind):
speed = wind.get('speed')
direction = wind.get('icon')
speed = wind.get("speed")
direction = wind.get("icon")
if direction == "Variable":
direction = self.config["unknown_direction"]
return self.config["wind_format"].format(
speed=speed, direction=direction)
speed=speed, direction=direction
)
def format_today_forecast(self, today_f):
temp = today_f['T']
temp = today_f["T"]
temp_minmax = self.config["minmax_temp_format"].format(
t_max=temp["max"], t_min=temp["min"])
rain = self.format_rain_perc(today_f['precipitation'])
sunset = format_ts_hour(today_f['sun']['set'])
t_max=temp["max"], t_min=temp["min"]
)
rain = self.format_rain_perc(today_f["precipitation"])
sunset = format_ts_hour(today_f["sun"]["set"])
return self.config["today_message"].format(
temp_minmax=temp_minmax, rain=rain, sunset=sunset)
temp_minmax=temp_minmax, rain=rain, sunset=sunset
)
def format_ts_hour(timestamp):
return time.strftime("%H:%M", time.localtime(timestamp))
def format_weather(weather):
return weather.get("desc", "?").lower()

View file

@ -21,7 +21,8 @@ class MiscReactionsPlugin(Plugin):
REQUIRED_CONFIGS = ["reactions", "rate"]
REACTIONS = set([
REACTIONS = set(
[
"sentence",
"stop",
"king",
@ -30,7 +31,8 @@ class MiscReactionsPlugin(Plugin):
"detector",
"repeat_letters",
"nudge",
])
]
)
def __init__(self, bot):
super().__init__(bot)
@ -136,8 +138,12 @@ class MiscReactionsPlugin(Plugin):
detector_neg = self.config.get("detector_neg")
if any(
s is None
for s in (detector_message, detector_process, detector_pos,
detector_neg)
for s in (
detector_message,
detector_process,
detector_pos,
detector_neg,
)
):
return
self.bot.say(event.target, detector_message.format(subject=words[-1]))
@ -155,10 +161,9 @@ class MiscReactionsPlugin(Plugin):
biggest_word = sorted(words, key=lambda w: len(w))[-1]
num_repeats = 2
repeated = biggest_word[:num_repeats]
while (
(not any(letter in repeated for letter in "aeiouy"))
and len(repeated) < len(biggest_word)
):
while (not any(letter in repeated for letter in "aeiouy")) and len(
repeated
) < len(biggest_word):
num_repeats += 1
repeated = biggest_word[:num_repeats]
word = biggest_word[:2] + biggest_word

View file

@ -21,7 +21,11 @@ class MoodPlugin(Plugin):
"""
REQUIRED_CONFIGS = [
"commands", "questions", "greetings", "answer", "calmed_message",
"commands",
"questions",
"greetings",
"answer",
"calmed_message",
]
def __init__(self, bot):

View file

@ -2,6 +2,7 @@ import random
try:
from scaruffi.api import ScaruffiApi
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False

View file

@ -6,8 +6,12 @@ from edmond.plugin import Plugin
class NotesPlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "content_regex", "confirmation", "deliver_format", "limit",
"too_many_notes"
"commands",
"content_regex",
"confirmation",
"deliver_format",
"limit",
"too_many_notes",
]
def __init__(self, bot):
@ -51,7 +55,7 @@ class NotesPlugin(Plugin):
note = {
"sender": event.source.nick,
"dest": target,
"message": message
"message": message,
}
self.append_storage_list_value("notes", note)
self.bot.say(event.target, self.config["confirmation"])

View file

@ -8,7 +8,11 @@ from edmond.plugin import Plugin
class OpinionPlugin(Plugin):
REQUIRED_CONFIGS = [
"questions", "thinking", "thinking_time", "positive", "negative"
"questions",
"thinking",
"thinking_time",
"positive",
"negative",
]
def __init__(self, bot):

View file

@ -9,8 +9,13 @@ class SleepPlugin(Plugin):
"""Handle sleep state of the bot, snore a little bit."""
REQUIRED_CONFIGS = [
"commands", "sleep_time", "wakeup_time", "snore", "sleep_messages",
"wakeup_messages", "snore_rate"
"commands",
"sleep_time",
"wakeup_time",
"snore",
"sleep_messages",
"wakeup_messages",
"snore_rate",
]
def __init__(self, bot):
@ -65,7 +70,9 @@ class SleepPlugin(Plugin):
return
self.set_runtime_value("awake", True)
for channel in self.bot.channels:
self.bot.say(channel, random.choice(self.config["wakeup_messages"]))
self.bot.say(
channel, random.choice(self.config["wakeup_messages"])
)
def is_sleep_time(self, now):
"""Return True if the bot should be sleeping by now.
@ -83,9 +90,7 @@ class SleepPlugin(Plugin):
else:
ref_dt = now
sleep_dt, wakeup_dt = self._get_sleep_range(
ref_dt,
sleep_time,
wakeup_time
ref_dt, sleep_time, wakeup_time
)
return sleep_dt <= now < wakeup_dt

View file

@ -30,8 +30,11 @@ IMG_FETCH_HTML = """\
class TaxrefPlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "not_found_reply", "reply", "ambiguous_reply",
"unnamed_species"
"commands",
"not_found_reply",
"reply",
"ambiguous_reply",
"unnamed_species",
]
def __init__(self, bot):
@ -90,7 +93,8 @@ class TaxrefPlugin(Plugin):
# If there are several species, check if one of them has the
# exact same name; else show an ambiguous reply.
species_with_same_name = [
item for item in species_items
item
for item in species_items
if item["scientificName"].lower() == name
]
if len(species_with_same_name) != 1:
@ -109,7 +113,7 @@ class TaxrefPlugin(Plugin):
)
self.bot.say(target, reply)
if (images_reply := self.get_images_reply(item_to_use)):
if images_reply := self.get_images_reply(item_to_use):
self.bot.say(target, images_reply)
def get_ambiguous_reply(self, items):
@ -153,7 +157,7 @@ class TaxrefPlugin(Plugin):
def get_img_url(item):
return item.get("_links", {}).get("file", {}).get("href")
if (shrlok := self.bot.get_plugin("shrlok")):
if shrlok := self.bot.get_plugin("shrlok"):
if len(items) > 10:
items = random.sample(items, 10)
urls = map(get_img_url, items)
@ -191,15 +195,18 @@ class TaxrefPlugin(Plugin):
else:
# More than one result? For simplicity sake, use the shrlok plugin
# if available or just show an ambiguous response.
if (shrlok := self.bot.get_plugin("shrlok")):
text = "\n".join(
if shrlok := self.bot.get_plugin("shrlok"):
text = (
"\n".join(
(
item['frenchVernacularName'] +
"" +
TaxrefPlugin.item_to_full_name(item)
item["frenchVernacularName"]
+ ""
+ TaxrefPlugin.item_to_full_name(item)
)
for item in items
) + "\n"
)
+ "\n"
)
reply = shrlok.post_text(text)
else:
reply = self.get_ambiguous_reply(items)

View file

@ -7,7 +7,6 @@ from ..sleep import SleepPlugin
class TestSleepPlugin(unittest.TestCase):
def test_is_sleep_time(self):
with get_plugin_patcher(SleepPlugin):
plugin = SleepPlugin()

View file

@ -5,7 +5,6 @@ from ..translate import TranslatePlugin
class TestTranslatePlugin(unittest.TestCase):
def test_parse_words(self):
with get_plugin_patcher(TranslatePlugin):
plugin = TranslatePlugin()

View file

@ -1,5 +1,6 @@
try:
from translate import Translator
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
@ -10,7 +11,10 @@ from edmond.plugin import Plugin
class TranslatePlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "default_dest", "param_source", "param_dest",
"commands",
"default_dest",
"param_source",
"param_dest",
]
def __init__(self, bot):

View file

@ -1,5 +1,6 @@
try:
import wolframalpha
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
@ -79,7 +80,9 @@ class UnknownCommandPlugin(Plugin):
else:
reply = answer_text
if len(reply) > self.MAX_LENGTH - len(self.CUT_MARK):
reply = reply[:self.MAX_LENGTH - len(self.CUT_MARK)] + self.CUT_MARK
reply = (
reply[: self.MAX_LENGTH - len(self.CUT_MARK)] + self.CUT_MARK
)
self.bot.say(target, reply)
@staticmethod

View file

@ -2,6 +2,7 @@ import time
try:
import wikipedia
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
@ -12,7 +13,10 @@ from edmond.plugin import Plugin
class WikipediaPlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "ambiguous_response", "empty_response", "lang",
"commands",
"ambiguous_response",
"empty_response",
"lang",
]
NUM_RETRIES = 3

View file

@ -1,6 +1,7 @@
try:
from googleapiclient.discovery import build as gapi_discovery_build
from googleapiclient.errors import Error as GoogleApiError
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
@ -23,9 +24,7 @@ class YoutubePlugin(Plugin):
def youtube(self):
if self._youtube is None:
self._youtube = gapi_discovery_build(
"youtube",
"v3",
developerKey=self.config["api_key"]
"youtube", "v3", developerKey=self.config["api_key"]
)
return self._youtube
@ -43,11 +42,15 @@ class YoutubePlugin(Plugin):
def handle_commands(self, target):
if self.command.ident == self.config["commands"][0]:
try:
search_response = self.youtube.search().list(
search_response = (
self.youtube.search()
.list(
q=self.command.content,
part="id,snippet",
maxResults=1,
).execute()
)
.execute()
)
except GoogleApiError:
self.signal_failure(target)
return

View file

@ -2,6 +2,7 @@ import re
try:
from googleapiclient.errors import Error as GoogleApiError
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
@ -49,8 +50,7 @@ class YoutubeParserPlugin(Plugin):
return False
try:
search_response = (
self.youtube_plugin.youtube
.videos()
self.youtube_plugin.youtube.videos()
.list(id=code, part="snippet")
.execute()
)

View file

@ -8,5 +8,6 @@ def http_get(url):
if response.status_code == 200:
return response.text
def proc(proba_percentage):
return random.random() < (proba_percentage / 100.0)