From 8b275597f5f324561d4c692f1ea46e555bd09f6d Mon Sep 17 00:00:00 2001 From: Mohammed Rabil Date: Sun, 5 May 2024 18:52:57 +0530 Subject: [PATCH] chore: Update MongoDB connection URL handling in bot.py --- README.md | 4 ++-- groq_chat/bot.py | 39 ++++++++++++++++++++++----------------- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index a501c9c..448eb8f 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ * Telegram Bot API token * Groq API Key * dotenv (for environment variables) - +* MongoDB (for storing chat history - optional) ### Docker @@ -62,7 +62,7 @@ docker run --env-file .env groq-chatbot 3. Create a `.env` file and add the following environment variables: * `BOT_TOKEN`: Your Telegram Bot API token. You can get one by talking to [@BotFather](https://t.me/BotFather). * `GROQ_API_KEY`: Your Groq API key. You can get one by signing up at [Groq Console](https://console.groq.com/keys). - * `MONGODB_URL`: Your MongoDB connection URL. Get one from [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). + * `MONGODB_URL`: Your MongoDB connection URL. Get one from [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). (optional) * `AUTHORIZED_USERS`: A comma-separated list of Telegram usernames or user IDs that are authorized to access the bot. (optional) Example value: `shonan23,1234567890` 4. Run the bot: * `python main.py` (if not using pipenv) diff --git a/groq_chat/bot.py b/groq_chat/bot.py index 1a84dcd..29a32f2 100644 --- a/groq_chat/bot.py +++ b/groq_chat/bot.py @@ -38,27 +38,32 @@ logger = logging.getLogger(__name__) -persistence = MongoPersistence( - mongo_url=os.getenv("MONGODB_URL"), - db_name="groq-chatbot", - name_col_user_data="user_data", - name_col_bot_data="bot_data", - name_col_chat_data="chat_data", - name_col_conversations_data="conversations_data", - create_col_if_not_exist=True, # optional - ignore_general_data=["cache"], - update_interval=10, -) +persistence = None +if os.getenv("MONGODB_URL"): + persistence = MongoPersistence( + mongo_url=os.getenv("MONGODB_URL"), + db_name="groq-chatbot", + name_col_user_data="user_data", + name_col_bot_data="bot_data", + name_col_chat_data="chat_data", + name_col_conversations_data="conversations_data", + create_col_if_not_exist=True, # optional + ignore_general_data=["cache"], + update_interval=10, + ) def start_bot(): logger.info("Starting bot") - app = ( - Application.builder() - .token(os.getenv("BOT_TOKEN")) - .persistence(persistence) - .build() - ) + + app_builder = Application.builder().token(os.getenv("BOT_TOKEN")) + + # Add persistence if available + if persistence: + app_builder.persistence = persistence + + # Build the app + app = app_builder.build() app.add_handler(CommandHandler("start", start, filters=AuthFilter)) app.add_handler(CommandHandler("help", help_command, filters=AuthFilter))