errorhandlerbot.pyΒΆ

 1#!/usr/bin/env python
 2# pylint: disable=unused-argument, wrong-import-position
 3# This program is dedicated to the public domain under the CC0 license.
 4
 5"""This is a very simple example on how one could implement a custom error handler."""
 6import html
 7import json
 8import logging
 9import traceback
10
11from telegram import __version__ as TG_VER
12
13try:
14    from telegram import __version_info__
15except ImportError:
16    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
17
18if __version_info__ < (20, 0, 0, "alpha", 1):
19    raise RuntimeError(
20        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
21        f"{TG_VER} version of this example, "
22        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
23    )
24from telegram import Update
25from telegram.constants import ParseMode
26from telegram.ext import Application, CommandHandler, ContextTypes
27
28# Enable logging
29logging.basicConfig(
30    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
31)
32logger = logging.getLogger(__name__)
33
34# This can be your own ID, or one for a developer group/channel.
35# You can use the /start command of this bot to see your chat id.
36DEVELOPER_CHAT_ID = 123456789
37
38
39async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
40    """Log the error and send a telegram message to notify the developer."""
41    # Log the error before we do anything else, so we can see it even if something breaks.
42    logger.error(msg="Exception while handling an update:", exc_info=context.error)
43
44    # traceback.format_exception returns the usual python message about an exception, but as a
45    # list of strings rather than a single string, so we have to join them together.
46    tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
47    tb_string = "".join(tb_list)
48
49    # Build the message with some markup and additional information about what happened.
50    # You might need to add some logic to deal with messages longer than the 4096 character limit.
51    update_str = update.to_dict() if isinstance(update, Update) else str(update)
52    message = (
53        f"An exception was raised while handling an update\n"
54        f"<pre>update = {html.escape(json.dumps(update_str, indent=2, ensure_ascii=False))}"
55        "</pre>\n\n"
56        f"<pre>context.chat_data = {html.escape(str(context.chat_data))}</pre>\n\n"
57        f"<pre>context.user_data = {html.escape(str(context.user_data))}</pre>\n\n"
58        f"<pre>{html.escape(tb_string)}</pre>"
59    )
60
61    # Finally, send the message
62    await context.bot.send_message(
63        chat_id=DEVELOPER_CHAT_ID, text=message, parse_mode=ParseMode.HTML
64    )
65
66
67async def bad_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
68    """Raise an error to trigger the error handler."""
69    await context.bot.wrong_method_name()  # type: ignore[attr-defined]
70
71
72async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
73    """Displays info on how to trigger an error."""
74    await update.effective_message.reply_html(
75        "Use /bad_command to cause an error.\n"
76        f"Your chat id is <code>{update.effective_chat.id}</code>."
77    )
78
79
80def main() -> None:
81    """Run the bot."""
82    # Create the Application and pass it your bot's token.
83    application = Application.builder().token("TOKEN").build()
84
85    # Register the commands...
86    application.add_handler(CommandHandler("start", start))
87    application.add_handler(CommandHandler("bad_command", bad_command))
88
89    # ...and the error handler
90    application.add_error_handler(error_handler)
91
92    # Run the bot until the user presses Ctrl-C
93    application.run_polling()
94
95
96if __name__ == "__main__":
97    main()