I’m working on a Telegram bot using the python-telegram-bot package. Right now, I’m using ConversationHandler to manage chat states. But I want to make these conversations last longer by saving their states in a MongoDB database.
I’m using mongoengine to talk to my database. I’ve been reading about BasePersistence and I think I need to make a new class called MongoPersistence that builds on it. I have to rewrite two methods:
get_conversations(name)
update_conversation(name, key, new_state)
But I’m not sure how these methods work or what they should return. Can anyone help me figure out how to set this up? Here’s what I’ve got so far:
from telegram.ext import BasePersistence
class MongoPersistence(BasePersistence):
def __init__(self):
super().__init__(store_user_data=False, store_chat_data=False, store_bot_data=False)
def get_conversations(self, name):
# What goes here?
def update_conversation(self, name, key, new_state):
# And here?
I don’t need to save user, chat, or bot data. I just want to keep the conversation states in MongoDB. Any ideas on how to make this work?
hey, i did this b4.
for get_conversations, fetch convo states from mongodb by name and return as a dict.
for update_conversation, update/insert the state for the convo using name and key.
hope it helps, lmk if u need more info.
I’ve implemented something similar in one of my projects. In my experience, for get_conversations, you’ll want to query your MongoDB collection for documents matching the conversation name, then convert these into a dictionary with the conversation keys as dictionary keys and the corresponding states as values.
For update_conversation, performing an upsert operation is key. This approach updates the conversation if an entry exists or creates a new record if it doesn’t. It’s also important to serialize your state objects correctly because MongoDB handles BSON rather than arbitrary Python objects. Incorporating error handling and caching can significantly improve the bot’s performance.
I’ve tackled this issue before. For get_conversations, query your MongoDB collection for documents with the given name. Return a dict where keys are conversation keys and values are their states.
For update_conversation, use an upsert operation. This updates existing entries or creates new ones if they don’t exist. Be sure to properly serialize your state objects for MongoDB storage.
Consider implementing some form of caching to reduce database calls and improve performance. Also, don’t forget to handle potential database errors to ensure your bot remains stable.
Remember to close your database connections properly to avoid resource leaks. Good luck with your implementation!