Creating a Custom Persistence Class for python-telegram-bot

I am in the process of building a basic Telegram bot utilizing the python-telegram-bot library. Presently, my bot employs the ConversationHandler to monitor the conversation’s state.

My goal is to enable conversation persistence by saving the conversation state to a MongoDB database.

To interact with my database, I am using the mongoengine library for Python.

Upon reviewing the documentation for BasePersistence, I discovered that I need to create a custom class, which I’ll refer to as MongoStorage, and override two specific methods:

  • fetch_conversations(user)
  • modify_conversation(user, identifier, updated_state)

However, the documentation does not clarify the format of the dict that fetch_conversations(user) returns, making it challenging to define modify_conversation(user, identifier, updated_state) effectively.

Here is the basic structure of the aforementioned class (with save_user_info, save_chat_info, and save_bot_info all set to False to avoid storing additional data):

from telegram.ext import BasePersistence


class MongoStorage(BasePersistence):

    def __init__(self):
        super(MongoStorage, self).__init__(save_user_info=False,
                                            save_chat_info=False,
                                            save_bot_info=False)

    def fetch_conversations(self, user):
        pass

    def modify_conversation(self, user, identifier, updated_state):
        pass

What would be the best way to implement this class to ensure my conversation state is correctly retrieved and stored in the database?

Try printing the output of fetch_conversations to see its strcture when just starting the bot. That’ll give you a hint. Also, look into JSON serialization since you might need it when dealing with MongoDB storage. Don’t forget to ensure thread safety if you’re gonna handle multiple conversations at once.