Update app.py
Browse files
app.py
CHANGED
|
@@ -1,188 +1,57 @@
|
|
| 1 |
# app.py
|
|
|
|
| 2 |
import os
|
| 3 |
-
import
|
|
|
|
| 4 |
import sys
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
path_root = pathlib.Path(__file__).parents[0]
|
| 8 |
-
sys.path.append(str(path_root / "src"))
|
| 9 |
-
sys.path.append(str(path_root / "src/qwen_api"))
|
| 10 |
-
|
| 11 |
-
import logging
|
| 12 |
import asyncio
|
| 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 |
-
def load_data():
|
| 46 |
-
global dataDict
|
| 47 |
-
dataDict = load_obj("data") if load_obj("data") is not None else {}
|
| 48 |
-
dataDict.setdefault("lock", True)
|
| 49 |
-
dataDict.setdefault("users", set())
|
| 50 |
-
if "config" not in dataDict: # type: ignore
|
| 51 |
-
filename = os.path.join(os.path.dirname(__file__), 'config.json')
|
| 52 |
-
dataDict["config"] = load_json(filename)
|
| 53 |
-
|
| 54 |
-
def save_data():
|
| 55 |
-
global dataDict
|
| 56 |
-
save_obj(dataDict, "data")
|
| 57 |
-
|
| 58 |
-
# --- Command handlers (async) ---
|
| 59 |
-
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 60 |
-
user = update.effective_user
|
| 61 |
-
await update.message.reply_markdown_v2(fr'Hi {user.mention_markdown_v2()}\!')
|
| 62 |
-
|
| 63 |
-
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 64 |
-
await update.message.reply_text('Help!')
|
| 65 |
-
|
| 66 |
-
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 67 |
-
await update.message.reply_text(str(update.message.text))
|
| 68 |
-
|
| 69 |
-
async def qwen(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 70 |
-
"""Calling qwen."""
|
| 71 |
-
|
| 72 |
-
res, content = qwen_chat(str(update.message.text))
|
| 73 |
-
|
| 74 |
-
await update.message.reply_text(content)
|
| 75 |
-
|
| 76 |
-
async def wget_downloader(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 77 |
-
await update.message.reply_text("β wget not supported in webhook mode.")
|
| 78 |
-
|
| 79 |
-
async def ip(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 80 |
-
await update.message.reply_text(get_public_ip() + " (" + get_local_ip() + ")")
|
| 81 |
-
|
| 82 |
-
async def commands(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 83 |
-
for command in dataDict.get("config", {}).get("commands", []):
|
| 84 |
-
if not command.get("hide"):
|
| 85 |
-
await update.message.reply_text(command["name"])
|
| 86 |
-
|
| 87 |
-
async def lock(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 88 |
-
global dataDict
|
| 89 |
-
dataDict["lock"] = not dataDict["lock"]
|
| 90 |
-
save_data()
|
| 91 |
-
await update.message.reply_text(str(dataDict["lock"]))
|
| 92 |
-
|
| 93 |
-
async def downloader(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 94 |
-
await update.message.reply_text("π₯ File handling limited in webhook mode.")
|
| 95 |
|
| 96 |
-
async def command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 97 |
-
await update.message.reply_text("βοΈ Command execution disabled in webhook demo.")
|
| 98 |
-
|
| 99 |
-
# --- Security wrapper ---
|
| 100 |
-
def security_check(handler):
|
| 101 |
-
async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 102 |
-
user = update.effective_user
|
| 103 |
-
if user.id in dataDict.get("users", set()):
|
| 104 |
-
return await handler(update, context)
|
| 105 |
-
else:
|
| 106 |
-
await update.message.reply_text("π Access denied.")
|
| 107 |
-
return wrapper
|
| 108 |
-
|
| 109 |
-
# --- Lifespan: Initialize bot and set webhook ---
|
| 110 |
-
@asynccontextmanager
|
| 111 |
-
async def lifespan(app: FastAPI):
|
| 112 |
-
global bot_app
|
| 113 |
-
logger.info("Starting Telegram bot (webhook mode)...")
|
| 114 |
-
|
| 115 |
-
# Load persistent data
|
| 116 |
-
load_data()
|
| 117 |
-
|
| 118 |
-
# Initialize Telegram application
|
| 119 |
-
bot_app = Application.builder().token(TELEGRAM_TOKEN).build()
|
| 120 |
-
|
| 121 |
-
# Register handlers
|
| 122 |
-
bot_app.add_handler(CommandHandler("start", start))
|
| 123 |
-
bot_app.add_handler(CommandHandler("help", help_command))
|
| 124 |
-
bot_app.add_handler(CommandHandler("ip", security_check(ip)))
|
| 125 |
-
bot_app.add_handler(CommandHandler("commands", security_check(commands)))
|
| 126 |
-
bot_app.add_handler(CommandHandler("lock", security_check(lock)))
|
| 127 |
-
bot_app.add_handler(CommandHandler("wget", security_check(wget_downloader)))
|
| 128 |
-
bot_app.add_handler(CommandHandler("download", security_check(downloader)))
|
| 129 |
-
bot_app.add_handler(CommandHandler("command", security_check(command)))
|
| 130 |
-
bot_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, qwen))
|
| 131 |
-
bot_app.add_handler(MessageHandler(filters.Document.ALL, downloader))
|
| 132 |
-
|
| 133 |
-
# Initialize bot
|
| 134 |
-
await bot_app.initialize()
|
| 135 |
-
|
| 136 |
-
# Set webhook
|
| 137 |
-
if WEBHOOK_URL:
|
| 138 |
-
logger.info(f"Setting webhook to: {WEBHOOK_URL}")
|
| 139 |
-
await bot_app.bot.set_webhook(url=WEBHOOK_URL)
|
| 140 |
-
else:
|
| 141 |
-
logger.warning("WEBHOOK_URL not set β skipping webhook setup")
|
| 142 |
-
|
| 143 |
-
# Start the application (so it can process updates)
|
| 144 |
-
await bot_app.start()
|
| 145 |
-
|
| 146 |
-
yield # App is running
|
| 147 |
-
|
| 148 |
-
# Shutdown
|
| 149 |
-
logger.info("Shutting down Telegram bot...")
|
| 150 |
-
await bot_app.stop()
|
| 151 |
-
await bot_app.shutdown()
|
| 152 |
-
|
| 153 |
-
# --- FastAPI app ---
|
| 154 |
-
app = FastAPI(lifespan=lifespan)
|
| 155 |
-
|
| 156 |
-
@app.get("/")
|
| 157 |
-
async def root():
|
| 158 |
-
return {"status": "Telegram bot is running", "webhook_url": WEBHOOK_URL}
|
| 159 |
-
|
| 160 |
-
@app.post(WEBHOOK_PATH)
|
| 161 |
-
async def telegram_webhook(request: Request):
|
| 162 |
-
"""Receive Telegram updates via webhook."""
|
| 163 |
-
if bot_app is None:
|
| 164 |
-
return Response(status_code=503, content="Bot not ready")
|
| 165 |
-
|
| 166 |
-
# Parse update
|
| 167 |
-
update_data = await request.json()
|
| 168 |
-
update = Update.de_json(update_data, bot_app.bot)
|
| 169 |
-
|
| 170 |
-
# Put update into the bot's update queue for processing
|
| 171 |
-
await bot_app.update_queue.put(update)
|
| 172 |
-
|
| 173 |
-
return {"ok": True}
|
| 174 |
-
|
| 175 |
-
# --- Local dev server ---
|
| 176 |
if __name__ == "__main__":
|
| 177 |
-
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
|
|
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
)
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# test_internet.py
|
| 3 |
import os
|
| 4 |
+
import socket
|
| 5 |
+
import ssl
|
| 6 |
import sys
|
| 7 |
+
import urllib.request
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import asyncio
|
| 9 |
+
import httpx
|
| 10 |
+
|
| 11 |
+
def test_dns():
|
| 12 |
+
print("π Testing DNS resolution for api.telegram.org...")
|
| 13 |
+
try:
|
| 14 |
+
ip = socket.gethostbyname("api.telegram.org")
|
| 15 |
+
print(f"β
DNS OK: api.telegram.org -> {ip}")
|
| 16 |
+
return True
|
| 17 |
+
except Exception as e:
|
| 18 |
+
print(f"β DNS FAILED: {e}")
|
| 19 |
+
return False
|
| 20 |
+
|
| 21 |
+
def test_https_urllib():
|
| 22 |
+
print("\nπ Testing HTTPS access via urllib (Python stdlib)...")
|
| 23 |
+
try:
|
| 24 |
+
with urllib.request.urlopen("https://api.telegram.org", timeout=10) as response:
|
| 25 |
+
print(f"β
HTTPS OK: status {response.getcode()}")
|
| 26 |
+
return True
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print(f"β HTTPS FAILED (urllib): {e}")
|
| 29 |
+
return False
|
| 30 |
+
|
| 31 |
+
async def test_https_httpx():
|
| 32 |
+
print("\nπ Testing HTTPS access via httpx (used by python-telegram-bot)...")
|
| 33 |
+
try:
|
| 34 |
+
async with httpx.AsyncClient(timeout=10) as client:
|
| 35 |
+
resp = await client.get("https://api.telegram.org")
|
| 36 |
+
print(f"β
HTTPS OK (httpx): status {resp.status_code}")
|
| 37 |
+
return True
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"β HTTPS FAILED (httpx): {e}")
|
| 40 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
if __name__ == "__main__":
|
| 43 |
+
print("="*60)
|
| 44 |
+
print("π‘ Hugging Face Space: Internet Access Test for Telegram")
|
| 45 |
+
print("="*60)
|
| 46 |
|
| 47 |
+
dns_ok = test_dns()
|
| 48 |
+
urllib_ok = test_https_urllib() if dns_ok else False
|
| 49 |
+
httpx_ok = asyncio.run(test_https_httpx()) if dns_ok else False
|
| 50 |
|
| 51 |
+
print("\n" + "="*60)
|
| 52 |
+
if dns_ok and (urllib_ok or httpx_ok):
|
| 53 |
+
print("π SUCCESS: Outbound internet appears to work!")
|
| 54 |
+
else:
|
| 55 |
+
print("π FAILURE: Outbound internet is BLOCKED.")
|
| 56 |
+
print(" β Telegram bots will NOT work on this platform.")
|
| 57 |
+
print("="*60)
|