Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

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
Luca Bellanti edited this pageFeb 18, 2024 ·20 revisions

Architecture

Thetelegram andtelegram.ext packages contain several classes that make writing (chat)bots easy.You have met most of them in thetutorial.Because all of that can be a bit overwhelming, the below diagram gives you an overview of how the different components interact with each other.

flowchart TD;    AppBuilder("        ext.ApplicationBuilder        builder pattern for        ext.Application    ");    App("        ext.Application                • entry point for the whole application</li>        • provides convenience methods for running the whole app via run_polling/webhook()</li>        • administers handlers and error handlers</li>        • administers user/chat/bot_data</li>    ");    BaseHandler("        ext.BaseHandler        specifies if and how        it handles updates    ");    BaseRequest("        request.BaseRequest        interface for handling the        networking backend    ");    BasePersistence("        ext.BasePersistence        interface for persisting        data from ext.Application        across restarts    ");    BaseUpdateProcessor("        ext.BaseUpdateProcessor        interface for processing        updates concurrently    ");    Bot("        (ext.Ext)Bot        Telegram Bot API client        used to make requests        to the API    ");    CallbackContext("        ext.CallbackContext        Convenience class for unified        access to different objects within        handler/job/error callbacks    ");        BaseRateLimiter("        ext.BaseRateLimiter        interface for rate limiting        API requests    ");        Defaults("        ext.Defaults        gathers default values for frequently        used parameters of (ext.Ext)Bot,        Ext.JobQueue and ext.BaseHandler    ");    CallbackDataCache("        ext.CallbackDataCache        in-memory LRU-cache for        arbitrary callback_data    ");    ContextTypes("        ext.ContextTypes        specifies types of        the context argument    ");    JobQueue("        ext.JobQueue        schedules tasks to run        at specific times    ");    Updater("        ext.Updater        fetches updates from Telegram        and puts them into the update_queue    ");        AppBuilder -- builds --> App;    App -- accesses to build context --> ContextTypes;    App -- "provides arguments for<br>handler callbacks, processes exceptions<br>raised in handler callbacks" --> BaseHandler;    App -- processes exceptions<br>raised in jobs --> JobQueue;    App -- fetches data<br>and passes it to<br>ext.BasePersistence --> CallbackDataCache;    App -- fetches updates from<br>the update_queue --> Updater;    App -- updates in<br>regular intervals --> BasePersistence;    App -- gets default values<br>for parameters --> Defaults;    App -- dispatches updates --> BaseUpdateProcessor;    BaseUpdateProcessor -- processes updates<br>in specified<br>concurrency scheme--> BaseHandler;    ContextTypes -- specifies types --> CallbackContext;    BasePersistence -- holds a reference --> Bot;    BaseRateLimiter -- rate limits requests<br>to the API --> BaseRequest;    Bot -- dispatches requests<br>to the API --> BaseRateLimiter;        Bot -- stores arbitrary<br>callback_data --> CallbackDataCache;    Bot -- gets default values<br>for parameters --> Defaults;    JobQueue -- accesses to<br>build context --> ContextTypes;    Updater -- calls get_updates<br>& set/delete_webhook --> Bot;
Loading

python-telegram-bot is designed such that you can adjust it to many use cases.In particular, many components/features are optional and some can even be fully customized.Moreover, the design allows the library to be used alongside otherasyncio frameworks in the same Python script. We have a dedicated section on this in theover here.

Fetching updates

TheUpdater class is there to fetch updates from the Bot API for your bot.But you don't need to use it.If you want to implement a custom mechanism to fetch updates (e.g. acustom webhook setup, you can just put your updates into theApplication.update_queue or even manually callApplication.process_update.To build anApplication that doesn't use anUpdater, simply passNone toApplicationBuilder.updater.

Concurrent update processing

By default, theApplication handles updates sequentially, i.e. one by one.However, you can also process updates concurrently, i.e. multiple updates at the same time.It is also possible to customize which updates should be processed concurrently and which should be processed sequentially by providing a custom implementation of theBaseUpdateProcessor interface class.Please have a look atthis wiki page for more info.

Scheduling tasks

TheJobQueue class integrates scheduling logic into the setup oftelegram.ext.This feature is optional.If you don't need/want to use aJobQueue, simply passNone toApplicationBuilder.job_queue.

Arbitrarycallback_data

TheCallbackDataCache is the backend for caching arbitrarycallback_data.This feature must be explicitly activated to be used.Please seethis wiki page for more info.

Default values

TheDefaults class allows you to specify default values for parameters that appear quite often, e.g. theparse_mode parameter.This is an opt-in feature.Please have a look atthis wiki page for more info.

Persisting data across restarts

By default, data likeApplication.{chat, bot, user}_data is stored in-memory and is lost when the bot shuts down.PTB includes an optional functionality to persist data across restarts, which hasBasePersistence as interface class at it's core.Head tothis page for more info.

Rate limiting

By default, all requests to the bot API, i.e. callingBot.send_message,Message.reply_text or any other API method, are immediately forwarded to Telegram.Since Telegram imposes rate limits, this can lead to flood errors if you're making to many requests in a short time span.PTB includes an optional functionality to "throttle" the outgoing requests, which hasBaseRateLimiter as interface class at it's core.Head tothis page for more info.

Networking

By default, PTB will use thehttpx library for the networking backend, i.e. making requests to the Bot API.However, you are free to use a custom backend implementation as well.For this, you'll have to implement theBaseRequest interface class and pass two instances of your custom networking class toApplicationBuilder.request andApplicationBuilder.get_updates_request.

Update handlers

TheHandler interface class is the most important class when it comes to the question of how theApplication processes updates.PTB comes with a number ofbuilt-in handler which cover most important use cases.However, if you want to implement a custom logic of when an update should be handled, you can also write a custom implementation ofHandler and use that.

Persistence

As mentioned above, PTBs persistence functionality is based on the interface classBasePersistence.To use persistence in PTB, you use an implementation of this class.PTB comes already ships two implementations (seethis page), but you are very welcome to implement a persistence class for your own serialization backend.

Customizing thecontext parameter

The classCallbackContext is a central part of the handler/job callbacks in PTB and more advanced users may want to add custom behavior to this class.You can do so by passing an instance of theContextTypes toApplicationBuilder.context_types.Have a look atthis example for example use cases.

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