import logging from telegram import Update from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes from utils import clean_text from os import environ import httpx from app import generate_response, detect_language from responses import get_response # Configure logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # Get token from environment variable TOKEN = environ.get("TELEGRAM_BOT_TOKEN") if not TOKEN: raise ValueError("No TELEGRAM_BOT_TOKEN found in environment variables!") # ------------------------- # API URL of the FastAPI server (running on Hugging Face) # ------------------------- #API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response" # ------------------------- # Function to fetch response from FastAPI # ------------------------- # async def fetch_response(user_text: str): # """ # Sends a POST request to the FastAPI API with the user's text and returns the JSON response. # """ # async with httpx.AsyncClient(timeout=45.0) as client: # try: # response = await client.post(API_URL, json={"text": user_text}) # response.raise_for_status() # Raise exception for HTTP 4XX/5XX errors # return response.json() # except httpx.HTTPStatusError as e: # logger.error(f"HTTP Error: {e.response.status_code} - {e.response.text}") # return {"response": "Error: API returned an error."} # except httpx.RequestError as e: # logger.error(f"Request Error: {e}") # return {"response": "Error: Could not reach API."} # except Exception as e: # logger.error(f"Unexpected Error: {e}") # return {"response": "Error: Unexpected error occurred."} async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): """Handler for the /start command.""" if not update.message or not update.message.text: return await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.") logger.info("Start command received.") # ------------------------- # Message handler for incoming text messages # ------------------------- async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): """ Handler for incoming messages. Sends the user's message to the API and replies with the response. """ try: if not update.message or not update.message.text: return user_text = clean_text(update.message.text) logger.info(f"User message: {user_text}") response = generate_response(user_text) await update.message.reply_text(response) except Exception as e: logger.error(f"Error processing message: {e}") # Send the user text to the FastAPI server and get the response. # result = await fetch_response(user_text) # response_text = result.get("response", "Error generating response.") # logger.info(f"API Response: {response_text}") # await update.message.reply_text(response_text) # async def decide(update: Update, context: ContextTypes.DEFAULT_TYPE): # """Handle the /decide command.""" # if not context.args: # user_lang = detect_language(update.message.from_user.language_code) # await update.message.reply_text(get_response('decide_help', user_lang)) # return # question = ' '.join(context.args) # response = generate_response(question) # await update.message.reply_text(response) # async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): # """Handle regular messages.""" # if not update.message or not update.message.text: # return # text = clean_text(update.message.text) # if '?' in text: # response = generate_response(text) # else: # user_lang = detect_language(text) # response = get_response('no_question', user_lang) # await update.message.reply_text(response) # async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): # """Handle errors.""" # logger.error(f"Error occurred: {context.error}") # try: # if update and update.message: # user_lang = detect_language(update.message.from_user.language_code) # await update.message.reply_text( # get_response('error', user_lang) # ) # except Exception as e: # logger.error(f"Error in error handler: {e}") def main(): """Start the bot.""" # Create the application application = Application.builder().token(TOKEN).build() # Add handlers application.add_handler(CommandHandler("start", start)) # application.add_handler(CommandHandler("help", help_command)) # application.add_handler(CommandHandler("decide", decide)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) # Add error handler # application.add_error_handler(error_handler) # Start the bot application.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == '__main__': main()