catch TelegramError (fixes #113)

This commit is contained in:
gcarq 2017-11-17 19:47:29 +01:00
parent 77887d6fbc
commit 59d04d1d0c
2 changed files with 15 additions and 12 deletions

View File

@ -8,7 +8,7 @@ from tabulate import tabulate
import arrow import arrow
from sqlalchemy import and_, func, text from sqlalchemy import and_, func, text
from telegram import ParseMode, Bot, Update from telegram import ParseMode, Bot, Update
from telegram.error import NetworkError from telegram.error import NetworkError, TelegramError
from telegram.ext import CommandHandler, Updater from telegram.ext import CommandHandler, Updater
from freqtrade import exchange, __version__ from freqtrade import exchange, __version__
@ -475,13 +475,17 @@ def send_msg(msg: str, bot: Bot = None, parse_mode: ParseMode = ParseMode.MARKDO
return return
bot = bot or _UPDATER.bot bot = bot or _UPDATER.bot
try: try:
bot.send_message(_CONF['telegram']['chat_id'], msg, parse_mode=parse_mode) try:
except NetworkError as error: bot.send_message(_CONF['telegram']['chat_id'], msg, parse_mode=parse_mode)
# Sometimes the telegram server resets the current connection, except NetworkError as network_err:
# if this is the case we send the message again. # Sometimes the telegram server resets the current connection,
logger.warning( # if this is the case we send the message again.
'Got Telegram NetworkError: %s! Trying one more time.', logger.warning(
error.message 'Got Telegram NetworkError: %s! Trying one more time.',
) network_err.message
bot.send_message(_CONF['telegram']['chat_id'], msg, parse_mode=parse_mode) )
bot.send_message(_CONF['telegram']['chat_id'], msg, parse_mode=parse_mode)
except TelegramError as telegram_err:
logger.warning('Got TelegramError: %s! Giving up on that message.', telegram_err.message)

View File

@ -535,8 +535,7 @@ def test_send_msg_network_error(default_conf, mocker):
default_conf['telegram']['enabled'] = True default_conf['telegram']['enabled'] = True
bot = MagicMock() bot = MagicMock()
bot.send_message = MagicMock(side_effect=NetworkError('Oh snap')) bot.send_message = MagicMock(side_effect=NetworkError('Oh snap'))
with pytest.raises(NetworkError, match=r'Oh snap'): send_msg('test', bot)
send_msg('test', bot)
# Bot should've tried to send it twice # Bot should've tried to send it twice
assert len(bot.method_calls) == 2 assert len(bot.method_calls) == 2