nvd commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,95 +1,58 @@
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
import httpx
|
| 4 |
-
from datetime import datetime
|
| 5 |
from telethon import TelegramClient, events
|
| 6 |
-
from telethon.sessions import StringSession
|
| 7 |
-
import pgpy
|
| 8 |
from motor.motor_asyncio import AsyncIOMotorClient
|
| 9 |
from fastapi import FastAPI, Request
|
| 10 |
import uvicorn
|
| 11 |
from contextlib import asynccontextmanager
|
| 12 |
|
| 13 |
-
|
| 14 |
|
| 15 |
-
# --- 1. SAFE ENV LOADING ---
|
| 16 |
-
def get_env(name):
|
| 17 |
-
val = os.getenv(name)
|
| 18 |
-
if not val:
|
| 19 |
-
print(f"❌ MISSING CONFIG: {name} is not set in Environment Variables")
|
| 20 |
-
return None
|
| 21 |
-
return val
|
| 22 |
-
|
| 23 |
-
TG_API_ID = get_env("TG_API_ID")
|
| 24 |
-
TG_API_HASH = get_env("TG_API_HASH")
|
| 25 |
-
BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
|
| 26 |
-
BALE_CHAT_ID = get_env("BALE_CHAT_ID")
|
| 27 |
-
MONGO_URI = get_env("MONGO_URI")
|
| 28 |
-
TARGET_CHANNELS_RAW = get_env("TARGET_CHANNELS")
|
| 29 |
-
PUB_KEY_TEXT = get_env("PUB_KEY_TEXT")
|
| 30 |
-
# For Telegram, we use a SESSION_STRING to avoid the phone login crash
|
| 31 |
-
TG_SESSION_STRING = os.getenv("TG_SESSION_STRING")
|
| 32 |
-
|
| 33 |
-
# --- 2. INITIALIZATION CHECK ---
|
| 34 |
-
if not all([TG_API_ID, TG_API_HASH, BALE_BOT_TOKEN, MONGO_URI, PUB_KEY_TEXT]):
|
| 35 |
-
print("FATAL: Critical variables missing. Check your Hugging Face Secrets.")
|
| 36 |
-
# We don't exit(1) immediately so we can see the logs
|
| 37 |
-
else:
|
| 38 |
-
print("✅ Environment Variables Loaded")
|
| 39 |
-
|
| 40 |
-
# Clients (Lazy init)
|
| 41 |
-
db_client = AsyncIOMotorClient(MONGO_URI)
|
| 42 |
-
db = db_client['telegram_bale_db']
|
| 43 |
-
messages_collection = db['messages']
|
| 44 |
-
|
| 45 |
-
try:
|
| 46 |
-
pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
|
| 47 |
-
print("✅ PGP Public Key Loaded")
|
| 48 |
-
except Exception as e:
|
| 49 |
-
print(f"❌ PGP Key Error: {e}")
|
| 50 |
-
|
| 51 |
-
# Telegram Client Setup
|
| 52 |
-
# If no SESSION_STRING is provided, it will use a local file (might fail on HF)
|
| 53 |
-
if TG_SESSION_STRING:
|
| 54 |
-
tg_client = TelegramClient(StringSession(TG_SESSION_STRING), int(TG_API_ID), TG_API_HASH)
|
| 55 |
-
else:
|
| 56 |
-
tg_client = TelegramClient('session_name', int(TG_API_ID), TG_API_HASH)
|
| 57 |
-
|
| 58 |
-
# --- 3. LOGIC ---
|
| 59 |
-
async def send_to_bale(text):
|
| 60 |
-
url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
|
| 61 |
-
async with httpx.AsyncClient() as client:
|
| 62 |
-
await client.post(url, json={"chat_id": BALE_CHAT_ID, "text": text})
|
| 63 |
-
|
| 64 |
-
@tg_client.on(events.NewMessage)
|
| 65 |
-
async def handler(event):
|
| 66 |
-
if event.is_channel:
|
| 67 |
-
chat = await event.get_chat()
|
| 68 |
-
username = getattr(chat, 'username', '').lower()
|
| 69 |
-
if username in [c.strip().lower() for c in TARGET_CHANNELS_RAW.split(",")]:
|
| 70 |
-
msg = pgpy.PGPMessage.new(f"📢 @{username}\n\n{event.raw_text}")
|
| 71 |
-
encrypted = str(pub_key.encrypt(msg))
|
| 72 |
-
await messages_collection.insert_one({"channel": username, "text": encrypted, "ts": datetime.utcnow()})
|
| 73 |
-
await send_to_bale(encrypted)
|
| 74 |
-
|
| 75 |
-
# --- 4. FASTAPI ---
|
| 76 |
@asynccontextmanager
|
| 77 |
async def lifespan(app: FastAPI):
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
| 85 |
yield
|
| 86 |
await tg_client.disconnect()
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
app = FastAPI(lifespan=lifespan)
|
| 89 |
|
| 90 |
@app.get("/")
|
| 91 |
async def health():
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
|
| 94 |
@app.post("/bale-webhook")
|
| 95 |
async def webhook(request: Request):
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
import httpx
|
| 4 |
+
from datetime import datetime
|
| 5 |
from telethon import TelegramClient, events
|
|
|
|
|
|
|
| 6 |
from motor.motor_asyncio import AsyncIOMotorClient
|
| 7 |
from fastapi import FastAPI, Request
|
| 8 |
import uvicorn
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
|
| 11 |
+
# ... (Keep your variable loading and encryption logic here) ...
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
@asynccontextmanager
|
| 14 |
async def lifespan(app: FastAPI):
|
| 15 |
+
# 1. Start Telegram in the BACKGROUND
|
| 16 |
+
# This prevents the app from getting "stuck" if Telegram fails
|
| 17 |
+
asyncio.create_task(start_telegram())
|
| 18 |
+
|
| 19 |
+
# 2. Set Webhook in the background
|
| 20 |
+
asyncio.create_task(setup_webhook())
|
| 21 |
+
|
| 22 |
+
print("🚀 Web server is up! Telegram is connecting in background...")
|
| 23 |
yield
|
| 24 |
await tg_client.disconnect()
|
| 25 |
|
| 26 |
+
async def start_telegram():
|
| 27 |
+
try:
|
| 28 |
+
# connect() does not ask for input, unlike start()
|
| 29 |
+
await tg_client.connect()
|
| 30 |
+
if not await tg_client.is_user_authorized():
|
| 31 |
+
print("❌ ERROR: Telegram session is not authorized. You need to login locally and upload the .session file again.")
|
| 32 |
+
return
|
| 33 |
+
|
| 34 |
+
print("✅ Telegram Connected and Authorized!")
|
| 35 |
+
await tg_client.run_until_disconnected()
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"❌ Telegram Background Error: {e}")
|
| 38 |
+
|
| 39 |
+
async def setup_webhook():
|
| 40 |
+
webhook_url = os.getenv("WEBHOOK_URL")
|
| 41 |
+
if webhook_url:
|
| 42 |
+
try:
|
| 43 |
+
async with httpx.AsyncClient() as client:
|
| 44 |
+
await client.get(f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/setWebhook?url={webhook_url}/bale-webhook")
|
| 45 |
+
print("✅ Bale Webhook Updated")
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"❌ Webhook Setup Error: {e}")
|
| 48 |
+
|
| 49 |
app = FastAPI(lifespan=lifespan)
|
| 50 |
|
| 51 |
@app.get("/")
|
| 52 |
async def health():
|
| 53 |
+
# If you see this in your browser, the app is "running"
|
| 54 |
+
return {"status": "online", "telegram_connected": tg_client.is_connected()}
|
| 55 |
+
|
| 56 |
|
| 57 |
@app.post("/bale-webhook")
|
| 58 |
async def webhook(request: Request):
|