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:
self.log_i("Caught keyboard interrupt.")
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()
for line in traceback.format_tb(exc_traceback):
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):
return False
main_reply = self.get_registered_days()
if main_reply:
self.bot.say(event.target, main_reply)
reg_days = self.get_registered_days()
if reg_days:
self.bot.say(event.target, ", ".join(reg_days))
jmcom_reply = ""
jmcom_days = []
if self.config.get("jmcom", False) is True:
jmcom_reply = self.get_jmcom_days(event.target)
if jmcom_reply:
self.bot.say(event.target, jmcom_reply)
jmcom_days = self.get_jmcom_days(event.target)
if jmcom_days:
# 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"])
return True
def get_registered_days(self) -> str:
def get_registered_days(self) -> list[str]:
"""Get international days for the local list."""
now = datetime.datetime.now()
date_tag = f"{now.month:02}-{now.day:02}"
today_obs = map(
today_items = map(
lambda line: line.split(maxsplit=1)[1],
filter(
lambda line: line.startswith(date_tag),
self.config["dates"],
),
)
days = ", ".join(today_obs)
return days
return list(today_items)
def get_jmcom_days(self, target) -> str:
def get_jmcom_days(self, target) -> list[str]:
"""Get international days from journee-mondiale.com."""
response = http_get(JourneeMondialePlugin.JMCOM_URL)
if not response:
@ -94,5 +99,5 @@ class JourneeMondialePlugin(Plugin):
plus_plugin.add_handler(target, handler)
days = ", ".join(map(lambda i: i["title"], entries))
return days
days = map(lambda i: i["title"], entries)
return list(days)

View file

@ -100,7 +100,7 @@ class PlaylistOfTheDayPlugin(Plugin):
html_items = map(lambda item: f"<li>{item}</li>", linkified_items)
html_list = "<ol>" + "".join(html_items) + "</ol>"
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:
self.bot.log_e("Shrlok returned None.")
self.signal_failure(target)

View file

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

View file

@ -1,14 +1,20 @@
import random
from typing import Optional
from typing import Callable, Optional
import requests
def http_get(url: str) -> Optional[str]:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
def http_get(url: str, log_e: Optional[Callable] = None) -> Optional[str]:
"""Get the HTML as text from this URL.
log_e is an optional error logging function."""
try:
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: