decision-helper-bot / new_bot.py
DeMaking's picture
Rename bot.py to new_bot.py
48917a9 verified
raw
history blame
3.63 kB
import logging
import httpx
import asyncio
import nest_asyncio
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
import subprocess # to remove
# import socket # maybe to remove
# maybe remove
# # Force using Google's DNS
# def set_dns():
# try:
# socket.setdefaulttimeout(5) # Set timeout for connections
# socket.getaddrinfo("api.telegram.org", 443, proto=socket.IPPROTO_TCP) # Force resolution
# print("DNS resolution successful!")
# except Exception as e:
# print(f"DNS resolution failed: {e}")
# set_dns()
# 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()
# to remove
async def test_telegram_connection():
try:
async with httpx.AsyncClient() as client:
response = await client.get("https://api.telegram.org")
print(f"Telegram API Status: {response.status_code}")
except Exception as e:
print(f"Error connecting to Telegram API: {e}")
asyncio.run(test_telegram_connection()) # to remove
# to remove
def check_dns():
try:
result = subprocess.run(["nslookup", "api.telegram.org"], capture_output=True, text=True)
print("DNS Lookup Result:\n", result.stdout)
except Exception as e:
print(f"Error running nslookup: {e}")
check_dns()
if __name__ == "__main__":
asyncio.run(main())