Add basic exception handling in translation

This commit is contained in:
deadcade 2022-08-27 16:35:33 +02:00
parent 3beb10075f
commit 1713a5180d

12
main.py
View file

@ -364,13 +364,19 @@ async def reaction_callback(room: nio.MatrixRoom, event: nio.UnknownEvent, react
lt = LibreTranslateAPI(settings["libretranslate_api"], settings["libretranslate_api_key"] if "libretranslate_api_key" in settings.keys() and settings["libretranslate_api_key"] else None)
# If the language is not supported
if from_lang not in [x["code"] for x in lt.languages()] and from_lang != "auto":
return await send_text(room.room_id, "Language " + from_lang + " is not supported!")
try:
if from_lang not in [x["code"] for x in lt.languages()] and from_lang != "auto":
return await send_text(room.room_id, "Language " + from_lang + " is not supported!")
except Exception:
return await send_text(room.room_id, "Something went wrong connecting to the LibreTranslate server!")
original_body = reacted_to_event.body
# If the message was a reply
if reacted_to_event.source.get("content", {}).get("m.relates_to", {}).get("m.in_reply_to", {}).get("event_id"):
original_body = "\n\n".join(reacted_to_event.body.split("\n\n")[1:]) # Remove the in reply to part
translated = lt.translate(original_body, from_lang, "en")
try:
translated = lt.translate(original_body, from_lang, "en")
except Exception:
return await send_text(room.room_id, "Something went wrong translating the message!")
lang = lt.detect(reacted_to_event.body)[0]["language"].upper() if from_lang == "auto" else from_lang.upper()
return await send_reply(room.room_id, reacted_to_event, "Translated from " + lang + " (" + flag_emoji("US" if lang == "EN" else lang) + "):\n" + translated + "\n")