nvd commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -3,150 +3,98 @@ import asyncio
|
|
| 3 |
import httpx
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
from telethon import TelegramClient, events
|
|
|
|
| 6 |
import pgpy
|
| 7 |
from motor.motor_asyncio import AsyncIOMotorClient
|
| 8 |
from fastapi import FastAPI, Request
|
|
|
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
|
| 11 |
-
|
| 12 |
-
def get_env(name, required=True):
|
| 13 |
-
value = os.getenv(name)
|
| 14 |
-
if required and not value:
|
| 15 |
-
raise ValueError(f"CRITICAL ERROR: Environment Variable '{name}' is missing!")
|
| 16 |
-
return value
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
|
| 22 |
BALE_CHAT_ID = get_env("BALE_CHAT_ID")
|
| 23 |
MONGO_URI = get_env("MONGO_URI")
|
| 24 |
-
|
| 25 |
-
# Configurations
|
| 26 |
-
# Expected format in EV: channel1,channel2,channel3
|
| 27 |
TARGET_CHANNELS_RAW = get_env("TARGET_CHANNELS")
|
| 28 |
-
TARGET_CHANNELS = [c.strip().lower() for c in TARGET_CHANNELS_RAW.split(",")]
|
| 29 |
-
|
| 30 |
-
# Public Key (Paste the whole -----BEGIN...END block into the EV)
|
| 31 |
PUB_KEY_TEXT = get_env("PUB_KEY_TEXT")
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
#
|
| 37 |
db_client = AsyncIOMotorClient(MONGO_URI)
|
| 38 |
db = db_client['telegram_bale_db']
|
| 39 |
messages_collection = db['messages']
|
| 40 |
|
| 41 |
-
|
| 42 |
-
pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
# --- 3.
|
| 48 |
-
def
|
| 49 |
-
|
| 50 |
-
return str(pub_key.encrypt(msg))
|
| 51 |
-
|
| 52 |
-
async def send_to_bale_async(text, show_keyboard=False):
|
| 53 |
-
payload = {"chat_id": BALE_CHAT_ID, "text": text}
|
| 54 |
-
if show_keyboard:
|
| 55 |
-
payload["reply_markup"] = {
|
| 56 |
-
"keyboard": [[{"text": "Fetch Today"}], [{"text": "Fetch Yesterday"}]],
|
| 57 |
-
"resize_keyboard": True
|
| 58 |
-
}
|
| 59 |
async with httpx.AsyncClient() as client:
|
| 60 |
-
|
| 61 |
-
resp = await client.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=10)
|
| 62 |
-
return resp.json()
|
| 63 |
-
except Exception as e:
|
| 64 |
-
print(f"Bale Send Error: {e}")
|
| 65 |
|
| 66 |
-
# --- 4. TELEGRAM EVENT HANDLER ---
|
| 67 |
@tg_client.on(events.NewMessage)
|
| 68 |
-
async def
|
| 69 |
-
if
|
| 70 |
-
return
|
| 71 |
-
|
| 72 |
-
try:
|
| 73 |
chat = await event.get_chat()
|
| 74 |
username = getattr(chat, 'username', '').lower()
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
# Save to MongoDB
|
| 82 |
-
await messages_collection.insert_one({
|
| 83 |
-
"channel": username,
|
| 84 |
-
"encrypted_text": encrypted,
|
| 85 |
-
"timestamp": datetime.utcnow()
|
| 86 |
-
})
|
| 87 |
-
|
| 88 |
-
# Forward to Bale
|
| 89 |
-
await send_to_bale_async(encrypted, show_keyboard=True)
|
| 90 |
-
print(f"β
Forwarded and Encrypted: @{username}")
|
| 91 |
-
|
| 92 |
-
except Exception as e:
|
| 93 |
-
print(f"Handler Error: {e}")
|
| 94 |
|
| 95 |
-
# ---
|
| 96 |
@asynccontextmanager
|
| 97 |
async def lifespan(app: FastAPI):
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
# Start Telegram
|
| 106 |
-
await tg_client.start()
|
| 107 |
-
print("π App Started: Telegram Connected & Webhook Set")
|
| 108 |
-
|
| 109 |
-
# Run Telegram in the background
|
| 110 |
-
tg_task = asyncio.create_task(tg_client.run_until_disconnected())
|
| 111 |
-
|
| 112 |
yield
|
| 113 |
-
|
| 114 |
-
# Shutdown
|
| 115 |
-
tg_task.cancel()
|
| 116 |
await tg_client.disconnect()
|
| 117 |
|
| 118 |
app = FastAPI(lifespan=lifespan)
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
@app.post("/bale-webhook")
|
| 121 |
-
async def
|
| 122 |
-
|
| 123 |
-
if "message" in data and "text" in data["message"]:
|
| 124 |
-
command = data["message"]["text"]
|
| 125 |
-
now = datetime.utcnow()
|
| 126 |
-
|
| 127 |
-
# Date filtering logic
|
| 128 |
-
if "Today" in command or command == "/start":
|
| 129 |
-
start_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 130 |
-
end_date = now + timedelta(hours=2)
|
| 131 |
-
elif "Yesterday" in command:
|
| 132 |
-
start_date = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 133 |
-
end_date = start_date + timedelta(days=1)
|
| 134 |
-
else:
|
| 135 |
-
return {"ok": True}
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
}).sort("timestamp", 1).limit(20)
|
| 141 |
-
|
| 142 |
-
results = await cursor.to_list(length=20)
|
| 143 |
-
|
| 144 |
-
if not results:
|
| 145 |
-
if command != "/start":
|
| 146 |
-
await send_to_bale_async(encrypt_message("No messages found for this period."))
|
| 147 |
-
else:
|
| 148 |
-
for msg in results:
|
| 149 |
-
await send_to_bale_async(msg["encrypted_text"])
|
| 150 |
-
await asyncio.sleep(0.3) # Prevent rate limiting
|
| 151 |
-
|
| 152 |
-
return {"ok": True}
|
|
|
|
| 3 |
import httpx
|
| 4 |
from datetime import datetime, timedelta
|
| 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 |
+
print("--- π System Starting ---")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
print("--- π Lifespan Starting ---")
|
| 79 |
+
try:
|
| 80 |
+
await tg_client.start()
|
| 81 |
+
print("β
Telegram Connected")
|
| 82 |
+
asyncio.create_task(tg_client.run_until_disconnected())
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f"β Telegram Connection Failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
yield
|
|
|
|
|
|
|
|
|
|
| 86 |
await tg_client.disconnect()
|
| 87 |
|
| 88 |
app = FastAPI(lifespan=lifespan)
|
| 89 |
|
| 90 |
+
@app.get("/")
|
| 91 |
+
async def health():
|
| 92 |
+
return {"status": "running", "time": str(datetime.now())}
|
| 93 |
+
|
| 94 |
@app.post("/bale-webhook")
|
| 95 |
+
async def webhook(request: Request):
|
| 96 |
+
return {"ok": True}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
# Hugging Face MUST run on port 7860
|
| 100 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|