mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2024-11-25 16:46:35 +01:00
a4e78f6183
* 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 <hinrich.mahler@freenet.de>
95 lines
3.4 KiB
Python
95 lines
3.4 KiB
Python
#!/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'
|
|
'<pre>update = {}</pre>\n\n'
|
|
'<pre>context.chat_data = {}</pre>\n\n'
|
|
'<pre>context.user_data = {}</pre>\n\n'
|
|
'<pre>{}</pre>'
|
|
).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 <code>{}</code>.'
|
|
.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()
|