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

Avoiding flood limits

Bibo-Joshi edited this pageNov 25, 2024 ·21 revisions

Flood Limits & Why to Avoid Them

ConsideringTelegram's Bot documentation, currently the maximum amount of messages being sent by bots is limited to ~30 messages/second for all ordinary messages and ~20 messages/minute for group messages.According to@BotSupport the limit for group also applies to channels (this is not confirmed by Telegram in their documentation however).We emphasize that Telegram doesnot document the precise limits, neither for sending messages nor for other kinds of API requests.Moreover, the limits may differ between bots and also over time.

When your bot hits spam limits, it starts to getRetryAfter errors from Telegram API.If you want to make sure that the message is actually sent and hence just try again on everyRetryAfter error, your code would spend a significant amount resources just on those retries.Moreover, constantly retrying to send messages while ignoring API errors could result in your bot being banned for some time.

That means, if you're making a production-ready bot that is expected to have a large number of users, it's a good idea to use throughput limiting mechanism for messages being sent/requests being made to the Bot API.This way you can ensure that all messages would be delivered to end-users as soon as possible in ordered way.

Tip

WithBot API 7.1 (PTB v27.1), Telegram introduced the parameterallow_paid_broadcast.This allows bots to send up to 1000 messages per second by paying a fee in Telegram Stars.

Caution

PTBs rate limiting mechanism doesn't takeallow_paid_broadcast into account automatically.If you want to use that parameter, make sure to implement the corresponding logic, so that the effect doesn't get lost.

PTBs Rate Limiting Mechanism

Since v20 (v20.0a3, to be precise), PTB comes with a built-in mechanism to throttle the number of API requests that your bot makes per time interval.This mechanism is exposed through thetelegram.ext.BaseRateLimiter interface class.This class has basically one important abstract coroutine method, calledBaseRateLimiter.process_request.This method is called every time when your bot makes an API request and it's purpose is to delay the request such that your bot doesn't hit the rate limits.Any implementation ofBaseRateLimiter can implement its own logic on how this should be done.If you observe a particular pattern in how your bot receivesRetryAfter errors (e.g. messages to one particular group triggerRetryAfter errors quickly), you can implement a logic that addresses these specific patterns.

TheBaseRateLimiter setup can be used only withtelegram.ext.ExtBot, not withtelegram.Bot.It's easy to set up and use.Assume thatMyLimiter implementsBaseRateLimiter.Then we use like this:

fromtelegramimportUpdatefromtelegram.extimportApplicationBuilder,ContextTypes,CommandHandlerapplication=ApplicationBuilder().token("TOKEN").rate_limiter(MyLimiter()).build()asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE):# This is automatically passed through `MyLimiter.process_request`!awaitupdate.message.reply_text(text="Hello World!")application.add_handler(CommandHandler('start',start))

You may also pass additional information toMyLimiter.process_request.Imagine that you want to broadcast a message to all the users of your bot.You might want to give those messages a lower priority, answering requests of your users should be faster.This could look like this:

importasynciofromtelegramimportUpdatefromtelegram.extimportApplicationBuilder,ContextTypes,CommandHandlerapplication=ApplicationBuilder().token("TOKEN").rate_limiter(MyLimiter()).build()user_ids= [1,2,3]asyncdefbroadcast(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitupdate.message.reply_text(text="Starting the broadcast...")context.application.create_task(asyncio.gather(*(context.bot.send_message(chat_id=user_id,text="Hello World!",rate_limit_args={'priority':-1}                )foruser_idinuser_ids            )        )    )application.add_handler(CommandHandler('broadcast',broadcast))

What kind of input is allowed for therate_limit_args argument is up to the implementation ofBaseRateLimiter.

Built-in Rate Limiter

PTB comes with a built-in implementation ofBaseRatelimiter: The classtelegram.ext.AIORateLimiter uses the libraryaiolimiter.Please consult the documentation ofAIORateLimiter for details on how it applies rate limits to API requests and how it should be used.

⚠️ We emphasize thatAIORateLimiter is to be understood as minimal effort reference implementation.If you would like to handle rate limiting in a more sophisticated, fine-tuned way, wewelcome you to implement your own subclass oftelegram.ext.BaseRateLimiter.Feel free to check out thesource code ofAIORateLimiter class for inspiration.

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