Compare commits

..

3 commits

Author SHA1 Message Date
dece 97c930ff09 taxref: fix shrlok issue 2022-11-29 13:00:21 +01:00
dece ea5acc28e8 journee_mondiale: various improvements, again… 2022-11-29 13:00:21 +01:00
dece 086ec48823 utils: improve logging 2022-11-29 13:00:21 +01:00
5 changed files with 38 additions and 24 deletions

View file

@ -126,7 +126,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
except KeyboardInterrupt: except KeyboardInterrupt:
self.log_i("Caught keyboard interrupt.") self.log_i("Caught keyboard interrupt.")
except Exception as exc: except Exception as exc:
self.log_c(f"Caught unhandled {type(exc)}: {exc}") self.log_c(f"Caught unhandled {type(exc).__name__}: {exc}")
_, _, exc_traceback = sys.exc_info() _, _, exc_traceback = sys.exc_info()
for line in traceback.format_tb(exc_traceback): for line in traceback.format_tb(exc_traceback):
self.log_d(line.rstrip()) self.log_d(line.rstrip())

View file

@ -37,35 +37,40 @@ class JourneeMondialePlugin(Plugin):
if not self.should_handle_command(event.arguments[0], no_content=True): if not self.should_handle_command(event.arguments[0], no_content=True):
return False return False
main_reply = self.get_registered_days() reg_days = self.get_registered_days()
if main_reply: if reg_days:
self.bot.say(event.target, main_reply) self.bot.say(event.target, ", ".join(reg_days))
jmcom_reply = "" jmcom_days = []
if self.config.get("jmcom", False) is True: if self.config.get("jmcom", False) is True:
jmcom_reply = self.get_jmcom_days(event.target) jmcom_days = self.get_jmcom_days(event.target)
if jmcom_reply: if jmcom_days:
self.bot.say(event.target, jmcom_reply) # Remove days already in reg_days.
lower_reg_days = [day.lower() for day in reg_days]
jmcom_days_filtered = [
day for day in jmcom_days
if day.lower() not in lower_reg_days
]
self.bot.say(event.target, ", ".join(jmcom_days_filtered))
if not (main_reply or jmcom_reply): if not (reg_days or jmcom_days):
self.bot.say(event.target, self.config["no_entry_reply"]) self.bot.say(event.target, self.config["no_entry_reply"])
return True return True
def get_registered_days(self) -> str: def get_registered_days(self) -> list[str]:
"""Get international days for the local list.""" """Get international days for the local list."""
now = datetime.datetime.now() now = datetime.datetime.now()
date_tag = f"{now.month:02}-{now.day:02}" date_tag = f"{now.month:02}-{now.day:02}"
today_obs = map( today_items = map(
lambda line: line.split(maxsplit=1)[1], lambda line: line.split(maxsplit=1)[1],
filter( filter(
lambda line: line.startswith(date_tag), lambda line: line.startswith(date_tag),
self.config["dates"], self.config["dates"],
), ),
) )
days = ", ".join(today_obs) return list(today_items)
return days
def get_jmcom_days(self, target) -> str: def get_jmcom_days(self, target) -> list[str]:
"""Get international days from journee-mondiale.com.""" """Get international days from journee-mondiale.com."""
response = http_get(JourneeMondialePlugin.JMCOM_URL) response = http_get(JourneeMondialePlugin.JMCOM_URL)
if not response: if not response:
@ -94,5 +99,5 @@ class JourneeMondialePlugin(Plugin):
plus_plugin.add_handler(target, handler) plus_plugin.add_handler(target, handler)
days = ", ".join(map(lambda i: i["title"], entries)) days = map(lambda i: i["title"], entries)
return days return list(days)

View file

@ -100,7 +100,7 @@ class PlaylistOfTheDayPlugin(Plugin):
html_items = map(lambda item: f"<li>{item}</li>", linkified_items) html_items = map(lambda item: f"<li>{item}</li>", linkified_items)
html_list = "<ol>" + "".join(html_items) + "</ol>" html_list = "<ol>" + "".join(html_items) + "</ol>"
data = HTML_TEMPLATE.format(html_list).encode() data = HTML_TEMPLATE.format(html_list).encode()
url = self.shrlok_plugin.post({"type": "raw"}, data) url = self.shrlok_plugin.post({"type": "raw", "ext": "html"}, data)
if not url: if not url:
self.bot.log_e("Shrlok returned None.") self.bot.log_e("Shrlok returned None.")
self.signal_failure(target) self.signal_failure(target)

View file

@ -230,13 +230,16 @@ class TaxrefPlugin(Plugin):
+ "\n" + "\n"
) )
reply = shrlok.post({"type": "txt"}, text.encode()) reply = shrlok.post({"type": "txt"}, text.encode())
if not reply:
self.bot.log_d("shrlok plugin returned an empty string.")
return
else: else:
reply = self.get_ambiguous_reply(items) reply = self.get_ambiguous_reply(items)
self.bot.say(target, reply) self.bot.say(target, reply)
@staticmethod @staticmethod
def item_to_full_name(item): def item_to_full_name(item: dict) -> str:
family_name = item.get("familyName") family_name = item.get("familyName")
sci_name = item.get("scientificName") sci_name = item.get("scientificName")
return f"{family_name} {sci_name}" return f"{family_name} {sci_name}"

View file

@ -1,14 +1,20 @@
import random import random
from typing import Optional from typing import Callable, Optional
import requests import requests
def http_get(url: str) -> Optional[str]: def http_get(url: str, log_e: Optional[Callable] = None) -> Optional[str]:
response = requests.get(url) """Get the HTML as text from this URL.
if response.status_code == 200: log_e is an optional error logging function."""
return response.text try:
return None response = requests.get(url)
response.raise_for_status()
except OSError as exc:
if log_e:
log_e(f"http_get error: {exc}")
return None
return response.text
def proc(proba_percentage: int) -> bool: def proc(proba_percentage: int) -> bool: