DeMaking commited on
Commit
ad4883e
·
verified ·
1 Parent(s): 48917a9

Create bot.py

Browse files
Files changed (1) hide show
  1. bot.py +128 -0
bot.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import asyncio
4
+ import nest_asyncio
5
+ import httpx
6
+
7
+ from telegram import Update
8
+ from telegram.ext import (
9
+ Application,
10
+ CommandHandler,
11
+ MessageHandler,
12
+ filters,
13
+ CallbackContext
14
+ )
15
+
16
+ # -------------------------
17
+ # Configure logging
18
+ # -------------------------
19
+ logging.basicConfig(
20
+ format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
21
+ )
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # -------------------------
25
+ # Environment variables
26
+ # -------------------------
27
+ # Get the Telegram Bot Token
28
+ TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
29
+ if not TOKEN:
30
+ raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.")
31
+
32
+ # Get the domain for webhook (publicly accessible, e.g., your-space.hf.space)
33
+ WEBHOOK_DOMAIN = os.getenv("WEBHOOK_DOMAIN")
34
+ if not WEBHOOK_DOMAIN:
35
+ raise ValueError("Missing Webhook Domain. Please set WEBHOOK_DOMAIN environment variable.")
36
+
37
+
38
+ # -------------------------
39
+ # Webhook configuration
40
+ # -------------------------
41
+ # Define a unique webhook path using the bot token
42
+ WEBHOOK_PATH = f"/{TOKEN}"
43
+ # Construct the full webhook URL (must be HTTPS as required by Telegram)
44
+ WEBHOOK_URL = f"https://{WEBHOOK_DOMAIN}{WEBHOOK_PATH}"
45
+
46
+
47
+ # -------------------------
48
+ # API URL of the FastAPI server (running on Hugging Face)
49
+ # -------------------------
50
+ API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
51
+
52
+
53
+ # -------------------------
54
+ # Function to fetch response from FastAPI (unchanged)
55
+ # -------------------------
56
+ async def fetch_response(user_text: str):
57
+ async with httpx.AsyncClient(timeout=45.0) as client:
58
+ try:
59
+ response = await client.post(API_URL, json={"text": user_text})
60
+ response.raise_for_status() # Raise exception for HTTP 4XX/5XX errors
61
+ return response.json()
62
+ except httpx.HTTPStatusError as e:
63
+ logger.error(f"HTTP Error: {e.response.status_code} - {e.response.text}")
64
+ return {"response": "Error: API returned an error."}
65
+ except httpx.RequestError as e:
66
+ logger.error(f"Request Error: {e}")
67
+ return {"response": "Error: Could not reach API."}
68
+ except Exception as e:
69
+ logger.error(f"Unexpected Error: {e}")
70
+ return {"response": "Error: Unexpected error occurred."}
71
+
72
+
73
+ # -------------------------
74
+ # Command handler for /start
75
+ # -------------------------
76
+ async def start(update: Update, context: CallbackContext):
77
+ # Respond to the /start command.
78
+ await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
79
+ logger.info("Start command received.")
80
+
81
+
82
+ # -------------------------
83
+ # Message handler for incoming text messages
84
+ # -------------------------
85
+ async def handle_message(update: Update, context: CallbackContext):
86
+ user_text = update.message.text
87
+ logger.info(f"User message: {user_text}")
88
+
89
+ # Send the user text to the FastAPI server and get the response.
90
+ result = await fetch_response(user_text)
91
+ response_text = result.get("response", "Error generating response.")
92
+
93
+ logger.info(f"API Response: {response_text}")
94
+ await update.message.reply_text(response_text)
95
+
96
+
97
+ # -------------------------
98
+ # Main function to run the bot using Webhook mode
99
+ # -------------------------
100
+ async def main():
101
+ # Build the Application with the Telegram Bot Token
102
+ application = Application.builder().token(TOKEN).build()
103
+
104
+ # Add command and message handlers
105
+ application.add_handler(CommandHandler("start", start))
106
+ application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
107
+
108
+ # Log: starting the bot in webhook mode.
109
+ logger.info("Starting bot in webhook mode...")
110
+
111
+ # Run the application using webhook mode.
112
+ # The bot will listen on all interfaces (0.0.0.0) at the specified port (5000 in this example).
113
+ # Make sure that the port you choose is allowed by your hosting environment.
114
+ await application.run_webhook(
115
+ listen="0.0.0.0", # Listen on all available interfaces
116
+ port=443, # Port to listen on
117
+ url_path=WEBHOOK_PATH, # The webhook path; here, we use the bot token
118
+ webhook_url=WEBHOOK_URL # The full webhook URL that Telegram will use to send updates
119
+ )
120
+
121
+
122
+ # -------------------------
123
+ # Run the main function
124
+ # -------------------------
125
+ if __name__ == "__main__":
126
+ # Apply nest_asyncio to support nested event loops if required.
127
+ nest_asyncio.apply()
128
+ asyncio.run(main())