File size: 2,291 Bytes
cf1677b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import logging
import asyncio
import nest_asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

from utils import clean_text
from app import generate_response  # Import the response generation function from app.py


# Configure logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
logger = logging.getLogger(__name__)


# Get Telegram Bot token from environment variable
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
if not TOKEN:
    raise ValueError("No TELEGRAM_BOT_TOKEN found in environment variables!")


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """
    Handler for the /start command.
    Replies with a welcome message.
    """
    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.")


async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """
    Handler for incoming messages.
    Cleans the text, generates a response, and replies to the user.
    """
    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}")

        # Generate response using the function from app.py
        response = generate_response(user_text)
        await update.message.reply_text(response)
    except Exception as e:
        logger.error(f"Error processing message: {e}")


def main():
    """
    Main function to start the Telegram bot in polling mode.
    """
    application = Application.builder().token(TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))

    # Start the bot using polling mode.
    application.run_polling(allowed_updates=Update.ALL_TYPES)


if __name__ == '__main__':
    # Apply nest_asyncio to support nested event loops in HF Spaces
    nest_asyncio.apply()
    # For HF Spaces, using run_polling() is simpler and less dependent on DNS/HTTPS issues.
    main()