Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

translate: catch requests exceptions #2153

Merged
merged 1 commit into from
Jul 10, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions sopel/modules/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import generator_stop

import json
import logging
import random

import requests
Expand All @@ -17,6 +18,7 @@
from sopel.tools import web


LOGGER = logging.getLogger(__name__)
PLUGIN_OUTPUT_PREFIX = '[translate] '


Expand Down Expand Up @@ -64,6 +66,9 @@ def translate(text, in_lang='auto', out_lang='en'):
try:
data = json.loads(result)
except ValueError:
LOGGER.error(
'Error parsing JSON response from translate API (%s to %s: "%s")',
in_lang, out_lang, text)
return None, None

if raw:
Expand Down Expand Up @@ -100,7 +105,21 @@ def tr(bot, trigger):
bot.reply('Language guessing failed, so try suggesting one!')
return

msg, in_lang = translate(phrase, in_lang, out_lang)
try:
msg, in_lang = translate(phrase, in_lang, out_lang)
except requests.Timeout:
bot.reply("Translation service unavailable (timeout).")
LOGGER.error(
'Translate API error (%s to %s: "%s"): timeout.',
in_lang, out_lang, phrase)
return
except requests.RequestException as http_error:
bot.reply("Translation request failed.")
LOGGER.exception(
'Translate API error (%s to %s: "%s"): %s.',
in_lang, out_lang, phrase, http_error)
return

if not in_lang:
bot.reply("Translation failed, probably because of a rate-limit.")
return
Expand Down Expand Up @@ -164,7 +183,21 @@ def langcode(p):
bot.reply('Language guessing failed, so try suggesting one!')
return

msg, src = translate(phrase, src, dest)
try:
msg, src = translate(phrase, src, dest)
except requests.Timeout:
bot.reply("Translation service unavailable (timeout).")
LOGGER.error(
'Translate API error (%s to %s: "%s"): timeout.',
src, dest, phrase)
return
except requests.RequestException as http_error:
bot.reply("Translation request failed.")
LOGGER.exception(
'Translate API error (%s to %s: "%s"): %s.',
src, dest, phrase, http_error)
return

if not src:
return bot.say("Translation failed, probably because of a rate-limit.")

Expand Down