Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
HuggingFace Spaces Entry Point for Jade Bot
|
| 3 |
-
Uses IP address directly to bypass DNS issues
|
| 4 |
"""
|
| 5 |
import os
|
| 6 |
import socket
|
|
@@ -14,30 +13,16 @@ from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, Messa
|
|
| 14 |
import uvicorn
|
| 15 |
import gradio as gr
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
TELEGRAM_IPS = ["149.154.167.220", "149.154.167.198", "149.154.167.199"]
|
| 20 |
|
| 21 |
-
def
|
| 22 |
-
""
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
def patched_init(self, *args, **kwargs):
|
| 26 |
-
# Add transport that maps api.telegram.org to IP
|
| 27 |
-
original_init(self, *args, **kwargs)
|
| 28 |
-
|
| 29 |
-
# Simple DNS override
|
| 30 |
-
original_getaddrinfo = socket.getaddrinfo
|
| 31 |
-
def custom_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
|
| 32 |
-
if "telegram" in str(host).lower():
|
| 33 |
-
# Return the first Telegram IP
|
| 34 |
-
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (TELEGRAM_IPS[0], port if port else 443))]
|
| 35 |
-
# Force IPv4 for everything else
|
| 36 |
-
return original_getaddrinfo(host, port, socket.AF_INET, type, proto, flags)
|
| 37 |
-
|
| 38 |
-
socket.getaddrinfo = custom_getaddrinfo
|
| 39 |
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
| 43 |
logger = logging.getLogger(__name__)
|
|
@@ -45,6 +30,8 @@ logger = logging.getLogger(__name__)
|
|
| 45 |
bot_status = {"started_at": None, "is_running": False, "error": None}
|
| 46 |
application = None
|
| 47 |
|
|
|
|
|
|
|
| 48 |
|
| 49 |
def get_status():
|
| 50 |
if bot_status.get("error"):
|
|
@@ -54,9 +41,6 @@ def get_status():
|
|
| 54 |
return f"## 🟢 Jade Running!\n- Started: {bot_status.get('started_at')}"
|
| 55 |
|
| 56 |
|
| 57 |
-
app = FastAPI()
|
| 58 |
-
|
| 59 |
-
|
| 60 |
@app.post("/webhook")
|
| 61 |
async def webhook(request: Request):
|
| 62 |
global application
|
|
@@ -86,7 +70,9 @@ async def setup_bot():
|
|
| 86 |
return
|
| 87 |
|
| 88 |
logger.info(f"Space URL: {space_url}")
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
try:
|
| 92 |
from core import TelegramJadeAgent
|
|
@@ -105,26 +91,49 @@ async def setup_bot():
|
|
| 105 |
response = await loop.run_in_executor(None, agent.chat, chat_id, user_text)
|
| 106 |
await context.bot.send_message(chat_id=chat_id, text=response)
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
application.add_handler(CommandHandler('start', start))
|
| 110 |
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))
|
| 111 |
|
| 112 |
-
await application.initialize()
|
| 113 |
-
|
| 114 |
webhook_url = f"{space_url}/webhook"
|
|
|
|
| 115 |
for attempt in range(5):
|
| 116 |
try:
|
| 117 |
-
logger.info(f"
|
| 118 |
-
await application.
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
bot_status["started_at"] = datetime.now().strftime("%H:%M:%S")
|
| 121 |
bot_status["is_running"] = True
|
| 122 |
return
|
|
|
|
| 123 |
except Exception as e:
|
| 124 |
logger.warning(f"Attempt {attempt + 1} failed: {e}")
|
| 125 |
-
|
|
|
|
| 126 |
|
| 127 |
-
bot_status["error"] = "Failed
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
logger.error(f"Bot setup failed: {e}")
|
|
|
|
| 1 |
"""
|
| 2 |
HuggingFace Spaces Entry Point for Jade Bot
|
|
|
|
| 3 |
"""
|
| 4 |
import os
|
| 5 |
import socket
|
|
|
|
| 13 |
import uvicorn
|
| 14 |
import gradio as gr
|
| 15 |
|
| 16 |
+
# Direct IP for Telegram API
|
| 17 |
+
TELEGRAM_IP = "149.154.167.220"
|
|
|
|
| 18 |
|
| 19 |
+
def custom_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
|
| 20 |
+
if "telegram" in str(host).lower():
|
| 21 |
+
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (TELEGRAM_IP, port if port else 443))]
|
| 22 |
+
return socket._original_getaddrinfo(host, port, socket.AF_INET, type, proto, flags)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
socket._original_getaddrinfo = socket.getaddrinfo
|
| 25 |
+
socket.getaddrinfo = custom_getaddrinfo
|
| 26 |
|
| 27 |
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
| 28 |
logger = logging.getLogger(__name__)
|
|
|
|
| 30 |
bot_status = {"started_at": None, "is_running": False, "error": None}
|
| 31 |
application = None
|
| 32 |
|
| 33 |
+
app = FastAPI()
|
| 34 |
+
|
| 35 |
|
| 36 |
def get_status():
|
| 37 |
if bot_status.get("error"):
|
|
|
|
| 41 |
return f"## 🟢 Jade Running!\n- Started: {bot_status.get('started_at')}"
|
| 42 |
|
| 43 |
|
|
|
|
|
|
|
|
|
|
| 44 |
@app.post("/webhook")
|
| 45 |
async def webhook(request: Request):
|
| 46 |
global application
|
|
|
|
| 70 |
return
|
| 71 |
|
| 72 |
logger.info(f"Space URL: {space_url}")
|
| 73 |
+
|
| 74 |
+
# Wait for network
|
| 75 |
+
await asyncio.sleep(3)
|
| 76 |
|
| 77 |
try:
|
| 78 |
from core import TelegramJadeAgent
|
|
|
|
| 91 |
response = await loop.run_in_executor(None, agent.chat, chat_id, user_text)
|
| 92 |
await context.bot.send_message(chat_id=chat_id, text=response)
|
| 93 |
|
| 94 |
+
# Build with extended timeouts
|
| 95 |
+
from telegram.ext import Defaults
|
| 96 |
+
from telegram.request import HTTPXRequest
|
| 97 |
+
|
| 98 |
+
request = HTTPXRequest(
|
| 99 |
+
connection_pool_size=8,
|
| 100 |
+
read_timeout=30,
|
| 101 |
+
write_timeout=30,
|
| 102 |
+
connect_timeout=30,
|
| 103 |
+
pool_timeout=30
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
application = (
|
| 107 |
+
ApplicationBuilder()
|
| 108 |
+
.token(token)
|
| 109 |
+
.request(request)
|
| 110 |
+
.get_updates_request(request)
|
| 111 |
+
.build()
|
| 112 |
+
)
|
| 113 |
application.add_handler(CommandHandler('start', start))
|
| 114 |
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))
|
| 115 |
|
|
|
|
|
|
|
| 116 |
webhook_url = f"{space_url}/webhook"
|
| 117 |
+
|
| 118 |
for attempt in range(5):
|
| 119 |
try:
|
| 120 |
+
logger.info(f"Attempt {attempt + 1}/5: Initializing...")
|
| 121 |
+
await application.initialize()
|
| 122 |
+
|
| 123 |
+
logger.info(f"Setting webhook to {webhook_url}...")
|
| 124 |
+
await application.bot.set_webhook(url=webhook_url, drop_pending_updates=True)
|
| 125 |
+
|
| 126 |
+
logger.info("✅ Webhook set successfully!")
|
| 127 |
bot_status["started_at"] = datetime.now().strftime("%H:%M:%S")
|
| 128 |
bot_status["is_running"] = True
|
| 129 |
return
|
| 130 |
+
|
| 131 |
except Exception as e:
|
| 132 |
logger.warning(f"Attempt {attempt + 1} failed: {e}")
|
| 133 |
+
if attempt < 4:
|
| 134 |
+
await asyncio.sleep(10)
|
| 135 |
|
| 136 |
+
bot_status["error"] = "Failed after 5 attempts"
|
| 137 |
|
| 138 |
except Exception as e:
|
| 139 |
logger.error(f"Bot setup failed: {e}")
|