From 895b0dec47936a5ce17deb6d2de46f0fbcab250d Mon Sep 17 00:00:00 2001 From: dece Date: Tue, 9 Aug 2022 23:47:28 +0200 Subject: [PATCH] style: run Black over the whole project --- edmond/bot.py | 18 +++-- edmond/log.py | 101 +++++++++++++------------ edmond/plugin.py | 6 +- edmond/plugins/ambience.py | 10 +-- edmond/plugins/beers.py | 3 +- edmond/plugins/capture.py | 8 +- edmond/plugins/capture_give.py | 8 +- edmond/plugins/capture_list.py | 6 +- edmond/plugins/caretaker.py | 8 +- edmond/plugins/journee_mondiale.py | 5 +- edmond/plugins/meteo_france.py | 52 ++++++++----- edmond/plugins/misc_reactions.py | 37 +++++---- edmond/plugins/mood.py | 6 +- edmond/plugins/music.py | 3 +- edmond/plugins/notes.py | 12 ++- edmond/plugins/opinion.py | 6 +- edmond/plugins/sleep.py | 17 +++-- edmond/plugins/taxref.py | 33 ++++---- edmond/plugins/tests/test_sleep.py | 1 - edmond/plugins/tests/test_translate.py | 1 - edmond/plugins/translate.py | 6 +- edmond/plugins/unknown_command.py | 5 +- edmond/plugins/wikipedia.py | 6 +- edmond/plugins/youtube.py | 19 +++-- edmond/plugins/youtube_parser.py | 4 +- edmond/utils.py | 1 + 26 files changed, 224 insertions(+), 158 deletions(-) diff --git a/edmond/bot.py b/edmond/bot.py index 924f214..b8c1220 100644 --- a/edmond/bot.py +++ b/edmond/bot.py @@ -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] = {} diff --git a/edmond/log.py b/edmond/log.py index f4fcc4c..f4d9150 100644 --- a/edmond/log.py +++ b/edmond/log.py @@ -9,17 +9,17 @@ 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 - WARNING = YELLOW - INFO = GREEN - DEBUG = CYAN + ERROR = RED + WARNING = YELLOW + INFO = GREEN + DEBUG = CYAN def __init__(self, stream=None): super().__init__(stream) @@ -49,37 +49,37 @@ class _AnsiColorStreamHandler(logging.StreamHandler): # pylint: disable=W0212 class _WinColorStreamHandler(logging.StreamHandler): - STD_INPUT_HANDLE = -10 - STD_OUTPUT_HANDLE = -11 - STD_ERROR_HANDLE = -12 - - FOREGROUND_BLACK = 0x0000 - FOREGROUND_BLUE = 0x0001 - FOREGROUND_GREEN = 0x0002 - FOREGROUND_CYAN = 0x0003 - FOREGROUND_RED = 0x0004 - FOREGROUND_MAGENTA = 0x0005 - FOREGROUND_YELLOW = 0x0006 - FOREGROUND_GREY = 0x0007 + STD_INPUT_HANDLE = -10 + STD_OUTPUT_HANDLE = -11 + STD_ERROR_HANDLE = -12 + + FOREGROUND_BLACK = 0x0000 + FOREGROUND_BLUE = 0x0001 + FOREGROUND_GREEN = 0x0002 + FOREGROUND_CYAN = 0x0003 + FOREGROUND_RED = 0x0004 + FOREGROUND_MAGENTA = 0x0005 + FOREGROUND_YELLOW = 0x0006 + FOREGROUND_GREY = 0x0007 FOREGROUND_INTENSITY = 0x0008 - FOREGROUND_WHITE = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED - - BACKGROUND_BLACK = 0x0000 - BACKGROUND_BLUE = 0x0010 - BACKGROUND_GREEN = 0x0020 - BACKGROUND_CYAN = 0x0030 - BACKGROUND_RED = 0x0040 - BACKGROUND_MAGENTA = 0x0050 - BACKGROUND_YELLOW = 0x0060 - BACKGROUND_GREY = 0x0070 + FOREGROUND_WHITE = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED + + BACKGROUND_BLACK = 0x0000 + BACKGROUND_BLUE = 0x0010 + BACKGROUND_GREEN = 0x0020 + BACKGROUND_CYAN = 0x0030 + BACKGROUND_RED = 0x0040 + BACKGROUND_MAGENTA = 0x0050 + BACKGROUND_YELLOW = 0x0060 + BACKGROUND_GREY = 0x0070 BACKGROUND_INTENSITY = 0x0080 - DEFAULT = FOREGROUND_WHITE + DEFAULT = FOREGROUND_WHITE CRITICAL = FOREGROUND_RED | FOREGROUND_INTENSITY - ERROR = FOREGROUND_RED | FOREGROUND_INTENSITY - WARNING = FOREGROUND_YELLOW | FOREGROUND_INTENSITY - INFO = FOREGROUND_GREEN - DEBUG = FOREGROUND_CYAN + ERROR = FOREGROUND_RED | FOREGROUND_INTENSITY + WARNING = FOREGROUND_YELLOW | FOREGROUND_INTENSITY + INFO = FOREGROUND_GREEN + DEBUG = FOREGROUND_CYAN def __init__(self, stream=None): super().__init__(stream) @@ -116,23 +116,31 @@ 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 -_FORMAT = "%(asctime)s %(levelname)-8s %(message)s" +_LOG_LEVEL = logging.DEBUG +_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) diff --git a/edmond/plugin.py b/edmond/plugin.py index 95128bb..72fdbaa 100644 --- a/edmond/plugin.py +++ b/edmond/plugin.py @@ -179,7 +179,7 @@ class Plugin: return False # Is it a question I can answer? - question = message[len(words[0]):].strip() + question = message[len(words[0]) :].strip() for preamble in self.config.get("questions", []): aliases = self.config.get("aliases", {}).get(preamble, []) for q in (preamble, *aliases): @@ -189,7 +189,7 @@ class Plugin: return False def __save_question(self, question, matched, preamble): - content = question[len(matched):].strip() + content = question[len(matched) :].strip() content = content.rstrip("?").rstrip() question = Question(preamble, content) self.question = question @@ -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 diff --git a/edmond/plugins/ambience.py b/edmond/plugins/ambience.py index 08f0f7a..9af512f 100644 --- a/edmond/plugins/ambience.py +++ b/edmond/plugins/ambience.py @@ -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="") ) diff --git a/edmond/plugins/beers.py b/edmond/plugins/beers.py index 0b1b195..3890be7 100644 --- a/edmond/plugins/beers.py +++ b/edmond/plugins/beers.py @@ -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 diff --git a/edmond/plugins/capture.py b/edmond/plugins/capture.py index 8e50129..46c29f5 100644 --- a/edmond/plugins/capture.py +++ b/edmond/plugins/capture.py @@ -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) diff --git a/edmond/plugins/capture_give.py b/edmond/plugins/capture_give.py index 306ae29..3ffab38 100644 --- a/edmond/plugins/capture_give.py +++ b/edmond/plugins/capture_give.py @@ -29,7 +29,7 @@ class CaptureGivePlugin(Plugin): # "give" command. if self.command.ident == self.config["commands"][0]: - content = self.command.raw[len(self.command.matched):].strip() + content = self.command.raw[len(self.command.matched) :].strip() matched = self.content_re.match(content) if not matched: return False @@ -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, []) @@ -51,7 +49,7 @@ class CaptureGivePlugin(Plugin): reply = self.config["no_such_thing_reply"].format(thing=thing) self.bot.say(event.target, reply) return True - + source_collection.remove(thing) collections[source] = source_collection diff --git a/edmond/plugins/capture_list.py b/edmond/plugins/capture_list.py index 98b7776..8d1e881 100644 --- a/edmond/plugins/capture_list.py +++ b/edmond/plugins/capture_list.py @@ -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) diff --git a/edmond/plugins/caretaker.py b/edmond/plugins/caretaker.py index 70b3b40..64d95c9 100644 --- a/edmond/plugins/caretaker.py +++ b/edmond/plugins/caretaker.py @@ -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): diff --git a/edmond/plugins/journee_mondiale.py b/edmond/plugins/journee_mondiale.py index fde4c3b..3456fe8 100644 --- a/edmond/plugins/journee_mondiale.py +++ b/edmond/plugins/journee_mondiale.py @@ -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: diff --git a/edmond/plugins/meteo_france.py b/edmond/plugins/meteo_france.py index 2aa8721..6d226b6 100644 --- a/edmond/plugins/meteo_france.py +++ b/edmond/plugins/meteo_france.py @@ -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() diff --git a/edmond/plugins/misc_reactions.py b/edmond/plugins/misc_reactions.py index eacc370..060aa7a 100644 --- a/edmond/plugins/misc_reactions.py +++ b/edmond/plugins/misc_reactions.py @@ -21,16 +21,18 @@ class MiscReactionsPlugin(Plugin): REQUIRED_CONFIGS = ["reactions", "rate"] - REACTIONS = set([ - "sentence", - "stop", - "king", - "mmm", - "ooo", - "detector", - "repeat_letters", - "nudge", - ]) + REACTIONS = set( + [ + "sentence", + "stop", + "king", + "mmm", + "ooo", + "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 diff --git a/edmond/plugins/mood.py b/edmond/plugins/mood.py index 01c56bd..df4ff5a 100644 --- a/edmond/plugins/mood.py +++ b/edmond/plugins/mood.py @@ -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): diff --git a/edmond/plugins/music.py b/edmond/plugins/music.py index 18bd02e..b3993c0 100644 --- a/edmond/plugins/music.py +++ b/edmond/plugins/music.py @@ -2,6 +2,7 @@ import random try: from scaruffi.api import ScaruffiApi + DEPENDENCIES_FOUND = True except ImportError: DEPENDENCIES_FOUND = False @@ -11,7 +12,7 @@ from edmond.plugin import Plugin class MusicPlugin(Plugin): """Get some good music for your friends using the scaruffi library. - + The first command returns a random good album. The second command allows you to choose the decade: you can say 1960, 60, 60s or 60's, all of these will return an album from the sixties. diff --git a/edmond/plugins/notes.py b/edmond/plugins/notes.py index 56a98a0..517bfca 100644 --- a/edmond/plugins/notes.py +++ b/edmond/plugins/notes.py @@ -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): @@ -32,7 +36,7 @@ class NotesPlugin(Plugin): # "note down" command. if self.command.ident == self.config["commands"][0]: - content = self.command.raw[len(self.command.matched):].strip() + content = self.command.raw[len(self.command.matched) :].strip() matched = self.content_re.match(content) if not matched: return False @@ -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"]) diff --git a/edmond/plugins/opinion.py b/edmond/plugins/opinion.py index aae88b4..5f32c30 100644 --- a/edmond/plugins/opinion.py +++ b/edmond/plugins/opinion.py @@ -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): diff --git a/edmond/plugins/sleep.py b/edmond/plugins/sleep.py index 5871f6e..2fdf327 100644 --- a/edmond/plugins/sleep.py +++ b/edmond/plugins/sleep.py @@ -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 diff --git a/edmond/plugins/taxref.py b/edmond/plugins/taxref.py index a70f2ed..6a7de42 100644 --- a/edmond/plugins/taxref.py +++ b/edmond/plugins/taxref.py @@ -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( - ( - item['frenchVernacularName'] + - " → " + - TaxrefPlugin.item_to_full_name(item) + if shrlok := self.bot.get_plugin("shrlok"): + text = ( + "\n".join( + ( + item["frenchVernacularName"] + + " → " + + TaxrefPlugin.item_to_full_name(item) + ) + for item in items ) - for item in items - ) + "\n" + + "\n" + ) reply = shrlok.post_text(text) else: reply = self.get_ambiguous_reply(items) diff --git a/edmond/plugins/tests/test_sleep.py b/edmond/plugins/tests/test_sleep.py index 35dcd8f..6851ca0 100644 --- a/edmond/plugins/tests/test_sleep.py +++ b/edmond/plugins/tests/test_sleep.py @@ -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() diff --git a/edmond/plugins/tests/test_translate.py b/edmond/plugins/tests/test_translate.py index aa8ef8e..ca682eb 100644 --- a/edmond/plugins/tests/test_translate.py +++ b/edmond/plugins/tests/test_translate.py @@ -5,7 +5,6 @@ from ..translate import TranslatePlugin class TestTranslatePlugin(unittest.TestCase): - def test_parse_words(self): with get_plugin_patcher(TranslatePlugin): plugin = TranslatePlugin() diff --git a/edmond/plugins/translate.py b/edmond/plugins/translate.py index 3b0fc71..7ec012a 100644 --- a/edmond/plugins/translate.py +++ b/edmond/plugins/translate.py @@ -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): diff --git a/edmond/plugins/unknown_command.py b/edmond/plugins/unknown_command.py index 8e12ca8..808f681 100644 --- a/edmond/plugins/unknown_command.py +++ b/edmond/plugins/unknown_command.py @@ -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 diff --git a/edmond/plugins/wikipedia.py b/edmond/plugins/wikipedia.py index 1e67d66..daf4b68 100644 --- a/edmond/plugins/wikipedia.py +++ b/edmond/plugins/wikipedia.py @@ -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 diff --git a/edmond/plugins/youtube.py b/edmond/plugins/youtube.py index 4dfb09c..863fdff 100644 --- a/edmond/plugins/youtube.py +++ b/edmond/plugins/youtube.py @@ -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( - q=self.command.content, - part="id,snippet", - maxResults=1, - ).execute() + search_response = ( + self.youtube.search() + .list( + q=self.command.content, + part="id,snippet", + maxResults=1, + ) + .execute() + ) except GoogleApiError: self.signal_failure(target) return diff --git a/edmond/plugins/youtube_parser.py b/edmond/plugins/youtube_parser.py index 4f9aafe..5dd1f26 100644 --- a/edmond/plugins/youtube_parser.py +++ b/edmond/plugins/youtube_parser.py @@ -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() ) diff --git a/edmond/utils.py b/edmond/utils.py index ce8f5c6..1f41f49 100644 --- a/edmond/utils.py +++ b/edmond/utils.py @@ -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)