File size: 2,527 Bytes
ad117a3 |
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 73 74 75 |
import logging
import httpx
import asyncio
import nest_asyncio
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
# Logging setup
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
# Get environment variables
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
if not TOKEN:
raise ValueError("Missing Telegram token. Please set TELEGRAM_BOT_TOKEN in environment variables.")
# URL of the FastAPI server (running on Hugging Face)
API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
async def fetch_response(user_text: str):
async with httpx.AsyncClient(timeout=45.0) as client:
try:
response = await client.post(API_URL, json={"text": user_text})
response.raise_for_status() # throws exception if the API returns 4XX/5XX errors
return response.json()
except httpx.HTTPStatusError as e:
logging.error(f"HTTP Error: {e.response.status_code} - {e.response.text}")
return {"response": "Error: API returned an error."}
except httpx.RequestError as e:
logging.error(f"Request Error: {e}")
return {"response": "Error: Could not reach API."}
except Exception as e:
logging.error(f"Unexpected Error: {e}")
return {"response": "Error: Unexpected error occurred."}
async def handle_message(update: Update, context: CallbackContext):
user_text = update.message.text
logging.info(f"User message: {user_text}")
# Send request to HF API
result = await fetch_response(user_text)
response_text = result.get("response", "Error generating response.")
logging.info(f"API Response: {response_text}")
await update.message.reply_text(response_text)
async def start(update: Update, context: CallbackContext):
await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
logging.info("Start command received.")
nest_asyncio.apply()
async def main():
application = Application.builder().token(TOKEN).build()
# Handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# Start polling
logging.info("Starting bot in polling mode...")
await application.initialize()
await application.run_polling()
if __name__ == "__main__":
asyncio.run(main())
|