Improve/simplify telegram exception handling

Move exceptionhandling to the decorator.
This commit is contained in:
Matthias 2022-12-01 06:27:19 +01:00
parent dac4a35be2
commit 95651fcd5a

View File

@ -79,6 +79,8 @@ def authorized_only(command_handler: Callable[..., None]) -> Callable[..., Any]:
)
try:
return command_handler(self, *args, **kwargs)
except RPCException as e:
self._send_msg(str(e))
except BaseException:
logger.exception('Exception occurred within Telegram module')
@ -538,8 +540,6 @@ class Telegram(RPCHandler):
handler for `/status` and `/status <id>`.
"""
try:
# Check if there's at least one numerical ID provided.
# If so, try to get only these trades.
trade_ids = []
@ -602,9 +602,6 @@ class Telegram(RPCHandler):
lines.extend(lines_detail if lines_detail else "")
self.__send_status_msg(lines, r)
except RPCException as e:
self._send_msg(str(e))
def __send_status_msg(self, lines: List[str], r: Dict[str, Any]) -> None:
"""
Send status message.
@ -630,7 +627,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
fiat_currency = self._config.get('fiat_display_currency', '')
statlist, head, fiat_profit_sum = self._rpc._rpc_status_table(
self._config['stake_currency'], fiat_currency)
@ -659,8 +655,6 @@ class Telegram(RPCHandler):
self._send_msg(f"<pre>{message}</pre>", parse_mode=ParseMode.HTML,
reload_able=True, callback_path="update_status_table",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _timeunit_stats(self, update: Update, context: CallbackContext, unit: str) -> None:
@ -686,7 +680,6 @@ class Telegram(RPCHandler):
timescale = int(context.args[0]) if context.args else val.default
except (TypeError, ValueError, IndexError):
timescale = val.default
try:
stats = self._rpc._rpc_timeunit_profit(
timescale,
stake_cur,
@ -713,8 +706,6 @@ class Telegram(RPCHandler):
)
self._send_msg(message, parse_mode=ParseMode.HTML, reload_able=True,
callback_path=val.callback, query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _daily(self, update: Update, context: CallbackContext) -> None:
@ -878,7 +869,6 @@ class Telegram(RPCHandler):
@authorized_only
def _balance(self, update: Update, context: CallbackContext) -> None:
""" Handler for /balance """
try:
result = self._rpc._rpc_balance(self._config['stake_currency'],
self._config.get('fiat_display_currency', ''))
@ -949,8 +939,6 @@ class Telegram(RPCHandler):
f"{fiat_val}\n")
self._send_msg(output, reload_able=True, callback_path="update_balance",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _start(self, update: Update, context: CallbackContext) -> None:
@ -1125,7 +1113,6 @@ class Telegram(RPCHandler):
nrecent = int(context.args[0]) if context.args else 10
except (TypeError, ValueError, IndexError):
nrecent = 10
try:
trades = self._rpc._rpc_trade_history(
nrecent
)
@ -1143,8 +1130,6 @@ class Telegram(RPCHandler):
message = (f"<b>{min(trades['trades_count'], nrecent)} recent trades</b>:\n"
+ (f"<pre>{trades_tab}</pre>" if trades['trades_count'] > 0 else ''))
self._send_msg(message, parse_mode=ParseMode.HTML)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _delete_trade(self, update: Update, context: CallbackContext) -> None:
@ -1155,7 +1140,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
if not context.args or len(context.args) == 0:
raise RPCException("Trade-id not set.")
trade_id = int(context.args[0])
@ -1165,9 +1149,6 @@ class Telegram(RPCHandler):
'Please make sure to take care of this asset on the exchange manually.'
))
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _performance(self, update: Update, context: CallbackContext) -> None:
"""
@ -1177,7 +1158,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
trades = self._rpc._rpc_performance()
output = "<b>Performance:</b>\n"
for i, trade in enumerate(trades):
@ -1196,8 +1176,6 @@ class Telegram(RPCHandler):
self._send_msg(output, parse_mode=ParseMode.HTML,
reload_able=True, callback_path="update_performance",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _enter_tag_performance(self, update: Update, context: CallbackContext) -> None:
@ -1208,7 +1186,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
pair = None
if context.args and isinstance(context.args[0], str):
pair = context.args[0]
@ -1231,8 +1208,6 @@ class Telegram(RPCHandler):
self._send_msg(output, parse_mode=ParseMode.HTML,
reload_able=True, callback_path="update_enter_tag_performance",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _exit_reason_performance(self, update: Update, context: CallbackContext) -> None:
@ -1243,7 +1218,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
pair = None
if context.args and isinstance(context.args[0], str):
pair = context.args[0]
@ -1266,8 +1240,6 @@ class Telegram(RPCHandler):
self._send_msg(output, parse_mode=ParseMode.HTML,
reload_able=True, callback_path="update_exit_reason_performance",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _mix_tag_performance(self, update: Update, context: CallbackContext) -> None:
@ -1278,7 +1250,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
pair = None
if context.args and isinstance(context.args[0], str):
pair = context.args[0]
@ -1301,8 +1272,6 @@ class Telegram(RPCHandler):
self._send_msg(output, parse_mode=ParseMode.HTML,
reload_able=True, callback_path="update_mix_tag_performance",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _count(self, update: Update, context: CallbackContext) -> None:
@ -1313,7 +1282,6 @@ class Telegram(RPCHandler):
:param update: message update
:return: None
"""
try:
counts = self._rpc._rpc_count()
message = tabulate({k: [v] for k, v in counts.items()},
headers=['current', 'max', 'total stake'],
@ -1323,8 +1291,6 @@ class Telegram(RPCHandler):
self._send_msg(message, parse_mode=ParseMode.HTML,
reload_able=True, callback_path="update_count",
query=update.callback_query)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _locks(self, update: Update, context: CallbackContext) -> None:
@ -1372,7 +1338,6 @@ class Telegram(RPCHandler):
Handler for /whitelist
Shows the currently active whitelist
"""
try:
whitelist = self._rpc._rpc_whitelist()
if context.args:
@ -1386,8 +1351,6 @@ class Telegram(RPCHandler):
logger.debug(message)
self._send_msg(message)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _blacklist(self, update: Update, context: CallbackContext) -> None:
@ -1424,7 +1387,6 @@ class Telegram(RPCHandler):
Handler for /logs
Shows the latest logs
"""
try:
try:
limit = int(context.args[0]) if context.args else 10
except (TypeError, ValueError, IndexError):
@ -1447,8 +1409,6 @@ class Telegram(RPCHandler):
if msgs:
self._send_msg(msgs, parse_mode=ParseMode.MARKDOWN_V2)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _edge(self, update: Update, context: CallbackContext) -> None:
@ -1456,7 +1416,6 @@ class Telegram(RPCHandler):
Handler for /edge
Shows information related to Edge
"""
try:
edge_pairs = self._rpc._rpc_edge()
if not edge_pairs:
message = '<b>Edge only validated following pairs:</b>'
@ -1469,9 +1428,6 @@ class Telegram(RPCHandler):
self._send_msg(message, parse_mode=ParseMode.HTML)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _help(self, update: Update, context: CallbackContext) -> None:
"""
@ -1551,12 +1507,9 @@ class Telegram(RPCHandler):
Handler for /health
Shows the last process timestamp
"""
try:
health = self._rpc._health()
message = f"Last process: `{health['last_process_loc']}`"
self._send_msg(message)
except RPCException as e:
self._send_msg(str(e))
@authorized_only
def _version(self, update: Update, context: CallbackContext) -> None: