File size: 3,631 Bytes
ad117a3 da3c213 97843ac 4db8adc 97843ac da3c213 ad117a3 78d577f ad117a3 da3c213 4d2cb62 da3c213 4d2cb62 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
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())
|