|
9 | 9 | from __future__ import generator_stop |
10 | 10 |
|
11 | 11 | import json |
| 12 | +import logging |
12 | 13 | import random |
13 | 14 |
|
14 | 15 | import requests |
|
17 | 18 | from sopel.tools import web |
18 | 19 |
|
19 | 20 |
|
| 21 | +LOGGER = logging.getLogger(__name__) |
20 | 22 | PLUGIN_OUTPUT_PREFIX = '[translate] ' |
21 | 23 |
|
22 | 24 |
|
@@ -64,6 +66,9 @@ def translate(text, in_lang='auto', out_lang='en'): |
64 | 66 | try: |
65 | 67 | data = json.loads(result) |
66 | 68 | except ValueError: |
| 69 | + LOGGER.error( |
| 70 | + 'Error parsing JSON response from translate API (%s to %s: "%s")', |
| 71 | + in_lang, out_lang, text) |
67 | 72 | return None, None |
68 | 73 |
|
69 | 74 | if raw: |
@@ -100,7 +105,21 @@ def tr(bot, trigger): |
100 | 105 | bot.reply('Language guessing failed, so try suggesting one!') |
101 | 106 | return |
102 | 107 |
|
103 | | - msg, in_lang = translate(phrase, in_lang, out_lang) |
| 108 | + try: |
| 109 | + msg, in_lang = translate(phrase, in_lang, out_lang) |
| 110 | + except requests.Timeout: |
| 111 | + bot.reply("Translation service unavailable (timeout).") |
| 112 | + LOGGER.error( |
| 113 | + 'Transalate API error (%s to %s: "%s"): timeout.', |
| 114 | + in_lang, out_lang, phrase) |
| 115 | + return |
| 116 | + except requests.RequestException as http_error: |
| 117 | + bot.reply("Failed to request the translation service.") |
| 118 | + LOGGER.exception( |
| 119 | + 'Transalate API error (%s to %s: "%s"): %s.', |
| 120 | + in_lang, out_lang, phrase, http_error) |
| 121 | + return |
| 122 | + |
104 | 123 | if not in_lang: |
105 | 124 | bot.reply("Translation failed, probably because of a rate-limit.") |
106 | 125 | return |
@@ -164,7 +183,21 @@ def langcode(p): |
164 | 183 | bot.reply('Language guessing failed, so try suggesting one!') |
165 | 184 | return |
166 | 185 |
|
167 | | - msg, src = translate(phrase, src, dest) |
| 186 | + try: |
| 187 | + msg, src = translate(phrase, src, dest) |
| 188 | + except requests.Timeout: |
| 189 | + bot.reply("Translation service unavailable (timeout).") |
| 190 | + LOGGER.error( |
| 191 | + 'Transalate API error (%s to %s: "%s"): timeout.', |
| 192 | + src, dest, phrase) |
| 193 | + return |
| 194 | + except requests.RequestException as http_error: |
| 195 | + bot.reply("Failed to request the translation service.") |
| 196 | + LOGGER.exception( |
| 197 | + 'Transalate API error (%s to %s: "%s"): %s.', |
| 198 | + src, dest, phrase, http_error) |
| 199 | + return |
| 200 | + |
168 | 201 | if not src: |
169 | 202 | return bot.say("Translation failed, probably because of a rate-limit.") |
170 | 203 |
|
|
0 commit comments