From e1fd96feb48a0f7deabafa3ddb2f2daf3ba6a8b8 Mon Sep 17 00:00:00 2001 From: hyfc <3365132+hyfc@users.noreply.github.com> Date: Sun, 24 Jun 2018 19:13:57 +0800 Subject: coping with large text entities --- bot.py | 17 ++++++++++++++--- utils/client.py | 4 ++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/bot.py b/bot.py index 85c32d2..43134ec 100644 --- a/bot.py +++ b/bot.py @@ -3,6 +3,7 @@ import os from utils.client import EmailClient from telegram import ParseMode +from telegram.constants import MAX_MESSAGE_LENGTH from telegram.ext import (Updater, CommandHandler) @@ -12,6 +13,15 @@ logger = logging.getLogger(__name__) bot_token = os.environ['TELEGRAM_TOKEN'] +def handle_large_text(text): + while text: + if len(text) < MAX_MESSAGE_LENGTH: + yield text + text = None + else: + out = text[:MAX_MESSAGE_LENGTH] + yield out + text = text.lstrip(out) def error(bot, update, _error): """Log Errors caused by Updates.""" @@ -48,9 +58,10 @@ def get_email(bot, update, args): index = args[0] with EmailClient(email_addr, email_passwd) as client: mail = client.get_mail_by_index(index) - bot.send_message(update.message.chat_id, - parse_mode=ParseMode.MARKDOWN, - text=mail) + content = mail.__repr__() + for text in handle_large_text(content): + bot.send_message(update.message.chat_id, + text=text) def main(): # Create the EventHandler and pass it your bot's token. diff --git a/utils/client.py b/utils/client.py index 07518bb..1dc9205 100644 --- a/utils/client.py +++ b/utils/client.py @@ -43,10 +43,10 @@ class EmailClient(object): def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: - print('exited normally\n') + logger.info('exited normally\n') self.server.quit() else: - print('raise an exception! ' + str(exc_type)) + logger.error('raise an exception! ' + str(exc_type)) self.server.close() return False # Propagate -- cgit v1.2.3