From a4e78f6183ca3a54b869d35d6d87e1d003e70462 Mon Sep 17 00:00:00 2001 From: n5y <41209360+n5y@users.noreply.github.com> Date: Fri, 12 Jun 2020 19:50:12 +0300 Subject: [PATCH] Add standalone example on error handlers (#1983) * Remove error handlers from examples Most examples use the same error handler, that error handler logs update.to_dict but doesn't log error traceback. Hiding error traceback is quite bad, removing the error handler entirely causes PTB to use default error logging which does include error traceback. * adding error handling example * Change error handler example Including: - Change the telegram message to include usual python error message. - HTML-escape the strings used to build the telegram message. - Capitalize comments and add more empty lines to hopefully unify the style with other examples, at least a bit. - Reorder imports. * Add an error-rising command to the error handler example * Slightly change example error handler docstring and comments * Make telegram message sent by the error handler example more readable * Rename error_handler.py to errorhandlerbot.py and add a start command * Change error handler example to work without developer chat id * Revert "Change error handler example to work without developer chat id" This reverts commit c4efea6f * Make bot token a module level constant in the error handler example Otherwise the example will require two edits 40 lines apart to run. * Show chat id in start command of the error handler example The example requires you to set developer chat id, this change will make things easier for users that don't know how to see their chat id. * Add errorhandlerbot.py to the examples folder readme Co-authored-by: poolitzer <25934244+poolitzer@users.noreply.github.com> Co-authored-by: Bibo-Joshi --- examples/README.md | 3 + examples/conversationbot.py | 8 --- examples/conversationbot2.py | 8 --- examples/deeplinking.py | 8 --- examples/echobot2.py | 8 --- examples/errorhandlerbot.py | 95 +++++++++++++++++++++++++++ examples/inlinebot.py | 8 --- examples/inlinekeyboard.py | 6 -- examples/inlinekeyboard2.py | 8 --- examples/nestedconversationbot.py | 9 --- examples/passportbot.py | 8 --- examples/paymentbot.py | 8 --- examples/persistentconversationbot.py | 7 -- examples/timerbot.py | 8 --- 14 files changed, 98 insertions(+), 94 deletions(-) create mode 100644 examples/errorhandlerbot.py diff --git a/examples/README.md b/examples/README.md index 557a14e60..42b7cc1bb 100644 --- a/examples/README.md +++ b/examples/README.md @@ -43,5 +43,8 @@ A basic example of a bot that can accept passports. Use in combination with [`pa ### [`paymentbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/paymentbot.py) A basic example of a bot that can accept payments. Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather). +### [`errorhandlerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/errorhandlerbot.py) +A basic example on how to set up a costum error handler. + ## Pure API The [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py) example uses only the pure, "bare-metal" API wrapper. diff --git a/examples/conversationbot.py b/examples/conversationbot.py index 21bbee983..b88d58de8 100644 --- a/examples/conversationbot.py +++ b/examples/conversationbot.py @@ -108,11 +108,6 @@ def cancel(update, context): return ConversationHandler.END -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks @@ -143,9 +138,6 @@ def main(): dp.add_handler(conv_handler) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index 8787a4a2f..fdb0a9bce 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -96,11 +96,6 @@ def done(update, context): return ConversationHandler.END -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks @@ -135,9 +130,6 @@ def main(): dp.add_handler(conv_handler) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/deeplinking.py b/examples/deeplinking.py index f10083490..b4d92d26e 100644 --- a/examples/deeplinking.py +++ b/examples/deeplinking.py @@ -72,11 +72,6 @@ def deep_linked_level_3(update, context): "The payload was: {0}".format(payload)) -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. @@ -103,9 +98,6 @@ def main(): # Make sure the deep-linking handlers occur *before* the normal /start handler. dp.add_handler(CommandHandler("start", start)) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/echobot2.py b/examples/echobot2.py index 7bc381918..b6abbbbad 100644 --- a/examples/echobot2.py +++ b/examples/echobot2.py @@ -43,11 +43,6 @@ def echo(update, context): update.message.reply_text(update.message.text) -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): """Start the bot.""" # Create the Updater and pass it your bot's token. @@ -65,9 +60,6 @@ def main(): # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, echo)) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/errorhandlerbot.py b/examples/errorhandlerbot.py new file mode 100644 index 000000000..1dfbac756 --- /dev/null +++ b/examples/errorhandlerbot.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# This program is dedicated to the public domain under the CC0 license. + +""" +This is a very simple example on how one could implement a custom error handler +""" +import html +import json +import logging +import traceback + +from telegram import Update, ParseMode +from telegram.ext import Updater, CallbackContext, CommandHandler + +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) + +logger = logging.getLogger(__name__) + +# The token you got from @botfather when you created the bot +BOT_TOKEN = "TOKEN" + +# This can be your own ID, or one for a developer group/channel. +# You can use the /start command of this bot to see your chat id. +DEVELOPER_CHAT_ID = 123456789 + + +def error_handler(update: Update, context: CallbackContext): + """Log the error and send a telegram message to notify the developer.""" + # Log the error before we do anything else, so we can see it even if something breaks. + logger.error(msg="Exception while handling an update:", exc_info=context.error) + + # traceback.format_exception returns the usual python message about an exception, but as a + # list of strings rather than a single string, so we have to join them together. + tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) + tb = ''.join(tb_list) + + # Build the message with some markup and additional information about what happened. + # You might need to add some logic to deal with messages longer than the 4096 character limit. + message = ( + 'An exception was raised while handling an update\n' + '
update = {}
\n\n' + '
context.chat_data = {}
\n\n' + '
context.user_data = {}
\n\n' + '
{}
' + ).format( + html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)), + html.escape(str(context.chat_data)), + html.escape(str(context.user_data)), + html.escape(tb) + ) + + # Finally, send the message + context.bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=message, parse_mode=ParseMode.HTML) + + +def bad_command(update: Update, context: CallbackContext): + """Raise an error to trigger the error handler.""" + context.bot.wrong_method_name() + + +def start(update: Update, context: CallbackContext): + update.effective_message.reply_html('Use /bad_command to cause an error.\n' + 'Your chat id is {}.' + .format(update.effective_chat.id)) + + +def main(): + # Create the Updater and pass it your bot's token. + # Make sure to set use_context=True to use the new context based callbacks + # Post version 12 this will no longer be necessary + updater = Updater(BOT_TOKEN, use_context=True) + + # Get the dispatcher to register handlers + dp = updater.dispatcher + + # Register the commands... + dp.add_handler(CommandHandler('start', start)) + dp.add_handler(CommandHandler('bad_command', bad_command)) + + # ...and the error handler + dp.add_error_handler(error_handler) + + # Start the Bot + updater.start_polling() + + # Run the bot until you press Ctrl-C or the process receives SIGINT, + # SIGTERM or SIGABRT. This should be used most of the time, since + # start_polling() is non-blocking and will stop the bot gracefully. + updater.idle() + + +if __name__ == '__main__': + main() diff --git a/examples/inlinebot.py b/examples/inlinebot.py index e1b38945e..f1b3e2f84 100644 --- a/examples/inlinebot.py +++ b/examples/inlinebot.py @@ -64,11 +64,6 @@ def inlinequery(update, context): update.inline_query.answer(results) -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks @@ -85,9 +80,6 @@ def main(): # on noncommand i.e message - echo the message on Telegram dp.add_handler(InlineQueryHandler(inlinequery)) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/inlinekeyboard.py b/examples/inlinekeyboard.py index 9748d4439..ffc7a164b 100644 --- a/examples/inlinekeyboard.py +++ b/examples/inlinekeyboard.py @@ -40,11 +40,6 @@ def help(update, context): update.message.reply_text("Use /start to test this bot.") -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks @@ -54,7 +49,6 @@ def main(): updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler(CommandHandler('help', help)) - updater.dispatcher.add_error_handler(error) # Start the Bot updater.start_polling() diff --git a/examples/inlinekeyboard2.py b/examples/inlinekeyboard2.py index 2befc8a1a..1242f7066 100644 --- a/examples/inlinekeyboard2.py +++ b/examples/inlinekeyboard2.py @@ -149,11 +149,6 @@ def end(update, context): return ConversationHandler.END -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. updater = Updater("TOKEN", use_context=True) @@ -184,9 +179,6 @@ def main(): # updates dp.add_handler(conv_handler) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/nestedconversationbot.py b/examples/nestedconversationbot.py index 58149b77f..14d59ad38 100644 --- a/examples/nestedconversationbot.py +++ b/examples/nestedconversationbot.py @@ -267,12 +267,6 @@ def stop_nested(update, context): return STOPPING -# Error handler -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks @@ -359,9 +353,6 @@ def main(): dp.add_handler(conv_handler) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/passportbot.py b/examples/passportbot.py index 5d57f731e..c66a97f69 100644 --- a/examples/passportbot.py +++ b/examples/passportbot.py @@ -77,11 +77,6 @@ def msg(update, context): actual_file.download() -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): """Start the bot.""" # Create the Updater and pass it your token and private key @@ -93,9 +88,6 @@ def main(): # On messages that include passport data call msg dp.add_handler(MessageHandler(Filters.passport_data, msg)) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/paymentbot.py b/examples/paymentbot.py index 5c65a043c..ae873c931 100644 --- a/examples/paymentbot.py +++ b/examples/paymentbot.py @@ -19,11 +19,6 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s logger = logging.getLogger(__name__) -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def start_callback(update, context): msg = "Use /shipping to get an invoice for shipping-payment, " msg += "or /noshipping for an invoice without shipping." @@ -134,9 +129,6 @@ def main(): # Success! Notify your user! dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback)) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling() diff --git a/examples/persistentconversationbot.py b/examples/persistentconversationbot.py index 708d79bd2..086a3091d 100644 --- a/examples/persistentconversationbot.py +++ b/examples/persistentconversationbot.py @@ -107,11 +107,6 @@ def done(update, context): return ConversationHandler.END -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): # Create the Updater and pass it your bot's token. pp = PicklePersistence(filename='conversationbot') @@ -149,8 +144,6 @@ def main(): show_data_handler = CommandHandler('show_data', show_data) dp.add_handler(show_data_handler) - # log all errors - dp.add_error_handler(error) # Start the Bot updater.start_polling() diff --git a/examples/timerbot.py b/examples/timerbot.py index 8cb777dc5..1baddacc5 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -77,11 +77,6 @@ def unset(update, context): update.message.reply_text('Timer successfully unset!') -def error(update, context): - """Log Errors caused by Updates.""" - logger.warning('Update "%s" caused error "%s"', update, context.error) - - def main(): """Run bot.""" # Create the Updater and pass it your bot's token. @@ -101,9 +96,6 @@ def main(): pass_chat_data=True)) dp.add_handler(CommandHandler("unset", unset, pass_chat_data=True)) - # log all errors - dp.add_error_handler(error) - # Start the Bot updater.start_polling()