taxref: complete showing image gallery if possible

This commit is contained in:
Adrien Abraham 2022-09-02 18:36:41 +02:00
parent e05d367f12
commit 872416343c
2 changed files with 23 additions and 11 deletions

View file

@ -44,7 +44,7 @@ class ShrlokPlugin(Plugin):
return url return url
def post_text(self, text): def post_text(self, text):
self.post("txt", text.encode()) return self.post("txt", text.encode())
def post_html(self, html): def post_html(self, html):
self.post("html", html.encode()) return self.post("html", html.encode())

View file

@ -1,5 +1,6 @@
import random import random
import urllib.parse import urllib.parse
from typing import Optional
import requests import requests
@ -9,7 +10,10 @@ BASE_URL = "https://taxref.mnhn.fr/api"
IMG_FETCH_HTML = """\ IMG_FETCH_HTML = """\
<!doctype html> <!doctype html>
<html> <html>
<head><meta charset="UTF-8"/></head> <head>
<meta charset="UTF-8"/>
<style>img {{ display: block; max-width: 95%; }}</style>
</head>
<body></body> <body></body>
<script> <script>
const urls = [{}]; const urls = [{}];
@ -52,7 +56,7 @@ class TaxrefPlugin(Plugin):
self.find_scientific_name(self.command.content, event.target) self.find_scientific_name(self.command.content, event.target)
return True return True
def search_by_name(self, name, target): def search_by_name(self, name: str, target: str) -> None:
"""Get species data from a scientific name. """Get species data from a scientific name.
Try to disambiguate the results by focusing on species only and their Try to disambiguate the results by focusing on species only and their
@ -116,7 +120,7 @@ class TaxrefPlugin(Plugin):
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) self.bot.say(target, images_reply)
def get_ambiguous_reply(self, items): def get_ambiguous_reply(self, items) -> str:
"""Show a reply with potential species.""" """Show a reply with potential species."""
reply = self.config["ambiguous_reply"] reply = self.config["ambiguous_reply"]
append = "" append = ""
@ -128,7 +132,7 @@ class TaxrefPlugin(Plugin):
reply += append reply += append
return reply return reply
def get_images_reply(self, item): def get_images_reply(self, item) -> Optional[str]:
"""If there are media available, return one in a message. """If there are media available, return one in a message.
If shrlok is available, return a link to an HTML page shared by shrlok. If shrlok is available, return a link to an HTML page shared by shrlok.
@ -145,16 +149,19 @@ class TaxrefPlugin(Plugin):
""" """
m_url = item.get("_links", {}).get("media", {}).get("href") m_url = item.get("_links", {}).get("media", {}).get("href")
if not m_url: if not m_url:
self.bot.log_d("No media links.")
return None return None
response = requests.get(m_url) response = requests.get(m_url)
if response.status_code != 200: if (code := response.status_code) != 200:
self.bot.log_d(f"Failed to reach media link ({code}).")
return None return None
media_data = response.json() media_data = response.json()
items = media_data.get("_embedded", {}).get("media", []) items = media_data.get("_embedded", {}).get("media", [])
if not items: if not items:
self.bot.log_d("No media found in response.")
return None return None
def get_img_url(item): def get_img_url(item) -> Optional[str]:
return item.get("_links", {}).get("file", {}).get("href") return item.get("_links", {}).get("file", {}).get("href")
if shrlok := self.bot.get_plugin("shrlok"): if shrlok := self.bot.get_plugin("shrlok"):
@ -163,14 +170,19 @@ class TaxrefPlugin(Plugin):
urls = map(get_img_url, items) urls = map(get_img_url, items)
urls_text = ",".join(map(lambda url: f'"{url}"', urls)) urls_text = ",".join(map(lambda url: f'"{url}"', urls))
html = IMG_FETCH_HTML.format(urls_text) html = IMG_FETCH_HTML.format(urls_text)
link = shrlok.post_html(html) link = shrlok.post_html(html) # type: ignore
if not link:
self.bot.log_d("shrlok plugin returned an empty string.")
else: else:
link = get_img_url(random.choice(items)) link = get_img_url(random.choice(items))
if not link:
self.bot.log_d("No link found.")
if link: if link:
return "📷 " + link return "📷 " + link
return None
def find_scientific_name(self, name, target): def find_scientific_name(self, name: str, target: str):
"""Find a corresponding scientific name for a vernacular name.""" """Find a corresponding scientific name for a vernacular name."""
name = name.lower() name = name.lower()
enc_name = urllib.parse.quote(name) enc_name = urllib.parse.quote(name)
@ -207,7 +219,7 @@ class TaxrefPlugin(Plugin):
) )
+ "\n" + "\n"
) )
reply = shrlok.post_text(text) reply = shrlok.post_text(text) # type: ignore
else: else:
reply = self.get_ambiguous_reply(items) reply = self.get_ambiguous_reply(items)