Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Exceptions, Warnings and Logging

Bibo-Joshi edited this pageOct 29, 2024 ·14 revisions

While you program your bot and while the bot is running there can be several things that can go wrong. This page gives an overview on how you can handle those situations.

Exceptions

Inpython-telegram-bot, all Telegram-related errors are encapsulated in theTelegramError exception class and its subclasses, located intelegram.error module.

Any error, includingTelegramError, that is raised in one of your handler or job callbacks (or while callingget_updates in theUpdater), is forwarded to all registered error handlers, so you can react to them. You can register an error handler by callingApplication.add_error_handler(callback), wherecallback is a coroutine function that takes theupdate andcontext.update will be the update that caused the error (orNone if the error wasn't caused by an update, e.g. forJobs) andcontext.error the error that was raised.

The good news is that exceptions that are handled by the error handlers don't stop your python process - your bot will just keep running!

Example: You're trying to send a message, but the user blocked the bot. AnForbidden exception, a subclass ofTelegramError, will be raised and delivered to your error handler, so you can delete it from your conversation list, if you keep one.

Note

The error handler might be only your last resort - of course you can also handle exceptions as they occur. Only uncaught exceptions are forwarded to the error handler.

Other common approaches for more fine-grained error handling are usingtry-except in crucial places or by implementing a custom retry-mechanism by subclassingBaseRequest orHTTPXRequest.

Example

For an example on how an error handler might look like, please head over to theexamples directory.

Logging

In case you don't have an error handler registered, PTB willlog any unhandled exception.For logging, PTB uses Python'slogging module.To set up logging to standard output, you can write something like

importlogginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

at the beginning of your script. If you want debug logs instead, uselevel=logging.DEBUG.python-telegram-bot makes some more verbose log entries on thelogging.DEBUG level that might be helpful when you're trying to debug your bot.

Note that also some third-party libraries thatpython-telegram-bot uses, make log entries in the same manner. If you are using thebasicConfig from the example above, you will see that your log is cluttered with entries byhttpx: starting withv.0.24.1,httpx logs all requests atINFO level, which makes sense forhttpx but could annoy you as a PTB user.

In this case, you can set logging level specifically forhttpx andhttpcore (used byhttpx:

importlogginglogging.getLogger('httpx').setLevel(logging.WARNING)logging.getLogger('httpcore').setLevel(logging.WARNING)

If you set logging level toDEBUG for your application, you might want to set it toINFO forhttpx (so you can see the requests that are made).

Another example: if you don't want to see the logs of theAPScheduler library about yourJobQueue jobs being scheduled, you can specify the logging level ofAPScheduler as follows:

importlogginglogging.getLogger('apscheduler').setLevel(logging.WARNING)

Warnings

In contrast to exceptions, warnings usually don't indicate that something already did go wrong, but rather that somethingcould go wrong or at least could be improved.Warnings issued bypython-telegram-bot are encapsulated inPTBUserWarning or one of the subclasses, located in thetelegram.warnings module.This allows you to easily handle the warnings using Pythonswarnings library.For example, if you don't want to miss any deprecation warning during development, you can tell Python to turn every such warning issued by PTB into an exception via

importwarningsfromtelegram.warningsimportPTBDeprecationWarningwarnings.filterwarnings("error",category=PTBDeprecationWarning)

Wiki ofpython-telegram-bot © Copyright 2015-2025 – Licensed byCreative Commons

Must read

  1. Introduction to the API
  2. Tutorial: Your first bot
  3. FAQ
  4. How to ask good questions
  5. How to write an MWE

Concepts & Important Elements

  1. Architecture Overview
  2. Builder Pattern forApplication
  3. Types of Handlers
  4. Working with Files and Media
  5. Exceptions, Warnings and Logging
  6. Concurrency in PTB

Notable Features

  1. Advanced Filters
  2. Storing data
  3. Making your bot persistent
  4. Adding Defaults
  5. Job Queue
  6. Arbitrarycallback_data
  7. Avoiding flood limits
  8. Webhooks
  9. Bot API Forward Compatiblity

Code Resources

  1. Frequently requested design patterns
  2. Code snippets
  3. Performance Optimizations
  4. Telegram Passport
  5. Bots built with PTB
  6. Automated Bot Tests

Examples explained

  1. InlineKeyboard Example

Networking

  1. Working Behind a Proxy
  2. Handling network errors

Other resources

  1. Where to host Telegram Bots
  2. How to host your bot
  3. Local API Server
  4. Type Checking with PTB
  5. Press
  6. Notes on GAE
  7. Related Projects
  8. Emoji

Transition Guides

Administration

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp