import os import logging from telegram import Update from telegram.ext import…
- User
import os import logging from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters from dotenv import load_dotenv from gemma_model import ModelClient
Load environment variables from a .env file
load_dotenv()
model_client = ModelClient()
telegram_api_token = os.getenv('TELEGRAM_API_TOKEN')
Setup logging
logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO )
Dictionary to keep track of user histories
user_histories = {}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """ Handles the /start command. Initiates a conversation with the user. """ await update.message.reply_text('Hello! I am your chatbot. Start talking to me!')
async def clear_history(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """ Clears the chat history for the user who issued the /clear command. """ user_id = update.message.from_user.id user_histories.pop(user_id, None) await update.message.reply_text('Your history has been cleared!')
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE): """ Handles incoming messages and generates responses. """ try: user_id = update.message.from_user.id user_message = update.message.text history = user_histories.setdefault(user_id, []) sys_prompt = "Your system prompt here"
# Replace this with the actual model client implementation response = model_client.get_response(user_message, history, sys_prompt) history.append((user_message, response)) await update.message.reply_text(response) except Exception as e: await update.message.reply_text("An error occurred. Please try again.") logging.error(f"Error in chat handler: {e}")async def main(): """ Initializes the Telegram bot application. """ application = Application.builder().token(telegram_api_token).build()
application.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("clear", clear_history)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat)) # Run the bot until manually terminated await application.run_polling(stop_signals=None)if name == 'main': try: import asyncio
asyncio.run(main()) except (KeyboardInterrupt, SystemExit): logging.info("Bot shutdown gracefully") - Assistant
Your code is setting up a Telegram bot that responds to user messages using a model client. Here's an overview and some potential improvements or reminders for your code:
Overview
- Environment Variables: Using
dotenvto manage environment variables, which is great for keeping sensitive data like API tokens secure. - Async/Await Structure: The use of asynchronous functions (
async def) will allow the bot to handle messages more efficiently. - Logging: Proper logging is set up, which will help with debugging and monitoring the bot's activities.
- User History Management: Custom history for each user is maintained, allowing for context-aware responses.
Potential Improvements
-
Token Loading:
- The
telegram_api_tokenvariable seems to be commented out in your current code. Make sure to uncomment it or set it correctly to ensure the bot can authenticate with Telegram.
telegram_api_token = os.getenv('TELEGRAM_API_TOKEN') - The
-
Safety Checks:
- Error Handling: While there's a catch-all exception handler, consider handling specific exceptions where possible to provide more precise error messages.
- Security: Verify the environment variables are securely managed and not stored or logged in plaintext.
-
Response and System Prompt:
- Ensure the
sys_promptvariable content meets your application's goal. Customize it to fit how you want the model to behave. - It's essential to have a robust implementation of
get_responsein yourModelClient.
- Ensure the
-
Logging Enhancements:
- Enhance the logger by adding more detailed logs, like when a user starts a new conversation or when history is cleared, for better tracing.
-
Graceful Shutdown:
- Ensure any necessary cleanup in
main()or within thefinallyblock if you add more shutdown logic.
- Ensure any necessary cleanup in
-
Bot Scope:
- Ensure handlers deal with specific commands and messages. For instance, check commands don't handle more than intended.
Running the Bot
To run the bot successfully, ensure:
- The
TELEGRAM_API_TOKENis set in the environment. - The model client (
ModelClient) is properly implemented and accessible. - All necessary libraries (
python-telegram-bot,python-dotenv, etc.) are installed.
This setup is a solid starting point for a Telegram chatbot, allowing you to build more features upon it, such as database integration, more complex command handling, etc.
- Environment Variables: Using
- User
Traceback (most recent call last): File "C:\Users\crazy.conda\envs\autogen_env\lib\site-packages\telegram\ext_application.py", line 881, in __run raise exc File "C:\Users\crazy.conda\envs\autogen_env\lib\site-packages\telegram\ext_application.py", line 870, in __run loop.run_until_complete(self.initialize()) File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\base_events.py", line 625, in run_until_complete self._check_running() File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\base_events.py", line 584, in _check_running raise RuntimeError('This event loop is already running') RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\crazy.conda\envs\autogen_env\lib\site-packages\telegram\ext_application.py", line 890, in __run loop.run_until_complete(self.shutdown()) File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\base_events.py", line 625, in run_until_complete self._check_running() File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\base_events.py", line 584, in _check_running raise RuntimeError('This event loop is already running') RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Developing\Python\AutoGen\bot.py", line 79, in asyncio.run(main()) File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\base_events.py", line 649, in run_until_complete return future.result() File "C:\Developing\Python\AutoGen\bot.py", line 72, in main await application.run_polling(stop_signals=None) File "C:\Users\crazy.conda\envs\autogen_env\lib\site-packages\telegram\ext_application.py", line 694, in run_polling return self.__run( File "C:\Users\crazy.conda\envs\autogen_env\lib\site-packages\telegram\ext_application.py", line 895, in __run loop.close() File "C:\Users\crazy.conda\envs\autogen_env\lib\asyncio\proactor_events.py", line 681, in close raise RuntimeError("Cannot close a running event loop") RuntimeError: Cannot close a running event loop sys:1: RuntimeWarning: coroutine 'Application.shutdown' was never awaited sys:1: RuntimeWarning: coroutine 'Application.initialize' was never awaited
- Assistant
The error you're encountering,
RuntimeError: This event loop is already running, is a common issue when usingasyncioin an environment where an event loop is already active. This often happens in environments like Jupyter notebooks or certain IDEs that run an event loop for their interfaces.Here's how you can address this issue:
Solution: Use
asyncioMethods Appropriately-
Separate the Code into an Async Function When Needed: Instead of running
asyncio.run, which attempts to create and run a new event loop, manage the loop differently if it's already running. -
Check if the Event Loop is Already Running:
- You can check if an event loop is running and decide how to treat it based on your environment's capability.
Example Adjustment:
Instead of using
asyncio.run(main()), you might consider usingawaitdirectly through the event loop if it is already running:import asyncio if __name__ == '__main__': try: # If running in an environment where the loop is already running (like Jupyter), # ensure to use it directly if not asyncio.get_event_loop().is_running(): asyncio.run(main()) else: # For environments that have an already running loop asyncio.get_event_loop().create_task(main()) except (KeyboardInterrupt, SystemExit): logging.info("Bot shutdown gracefully")Breakdown of Steps:
- Check if the Loop is Running: This code checks whether the asyncio event loop is already running. If not, it uses
asyncio.run()to start an event loop and runmain(). - Use the Existing Loop: If the loop is running (common in interactive environments), it uses
create_task()to schedule themain()coroutine.
Additional Considerations:
- Interaction with IDEs: Make sure your IDE settings don't interfere with the asyncio loop. Some development environments have specific integration settings that should be adjusted for async code.
- Understand Your Environment: Knowing if your code runs in a script, Jupyter notebook, or a console will help determine the best method to initiate an asyncio event loop.
-