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

Handling network errors

Hinrich Mahler edited this pageDec 7, 2024 ·14 revisions

Background

Network errors can happen at many levels, on the local side, on the remote or somewhere along the way.

It is hard for applications to identify when an error occurs as it is not always something that can be identified in real time but rather when an additional event happens.

Network errors are a problem which each application have to deal with. Each application for its own use case and desired service level.

Where things can break?

Locally (in PTB)

For something to "break" locally we need to close the network socket. This is something that PTB doesn't do voluntarily and basically if you've encountered such a case, it's a bug.

Remotely on Telegram servers

There is a suspicion that Telegram are closing connections on some conditions. Whether it is true or not we can't really tell. The application should still be able to deal with it.

Somewhere along the way

How to mitigate?

Analysis

There is no one way to handle networking issues. Each bot has its own usage pattern and unique network behaviour.

Some bots will require providing answer to user requests within a limited time, while others can take all the time they need.Some bots will be ok with "losing" a sent message once in a while, while others must ensure that the message was sent within a limited time frame.Some bots send big files, while others only receive small files. Etc., etc.

In addition, the network connection takes an important factor. Hosting your bot in a region with poor Internet (bandwidth / packet lost / disconnections) is the obvious example, but it is not the only problem.In case the bot is hosted "far" from the Telegram Bot servers you'll experience greater latency and possibly more packet loss. TCP should be able to handle packet loss, however, there are side effects for that (when will TCP identify the loss of a packet? what will be the window size? etc.).

Hosting the bot on a slow server can also affect performance and may be observed as networking issues.

Once you've understood the usage pattern of your bot (that includes the QoS) you can go into fine-tuning the ptb library for your needs.

Tweaking PTB

Networking backend tweaks

PTB performs HTTPS requests using thetelegram.request.BaseRequest interface.The methodBaseRequest.do_request accepts four parameters for controlling timeouts:

  • read_timeout specifies the maximum amount of time (in seconds) to wait for a response from Telegram’s server
  • write_timeout specifies the maximum amount of time (in seconds) to wait for a write operation to complete (in terms of a network socket; i.e. POSTing a request or uploading a file)
  • connect_timeout specifies the maximum amount of time (in seconds) to wait for a connection attempt to a Telegram server
  • pool_timeout specifies the maximum amount of time (in seconds) to wait for a connection to become available from the connection pool

The built-inrequest.HTTPXRequest (which implementsBaseRequest) uses a default of 5 seconds for{read, write, connect}_timeout and 1 second forpool_timeout.

Thewrite_timeout is overwritten to 20 seconds when using send methods which attach files (send_audio,send_document, etc.).When sending big files, callingBot.send_*(write_timeout=BIGGER_VALUE) might be a good idea.

When using the standardHTTPXRequest, changing the defaults of{read, write, connect, pool}_timeout &connect_timeout is done when initializing theApplication.

Application.builder().token("Token").read_timeout(7).get_updates_read_timeout(42).build()

Note that there is bothApplicationBuilder.read_timeout() andApplicationBuilder.get_updates_read_timeout (and similarly for the other timeouts) since PTB uses two different request objects forBot.get_updates and all other bot methods.

See also the wiki page on thebuilder pattern.

Bot.get_updates

When usingApplication.run_polling()/Updater.start_polling(),getUpdates is achieved usingLong Polling.This means that theget_updates request is kept alive for a(Telegram defined) timeout of X seconds to respond with newUpdate(s).Only if updates are available before the X seconds have passed, the request is closed right away andget_updates is called again.This also means that if a network error occurs during that timeout, it will be discovered only after the timeout has passed.

To be specific, when using the raw API (i.e. usingBot directly), the value you pass fortimeout is added to the value ofread_timeout and that is the exact timing when the error will be detected.In that mode, the default value oftimeout is 0 and the default value ofread_timeout is 2.

If you're usingUpdater.start_polling/Application.run_polling() then the default value oftimeout is overridden to 10. That means that the average time to identify network error is 6 seconds.

Depending on the SLA you'd like to provide, if you suffer from frequent errors duringgetUpdates consider lowering thetimeout value to catch the errors faster.Please take in mind that too short polling intervals may have undesirable side effects:

  • Telegram servers might conceive it as abusive and block your bot.
  • Increase the load on your server and network connection.

Socket options

Depending on your OS you may be able to set socket options to perform low level tweaks.In the default networking backend,HTTPXRequest, there is a corresponding parameter for this.

Stabilizing your app

When a network error occurs, be prepared to catch theraised exception and handle it according to your policy (do you want to retry? ignore? other?) or use PTBs built-in mechanism forexception handling. Note that for (network) errors that happen as part ofApplication.run_polling/Updater.start_polling arealso processed viaApplication.process_error.

PTB

If you think of another way to improve stability from within ptb, please contact us (the maintainers).

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