Simplify update message sending

This commit is contained in:
Matthias 2021-06-13 20:21:43 +02:00
parent d32508aa75
commit 03eff69829

View File

@ -10,12 +10,12 @@ from datetime import date, datetime, timedelta
from html import escape from html import escape
from itertools import chain from itertools import chain
from math import isnan from math import isnan
from typing import Any, Callable, Dict, List, Union, cast from typing import Any, Callable, Dict, List, Union
import arrow import arrow
from tabulate import tabulate from tabulate import tabulate
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ParseMode, from telegram import (CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton,
ReplyKeyboardMarkup, Update) ParseMode, ReplyKeyboardMarkup, Update)
from telegram.error import BadRequest, NetworkError, TelegramError from telegram.error import BadRequest, NetworkError, TelegramError
from telegram.ext import CallbackContext, CallbackQueryHandler, CommandHandler, Updater from telegram.ext import CallbackContext, CallbackQueryHandler, CommandHandler, Updater
from telegram.utils.helpers import escape_markdown from telegram.utils.helpers import escape_markdown
@ -180,8 +180,8 @@ class Telegram(RPCHandler):
for handle in handles: for handle in handles:
self._updater.dispatcher.add_handler(handle) self._updater.dispatcher.add_handler(handle)
for handle in callbacks: for callback in callbacks:
self._updater.dispatcher.add_handler(handle) self._updater.dispatcher.add_handler(callback)
self._updater.start_polling( self._updater.start_polling(
bootstrap_retries=-1, bootstrap_retries=-1,
@ -422,9 +422,7 @@ class Telegram(RPCHandler):
lines = message.split("\n") lines = message.split("\n")
message = "\n".join(lines[:-1] + [lines[1]] + [lines[-1]]) message = "\n".join(lines[:-1] + [lines[1]] + [lines[-1]])
if(messages_count == 1 and update.callback_query): if(messages_count == 1 and update.callback_query):
query = update.callback_query self._update_msg(query=update.callback_query,
self._update_msg(chat_id=query.message.chat_id,
message_id=query.message.message_id,
msg=f"<pre>{message}</pre>", msg=f"<pre>{message}</pre>",
parse_mode=ParseMode.HTML, parse_mode=ParseMode.HTML,
callback_path="update_status_table", reload_able=True) callback_path="update_status_table", reload_able=True)
@ -469,8 +467,7 @@ class Telegram(RPCHandler):
tablefmt='simple') tablefmt='simple')
message = f'<b>Daily Profit over the last {timescale} days</b>:\n<pre>{stats_tab}</pre>' message = f'<b>Daily Profit over the last {timescale} days</b>:\n<pre>{stats_tab}</pre>'
if(update.callback_query): if(update.callback_query):
query = update.callback_query self._update_msg(query=update.callback_query,
self._update_msg(chat_id=query.message.chat_id, message_id=query.message.message_id,
msg=message, parse_mode=ParseMode.HTML, msg=message, parse_mode=ParseMode.HTML,
callback_path="update_daily", reload_able=True) callback_path="update_daily", reload_able=True)
else: else:
@ -548,8 +545,7 @@ class Telegram(RPCHandler):
markdown_msg += (f"\n*Avg. Duration:* `{avg_duration}`\n" markdown_msg += (f"\n*Avg. Duration:* `{avg_duration}`\n"
f"*Best Performing:* `{best_pair}: {best_rate:.2f}%`") f"*Best Performing:* `{best_pair}: {best_rate:.2f}%`")
if(update.callback_query): if(update.callback_query):
query = update.callback_query self._update_msg(query=update.callback_query,
self._update_msg(chat_id=query.message.chat_id, message_id=query.message.message_id,
msg=markdown_msg, callback_path="update_profit", reload_able=True) msg=markdown_msg, callback_path="update_profit", reload_able=True)
else: else:
self._send_msg(msg=markdown_msg, callback_path="update_profit", reload_able=True) self._send_msg(msg=markdown_msg, callback_path="update_profit", reload_able=True)
@ -640,8 +636,7 @@ class Telegram(RPCHandler):
f"\t`{result['symbol']}: " f"\t`{result['symbol']}: "
f"{round_coin_value(result['value'], result['symbol'], False)}`\n") f"{round_coin_value(result['value'], result['symbol'], False)}`\n")
if(update.callback_query): if(update.callback_query):
query = update.callback_query self._update_msg(query=update.callback_query,
self._update_msg(chat_id=query.message.chat_id, message_id=query.message.message_id,
msg=output, callback_path="update_balance", reload_able=True) msg=output, callback_path="update_balance", reload_able=True)
else: else:
self._send_msg(msg=output, callback_path="update_balance", reload_able=True) self._send_msg(msg=output, callback_path="update_balance", reload_able=True)
@ -841,8 +836,7 @@ class Telegram(RPCHandler):
output += stat_line output += stat_line
if(sent_messages == 0 and update.callback_query): if(sent_messages == 0 and update.callback_query):
query = update.callback_query self._update_msg(query=update.callback_query,
self._update_msg(chat_id=query.message.chat_id, message_id=query.message.message_id,
msg=output, parse_mode=ParseMode.HTML, msg=output, parse_mode=ParseMode.HTML,
callback_path="update_performance", reload_able=True) callback_path="update_performance", reload_able=True)
else: else:
@ -868,8 +862,7 @@ class Telegram(RPCHandler):
message = "<pre>{}</pre>".format(message) message = "<pre>{}</pre>".format(message)
logger.debug(message) logger.debug(message)
if(update.callback_query): if(update.callback_query):
query = update.callback_query self._update_msg(query=update.callback_query,
self._update_msg(chat_id=query.message.chat_id, message_id=query.message.message_id,
msg=message, parse_mode=ParseMode.HTML, msg=message, parse_mode=ParseMode.HTML,
callback_path="update_count", reload_able=True) callback_path="update_count", reload_able=True)
else: else:
@ -1106,7 +1099,7 @@ class Telegram(RPCHandler):
f"*Current state:* `{val['state']}`" f"*Current state:* `{val['state']}`"
) )
def _update_msg(self, chat_id: str, message_id: str, msg: str, callback_path: str = "", def _update_msg(self, query: CallbackQuery, msg: str, callback_path: str = "",
reload_able: bool = False, parse_mode: str = ParseMode.MARKDOWN) -> None: reload_able: bool = False, parse_mode: str = ParseMode.MARKDOWN) -> None:
if reload_able: if reload_able:
reply_markup = InlineKeyboardMarkup([ reply_markup = InlineKeyboardMarkup([
@ -1115,6 +1108,11 @@ class Telegram(RPCHandler):
else: else:
reply_markup = InlineKeyboardMarkup([[]]) reply_markup = InlineKeyboardMarkup([[]])
msg += "\nUpdated: {}".format(datetime.now().ctime()) msg += "\nUpdated: {}".format(datetime.now().ctime())
if not query.message:
return
chat_id = query.message.chat_id
message_id = query.message.message_id
try: try:
try: try:
self._updater.bot.edit_message_text( self._updater.bot.edit_message_text(