DeMaking's picture
Create bot.py
ad4883e verified
raw
history blame
4.55 kB
import os
import logging
import asyncio
import nest_asyncio
import httpx
from telegram import Update
from telegram.ext import (
Application,
CommandHandler,
MessageHandler,
filters,
CallbackContext
)
# -------------------------
# Configure logging
# -------------------------
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
# -------------------------
# Environment variables
# -------------------------
# Get the Telegram Bot Token
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
if not TOKEN:
raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.")
# Get the domain for webhook (publicly accessible, e.g., your-space.hf.space)
WEBHOOK_DOMAIN = os.getenv("WEBHOOK_DOMAIN")
if not WEBHOOK_DOMAIN:
raise ValueError("Missing Webhook Domain. Please set WEBHOOK_DOMAIN environment variable.")
# -------------------------
# Webhook configuration
# -------------------------
# Define a unique webhook path using the bot token
WEBHOOK_PATH = f"/{TOKEN}"
# Construct the full webhook URL (must be HTTPS as required by Telegram)
WEBHOOK_URL = f"https://{WEBHOOK_DOMAIN}{WEBHOOK_PATH}"
# -------------------------
# API URL of the FastAPI server (running on Hugging Face)
# -------------------------
API_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
# -------------------------
# Function to fetch response from FastAPI (unchanged)
# -------------------------
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() # Raise exception for HTTP 4XX/5XX errors
return response.json()
except httpx.HTTPStatusError as e:
logger.error(f"HTTP Error: {e.response.status_code} - {e.response.text}")
return {"response": "Error: API returned an error."}
except httpx.RequestError as e:
logger.error(f"Request Error: {e}")
return {"response": "Error: Could not reach API."}
except Exception as e:
logger.error(f"Unexpected Error: {e}")
return {"response": "Error: Unexpected error occurred."}
# -------------------------
# Command handler for /start
# -------------------------
async def start(update: Update, context: CallbackContext):
# Respond to the /start command.
await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
logger.info("Start command received.")
# -------------------------
# Message handler for incoming text messages
# -------------------------
async def handle_message(update: Update, context: CallbackContext):
user_text = update.message.text
logger.info(f"User message: {user_text}")
# Send the user text to the FastAPI server and get the response.
result = await fetch_response(user_text)
response_text = result.get("response", "Error generating response.")
logger.info(f"API Response: {response_text}")
await update.message.reply_text(response_text)
# -------------------------
# Main function to run the bot using Webhook mode
# -------------------------
async def main():
# Build the Application with the Telegram Bot Token
application = Application.builder().token(TOKEN).build()
# Add command and message handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# Log: starting the bot in webhook mode.
logger.info("Starting bot in webhook mode...")
# Run the application using webhook mode.
# The bot will listen on all interfaces (0.0.0.0) at the specified port (5000 in this example).
# Make sure that the port you choose is allowed by your hosting environment.
await application.run_webhook(
listen="0.0.0.0", # Listen on all available interfaces
port=443, # Port to listen on
url_path=WEBHOOK_PATH, # The webhook path; here, we use the bot token
webhook_url=WEBHOOK_URL # The full webhook URL that Telegram will use to send updates
)
# -------------------------
# Run the main function
# -------------------------
if __name__ == "__main__":
# Apply nest_asyncio to support nested event loops if required.
nest_asyncio.apply()
asyncio.run(main())