nvd commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -17,8 +17,8 @@ BALE_CHAT_ID = '447422307'
|
|
| 17 |
MONGO_URI = 'mongodb+srv://test1:Kjs93&kh39@cluster0.tx7plhr.mongodb.net/?appName=Cluster0'
|
| 18 |
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 19 |
|
| 20 |
-
# Target Channels (
|
| 21 |
-
TARGET_CHANNELS = ['
|
| 22 |
|
| 23 |
# PGP Public Key
|
| 24 |
PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
|
|
@@ -99,56 +99,58 @@ def send_to_bale(text, show_keyboard=False):
|
|
| 99 |
}
|
| 100 |
try:
|
| 101 |
requests.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=8)
|
| 102 |
-
except
|
| 103 |
-
|
| 104 |
|
| 105 |
-
# --- TELEGRAM LISTENER ---
|
| 106 |
-
@tg_client.on(events.NewMessage
|
| 107 |
-
async def
|
| 108 |
try:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
print(f"π₯ MESSAGE RECEIVED from @{channel_name}")
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
# Save with a clean UTC timestamp
|
| 119 |
-
messages_collection.insert_one({
|
| 120 |
-
"channel": channel_name,
|
| 121 |
-
"encrypted_text": encrypted,
|
| 122 |
-
"timestamp": datetime.utcnow()
|
| 123 |
-
})
|
| 124 |
|
| 125 |
-
#
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
# --- BACKGROUND TASK ---
|
| 133 |
-
async def start_telegram():
|
| 134 |
-
print("Connecting to Telegram...")
|
| 135 |
-
try:
|
| 136 |
-
await tg_client.start()
|
| 137 |
-
print("β
TELEGRAM CONNECTED SUCCESSFULLY")
|
| 138 |
-
await tg_client.run_until_disconnected()
|
| 139 |
except Exception as e:
|
| 140 |
-
print(f"
|
| 141 |
|
| 142 |
# --- WEB SERVER ---
|
| 143 |
@asynccontextmanager
|
| 144 |
async def lifespan(app: FastAPI):
|
| 145 |
-
#
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
-
#
|
| 151 |
-
asyncio.create_task(
|
| 152 |
yield
|
| 153 |
await tg_client.disconnect()
|
| 154 |
|
|
@@ -156,7 +158,7 @@ app = FastAPI(lifespan=lifespan)
|
|
| 156 |
|
| 157 |
@app.get("/")
|
| 158 |
async def status():
|
| 159 |
-
return {"
|
| 160 |
|
| 161 |
@app.post("/bale-webhook")
|
| 162 |
async def bale_webhook(request: Request):
|
|
@@ -166,34 +168,25 @@ async def bale_webhook(request: Request):
|
|
| 166 |
command = data["message"]["text"]
|
| 167 |
now = datetime.utcnow()
|
| 168 |
|
| 169 |
-
print(f"πΉοΈ Bale Command: {command}")
|
| 170 |
-
|
| 171 |
if "Today" in command or command == "/start":
|
| 172 |
-
# Search from the start of today UTC
|
| 173 |
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 174 |
-
end = now + timedelta(hours=2)
|
| 175 |
elif "Yesterday" in command:
|
| 176 |
start = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 177 |
end = start + timedelta(days=1)
|
| 178 |
else:
|
| 179 |
return {"ok": True}
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
print(f"π Found {len(results)} messages.")
|
| 184 |
-
|
| 185 |
-
if len(results) == 0:
|
| 186 |
if command != "/start":
|
| 187 |
-
send_to_bale(encrypt_message("
|
| 188 |
-
else:
|
| 189 |
-
send_to_bale(encrypt_message("System Active. Waiting for new messages..."), show_keyboard=True)
|
| 190 |
else:
|
| 191 |
for msg in results:
|
| 192 |
send_to_bale(msg["encrypted_text"])
|
| 193 |
await asyncio.sleep(0.3)
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
print(f"β Webhook Error: {e}")
|
| 197 |
return {"ok": True}
|
| 198 |
|
| 199 |
if __name__ == "__main__":
|
|
|
|
| 17 |
MONGO_URI = 'mongodb+srv://test1:Kjs93&kh39@cluster0.tx7plhr.mongodb.net/?appName=Cluster0'
|
| 18 |
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 19 |
|
| 20 |
+
# Target Channels (Lowercase for matching)
|
| 21 |
+
TARGET_CHANNELS = ['iranintltv', 'vahidonline', 'indypersian', 'mamlekate']
|
| 22 |
|
| 23 |
# PGP Public Key
|
| 24 |
PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
|
|
|
|
| 99 |
}
|
| 100 |
try:
|
| 101 |
requests.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=8)
|
| 102 |
+
except:
|
| 103 |
+
pass
|
| 104 |
|
| 105 |
+
# --- IMPROVED TELEGRAM LISTENER ---
|
| 106 |
+
@tg_client.on(events.NewMessage) # Listen to EVERYTHING
|
| 107 |
+
async def broad_handler(event):
|
| 108 |
try:
|
| 109 |
+
# 1. Ignore private messages to the bot
|
| 110 |
+
if not event.is_channel and not event.is_group:
|
| 111 |
+
return
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
# 2. Get channel name
|
| 114 |
+
chat = await event.get_chat()
|
| 115 |
+
username = getattr(chat, 'username', '').lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
# 3. Log ALL incoming channel traffic to see what's happening
|
| 118 |
+
print(f"DEBUG: Message seen from channel: @{username}")
|
| 119 |
+
|
| 120 |
+
# 4. Filter for your target channels
|
| 121 |
+
if username in TARGET_CHANNELS:
|
| 122 |
+
print(f"π― MATCH! Capturing @{username}")
|
| 123 |
+
raw_text = event.raw_text
|
| 124 |
+
formatted_text = f"π’ Channel: @{username}\nβ° {datetime.now().strftime('%H:%M')}\n\n{raw_text}"
|
| 125 |
+
encrypted = encrypt_message(formatted_text)
|
| 126 |
+
|
| 127 |
+
messages_collection.insert_one({
|
| 128 |
+
"channel": username,
|
| 129 |
+
"encrypted_text": encrypted,
|
| 130 |
+
"timestamp": datetime.utcnow()
|
| 131 |
+
})
|
| 132 |
+
send_to_bale(encrypted, show_keyboard=True)
|
| 133 |
+
print("β
Processed and Sent.")
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
except Exception as e:
|
| 136 |
+
print(f"Error in Broad Handler: {e}")
|
| 137 |
|
| 138 |
# --- WEB SERVER ---
|
| 139 |
@asynccontextmanager
|
| 140 |
async def lifespan(app: FastAPI):
|
| 141 |
+
# Set Webhook
|
| 142 |
+
requests.get(f"{BALE_API_URL}/setWebhook?url=https://nvd13-test1.hf.space/bale-webhook")
|
| 143 |
+
|
| 144 |
+
# Connect Telegram
|
| 145 |
+
print("--- Starting Telegram ---")
|
| 146 |
+
await tg_client.connect()
|
| 147 |
+
if not await tg_client.is_user_authorized():
|
| 148 |
+
print("β SESSION EXPIRED OR INVALID. Please re-run login.py locally.")
|
| 149 |
+
else:
|
| 150 |
+
print("β
TELEGRAM AUTHENTICATED AND CONNECTED")
|
| 151 |
|
| 152 |
+
# Run in background
|
| 153 |
+
asyncio.create_task(tg_client.run_until_disconnected())
|
| 154 |
yield
|
| 155 |
await tg_client.disconnect()
|
| 156 |
|
|
|
|
| 158 |
|
| 159 |
@app.get("/")
|
| 160 |
async def status():
|
| 161 |
+
return {"tg_connected": tg_client.is_connected()}
|
| 162 |
|
| 163 |
@app.post("/bale-webhook")
|
| 164 |
async def bale_webhook(request: Request):
|
|
|
|
| 168 |
command = data["message"]["text"]
|
| 169 |
now = datetime.utcnow()
|
| 170 |
|
|
|
|
|
|
|
| 171 |
if "Today" in command or command == "/start":
|
|
|
|
| 172 |
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
| 173 |
+
end = now + timedelta(hours=2)
|
| 174 |
elif "Yesterday" in command:
|
| 175 |
start = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
|
| 176 |
end = start + timedelta(days=1)
|
| 177 |
else:
|
| 178 |
return {"ok": True}
|
| 179 |
|
| 180 |
+
results = list(messages_collection.find({"timestamp": {"$gte": start, "$lt": end}}).limit(50))
|
| 181 |
+
if not results:
|
|
|
|
|
|
|
|
|
|
| 182 |
if command != "/start":
|
| 183 |
+
send_to_bale(encrypt_message("Database is empty for this timeframe."))
|
|
|
|
|
|
|
| 184 |
else:
|
| 185 |
for msg in results:
|
| 186 |
send_to_bale(msg["encrypted_text"])
|
| 187 |
await asyncio.sleep(0.3)
|
| 188 |
+
except:
|
| 189 |
+
pass
|
|
|
|
| 190 |
return {"ok": True}
|
| 191 |
|
| 192 |
if __name__ == "__main__":
|