Add basic exception handling in translation
This commit is contained in:
parent
3beb10075f
commit
1713a5180d
1 changed files with 9 additions and 3 deletions
6
main.py
6
main.py
|
@ -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
|
||||
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
|
||||
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")
|
||||
|
||||
|
|
Loading…
Reference in a new issue