from fastapi import FastAPI, Request from fastapi.responses import JSONResponse import httpx from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes import os app = FastAPI() # Replace this with your Hugging Face Space URL HUGGING_FACE_SPACE_URL = "https://demaking-decision-helper-bot.hf.space" # Get Telegram bot token from environment variables TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") if not TOKEN: raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.") async def call_hugging_face_space(input_data: str): async with httpx.AsyncClient(timeout=45.0) as client: try: response = await client.post(HUGGING_FACE_SPACE_URL, json={"input": input_data}) response.raise_for_status() # Raise an error for bad responses return response.json() except httpx.HTTPStatusError as e: print(f"HTTP error occurred: {e}") return {"error": str(e)} except httpx.ConnectError as e: print(f"Connection error: {e}") return {"error": "Could not connect to the Hugging Face Space"} except Exception as e: print(f"An error occurred: {e}") return {"error": str(e)} @app.post("/webhook/{token}") async def webhook(token: str, request: Request): if token != TOKEN: return JSONResponse(status_code=403, content={"message": "Forbidden"}) update = Update.de_json(await request.json(), None) message_text = update.message.text result = await call_hugging_face_space(message_text) return JSONResponse(content=result) def start_telegram_bot(): application = ApplicationBuilder().token(TOKEN).build() # Set up a command handler async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.") print("Start command received.") async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): user_text = update.message.text print(f"User message: {user_text}") # Send the user text to the FastAPI server and get the response. result = await call_hugging_face_space(user_text) response_text = result.get("response", "Error generating response.") print(f"API Response: {response_text}") await update.message.reply_text(response_text) application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) # Start the bot application.run_polling() if __name__ == "__main__": import threading # Start the Telegram bot in a separate thread threading.Thread(target=start_telegram_bot).start() # Start the FastAPI app import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)