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

Making your bot persistent

Harshil edited this pageDec 15, 2023 ·43 revisions

In V12.0b1 we added a persistence mechanism totelegram.ext. This wiki page is there to help you understand and set up persistence for your bots.

What can become persistent?

  • The persistence structure is designed to make

    • bot_data
    • chat_data
    • user_data,
    • ConversationHandler's states and
    • ExtBot.callback_data_cache persistent.
  • Job's and thejob_queue is not supported.However, the currentJobQueue backendAPScheduler has its own persistence logic that you can leverage.See e.g.ptbcontrib/ptb_jobstores

  • For a special note aboutBot instances, seebelow

Included persistence classes

Three classes concerning persistence in bots have been added.

  • BasePersistence - Is an interface class for persistence classes.If you create your own persistence classes to maintain a database-connection for example, you must inherit fromBasePersistence and implement all abstract methods
  • PicklePersistence - Uses pickle files to make the bot persistent.
  • DictPersistence - Uses in memory dicts and easy conversion to and from JSON to make the bot persistent.Note that this class is mainly intended as starting point for custom persistence classes that need to JSON-serialize the stored data before writing them to file/database and doesnot actually write any data to file/database.

3rd party persistence classes

Instead of manually handling a database to store data, consider implementing a subclass ofBasePersistence. This allows you to simply pass an instance of that subclass to theApplication and let PTB handle the loading, updating & storing of the data!

If you want to create your own persistence class, please carefully read the docs onBasePersistence. It will tell you what methods you need to overwrite.

If you've written a persistence class that could benefit others (e.g., a general one covering all types of data), it would be great if you linked it here or even better made it available inptbcontrib.

These 3rd party packages contain persistence classes (the list is incomplete):

What do I need to change?

To make your bot persistent you need to do the following.

  • Create a persistence object (e.g.my_persistence = PicklePersistence(filepath='my_file'))
  • ConstructApplication with the persistence (Application.builder().token('TOKEN').persistence(persistence=my_persistence).build()).

This is enough to makeuser_data,bot_data,chat_data andExtBot.callback_data_cache persistent.To make a conversation handler persistent (save states between bot restarts) youmust name it and setpersistent toTrue.For exampleConversationHandler(..., persistent=True, name='my_name').persistent isFalse by default.Adding these arguments and adding the conversation handler to a persistence-awareApplication will make it persistent.

When starting theApplication withApplication.start() orApplication.run_{polling, webhook}, it will loads the data from the persistence on startup and automatically update the persistence in regular intervals.You can customize the interval via theupdate_interval argument ofBase/Pickle/Dict/…Persistence.

You can also selectively store only some of{bot,chat,user,callback}_data by passing aPersistenceInput to thestore_data argument your persistence class.

Note

Since the persisted data is loaded on start-up, any data written toApplication.{bot, chat, user_data}before startup will hence be overridden! To manually write data into theseafter the persisted data has been loaded, please useApplication.post_init.

Refreshing at runtime

If your persistence reads the data from an external database, the entries in this database could change at runtime.This is the case in particular, if the entries in the database are created by a 3rd party service independently of your bot.If you want to make sure that the data incontext.user/chat/bot_data are always up-to-date, your persistence class should implement the methodsrefresh_bot/chat/user_data.Those will be called when in update comes in, before any of your callbacks are called.

These methods can also be useful to implement a lazy-loading strategy.

Storing Bots

Instances oftelegram.Bot should not be serialized, because changes to the bot don't apply to the serialized object.

For example, you might change thedefault values used by the bot.Or if you change the bots token, this may lead to e.g.Chat not found errors.This is relevant e.g., if you store Telegram objects likeMessage inbot/user/chat_data, as some of them hold a reference toApplication.bot (which is how the shortcuts likeMessage.reply_text work).

The interface classBasePersistence does not question what kind of data you supply to its methods.Hence, each implementation should take care that it does not try to serializetelegram.Bot instances.For example, it can check if the data equals the attributeBasePersistence.bot (which will be the bot object used by theApplication) and instead store a placeholder.When loading the data, theBasePersistence.bot can be reinserted instead of the placeholder.Indeed, this is basically what the built-inPicklePersistence does.

For more technical details, please refer to the documentation ofBasePersistence,PicklePersistence

Note

AlthoughPicklePersistence does the 'placeholder' process described above, all the data are deep copied withcopy.deepcopy before being handed over to persistence. This means that you should either store only copyable data (e.g. notelegram.Bot objects) and/or ensure that your stored data defines appropriate custom deepcopy behavior. This technical detail is described in a notehere

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