DeMaking commited on
Commit
cf1677b
·
verified ·
1 Parent(s): 1a7b925

Create bot.py

Browse files
Files changed (1) hide show
  1. bot.py +71 -0
bot.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import asyncio
4
+ import nest_asyncio
5
+ from telegram import Update
6
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
7
+
8
+ from utils import clean_text
9
+ from app import generate_response # Import the response generation function from app.py
10
+
11
+
12
+ # Configure logging
13
+ logging.basicConfig(
14
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
15
+ level=logging.INFO
16
+ )
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ # Get Telegram Bot token from environment variable
21
+ TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
22
+ if not TOKEN:
23
+ raise ValueError("No TELEGRAM_BOT_TOKEN found in environment variables!")
24
+
25
+
26
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
27
+ """
28
+ Handler for the /start command.
29
+ Replies with a welcome message.
30
+ """
31
+ if not update.message or not update.message.text:
32
+ return
33
+ await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
34
+ logger.info("Start command received.")
35
+
36
+
37
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
38
+ """
39
+ Handler for incoming messages.
40
+ Cleans the text, generates a response, and replies to the user.
41
+ """
42
+ try:
43
+ if not update.message or not update.message.text:
44
+ return
45
+ user_text = clean_text(update.message.text)
46
+ logger.info(f"User message: {user_text}")
47
+
48
+ # Generate response using the function from app.py
49
+ response = generate_response(user_text)
50
+ await update.message.reply_text(response)
51
+ except Exception as e:
52
+ logger.error(f"Error processing message: {e}")
53
+
54
+
55
+ def main():
56
+ """
57
+ Main function to start the Telegram bot in polling mode.
58
+ """
59
+ application = Application.builder().token(TOKEN).build()
60
+ application.add_handler(CommandHandler("start", start))
61
+ application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
62
+
63
+ # Start the bot using polling mode.
64
+ application.run_polling(allowed_updates=Update.ALL_TYPES)
65
+
66
+
67
+ if __name__ == '__main__':
68
+ # Apply nest_asyncio to support nested event loops in HF Spaces
69
+ nest_asyncio.apply()
70
+ # For HF Spaces, using run_polling() is simpler and less dependent on DNS/HTTPS issues.
71
+ main()