Create bot.py
Browse files
bot.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import httpx
|
3 |
+
import asyncio
|
4 |
+
import nest_asyncio
|
5 |
+
import os
|
6 |
+
|
7 |
+
from telegram import Update
|
8 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
9 |
+
|
10 |
+
|
11 |
+
# Logging setup
|
12 |
+
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
|
13 |
+
|
14 |
+
|
15 |
+
# Get environment variables
|
16 |
+
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
17 |
+
if not TOKEN:
|
18 |
+
raise ValueError("Missing Telegram token. Please set TELEGRAM_BOT_TOKEN in environment variables.")
|
19 |
+
|
20 |
+
# URL of the FastAPI server (running on Hugging Face)
|
21 |
+
API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
|
22 |
+
|
23 |
+
|
24 |
+
async def fetch_response(user_text: str):
|
25 |
+
async with httpx.AsyncClient(timeout=45.0) as client:
|
26 |
+
try:
|
27 |
+
response = await client.post(API_URL, json={"text": user_text})
|
28 |
+
response.raise_for_status() # throws exception if the API returns 4XX/5XX errors
|
29 |
+
return response.json()
|
30 |
+
except httpx.HTTPStatusError as e:
|
31 |
+
logging.error(f"HTTP Error: {e.response.status_code} - {e.response.text}")
|
32 |
+
return {"response": "Error: API returned an error."}
|
33 |
+
except httpx.RequestError as e:
|
34 |
+
logging.error(f"Request Error: {e}")
|
35 |
+
return {"response": "Error: Could not reach API."}
|
36 |
+
except Exception as e:
|
37 |
+
logging.error(f"Unexpected Error: {e}")
|
38 |
+
return {"response": "Error: Unexpected error occurred."}
|
39 |
+
|
40 |
+
|
41 |
+
async def handle_message(update: Update, context: CallbackContext):
|
42 |
+
user_text = update.message.text
|
43 |
+
logging.info(f"User message: {user_text}")
|
44 |
+
|
45 |
+
# Send request to HF API
|
46 |
+
result = await fetch_response(user_text)
|
47 |
+
response_text = result.get("response", "Error generating response.")
|
48 |
+
|
49 |
+
logging.info(f"API Response: {response_text}")
|
50 |
+
await update.message.reply_text(response_text)
|
51 |
+
|
52 |
+
|
53 |
+
async def start(update: Update, context: CallbackContext):
|
54 |
+
await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
|
55 |
+
logging.info("Start command received.")
|
56 |
+
|
57 |
+
nest_asyncio.apply()
|
58 |
+
|
59 |
+
|
60 |
+
async def main():
|
61 |
+
application = Application.builder().token(TOKEN).build()
|
62 |
+
|
63 |
+
# Handlers
|
64 |
+
application.add_handler(CommandHandler("start", start))
|
65 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
66 |
+
|
67 |
+
# Start polling
|
68 |
+
logging.info("Starting bot in polling mode...")
|
69 |
+
await application.initialize()
|
70 |
+
await application.run_polling()
|
71 |
+
|
72 |
+
|
73 |
+
if __name__ == "__main__":
|
74 |
+
asyncio.run(main())
|