nvd commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
import sys
|
| 2 |
-
import types
|
| 3 |
import os
|
| 4 |
import asyncio
|
| 5 |
import requests
|
|
@@ -11,14 +9,17 @@ from fastapi import FastAPI, Request
|
|
| 11 |
from contextlib import asynccontextmanager
|
| 12 |
import uvicorn
|
| 13 |
|
| 14 |
-
# --- CONFIGURATION ---
|
| 15 |
-
TELEGRAM_API_ID = 35190771
|
| 16 |
TELEGRAM_API_HASH = 'a2bc0931f3ee06130ceab419802d5703'
|
| 17 |
BALE_BOT_TOKEN = '736303401:8hhKYE6A0Kg0O7rm_dBDWka8MHCS15aHBcE'
|
| 18 |
BALE_CHAT_ID = '447422307'
|
| 19 |
MONGO_URI = 'mongodb+srv://test1:Kjs93&kh39@cluster0.tx7plhr.mongodb.net/?appName=Cluster0'
|
| 20 |
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 21 |
|
|
|
|
|
|
|
|
|
|
| 22 |
# PGP Public Key
|
| 23 |
PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
|
| 24 |
Version: Mailvelope v6.2.1
|
|
@@ -77,98 +78,111 @@ H8KJTDlU8JXRiccVFnJITD2pXmrYh0ETyKfmfvKyClnZlYvWyj38p+/49+E5
|
|
| 77 |
=yiS/
|
| 78 |
-----END PGP PUBLIC KEY BLOCK-----"""
|
| 79 |
|
| 80 |
-
# --- INITIALIZE ---
|
| 81 |
-
db_client = MongoClient(MONGO_URI)
|
| 82 |
db = db_client['telegram_bale_db']
|
| 83 |
messages_collection = db['messages']
|
| 84 |
|
| 85 |
pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
|
| 86 |
-
|
| 87 |
-
# We initialize the client but don't start it yet
|
| 88 |
tg_client = TelegramClient('session_name', TELEGRAM_API_ID, TELEGRAM_API_HASH)
|
| 89 |
|
| 90 |
def encrypt_message(text):
|
| 91 |
msg = pgpy.PGPMessage.new(text)
|
| 92 |
-
|
| 93 |
-
return str(encrypted_msg)
|
| 94 |
|
| 95 |
def send_to_bale(text, show_keyboard=False):
|
| 96 |
payload = {"chat_id": BALE_CHAT_ID, "text": text}
|
| 97 |
if show_keyboard:
|
| 98 |
payload["reply_markup"] = {
|
| 99 |
-
"keyboard":[[{"text": "Fetch Today
|
| 100 |
"resize_keyboard": True
|
| 101 |
}
|
| 102 |
try:
|
| 103 |
-
requests.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=
|
| 104 |
-
except
|
| 105 |
-
|
| 106 |
|
| 107 |
-
# --- TELEGRAM
|
| 108 |
-
@tg_client.on(events.NewMessage(chats=
|
| 109 |
-
async def
|
| 110 |
try:
|
| 111 |
raw_text = event.raw_text
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
messages_collection.insert_one({
|
| 116 |
"channel": channel_name,
|
| 117 |
-
"encrypted_text":
|
| 118 |
"timestamp": datetime.utcnow()
|
| 119 |
})
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
-
print(f"
|
| 123 |
|
| 124 |
-
# ---
|
| 125 |
@asynccontextmanager
|
| 126 |
async def lifespan(app: FastAPI):
|
| 127 |
-
#
|
| 128 |
-
print("--- Server Starting ---")
|
| 129 |
-
|
| 130 |
-
# 1. Set Bale Webhook
|
| 131 |
webhook_url = "https://nvd13-test1.hf.space/bale-webhook"
|
| 132 |
requests.get(f"{BALE_API_URL}/setWebhook?url={webhook_url}")
|
| 133 |
-
print(f"Webhook set to: {webhook_url}")
|
| 134 |
-
|
| 135 |
-
# 2. Start Telegram Client in the background
|
| 136 |
-
await tg_client.start()
|
| 137 |
-
print("Telegram Client Connected!")
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
await tg_client.disconnect()
|
| 143 |
|
| 144 |
app = FastAPI(lifespan=lifespan)
|
| 145 |
|
| 146 |
@app.get("/")
|
| 147 |
-
def
|
| 148 |
-
return {"status": "
|
| 149 |
|
| 150 |
@app.post("/bale-webhook")
|
| 151 |
async def bale_webhook(request: Request):
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
return {"ok": True}
|
| 171 |
|
| 172 |
if __name__ == "__main__":
|
| 173 |
-
# Port 7860 is mandatory for Hugging Face
|
| 174 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
import requests
|
|
|
|
| 9 |
from contextlib import asynccontextmanager
|
| 10 |
import uvicorn
|
| 11 |
|
| 12 |
+
# --- CONFIGURATION (Integrated) ---
|
| 13 |
+
TELEGRAM_API_ID = 35190771
|
| 14 |
TELEGRAM_API_HASH = 'a2bc0931f3ee06130ceab419802d5703'
|
| 15 |
BALE_BOT_TOKEN = '736303401:8hhKYE6A0Kg0O7rm_dBDWka8MHCS15aHBcE'
|
| 16 |
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 = ['IranintlTV', 'vahidonline', 'Indypersian', 'mamlekate']
|
| 22 |
+
|
| 23 |
# PGP Public Key
|
| 24 |
PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
|
| 25 |
Version: Mailvelope v6.2.1
|
|
|
|
| 78 |
=yiS/
|
| 79 |
-----END PGP PUBLIC KEY BLOCK-----"""
|
| 80 |
|
| 81 |
+
# --- INITIALIZE SERVICES ---
|
| 82 |
+
db_client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
|
| 83 |
db = db_client['telegram_bale_db']
|
| 84 |
messages_collection = db['messages']
|
| 85 |
|
| 86 |
pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
|
|
|
|
|
|
|
| 87 |
tg_client = TelegramClient('session_name', TELEGRAM_API_ID, TELEGRAM_API_HASH)
|
| 88 |
|
| 89 |
def encrypt_message(text):
|
| 90 |
msg = pgpy.PGPMessage.new(text)
|
| 91 |
+
return str(pub_key.encrypt(msg))
|
|
|
|
| 92 |
|
| 93 |
def send_to_bale(text, show_keyboard=False):
|
| 94 |
payload = {"chat_id": BALE_CHAT_ID, "text": text}
|
| 95 |
if show_keyboard:
|
| 96 |
payload["reply_markup"] = {
|
| 97 |
+
"keyboard":[[{"text": "Fetch Today"}],[{"text": "Fetch Yesterday"}]],
|
| 98 |
"resize_keyboard": True
|
| 99 |
}
|
| 100 |
try:
|
| 101 |
+
requests.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=8)
|
| 102 |
+
except:
|
| 103 |
+
pass
|
| 104 |
|
| 105 |
+
# --- TELEGRAM LISTENER ---
|
| 106 |
+
@tg_client.on(events.NewMessage(chats=TARGET_CHANNELS))
|
| 107 |
+
async def telegram_handler(event):
|
| 108 |
try:
|
| 109 |
raw_text = event.raw_text
|
| 110 |
+
sender = await event.get_chat()
|
| 111 |
+
channel_name = getattr(sender, 'username', 'Unknown')
|
| 112 |
+
|
| 113 |
+
# Encrypt and Save
|
| 114 |
+
formatted_text = f"📢 Channel: @{channel_name}\n⏰ {datetime.now().strftime('%H:%M')}\n\n{raw_text}"
|
| 115 |
+
encrypted = encrypt_message(formatted_text)
|
| 116 |
|
| 117 |
messages_collection.insert_one({
|
| 118 |
"channel": channel_name,
|
| 119 |
+
"encrypted_text": encrypted,
|
| 120 |
"timestamp": datetime.utcnow()
|
| 121 |
})
|
| 122 |
+
|
| 123 |
+
# Send to Bale
|
| 124 |
+
send_to_bale(encrypted, show_keyboard=True)
|
| 125 |
+
except Exception as e:
|
| 126 |
+
print(f"Error handling Telegram message: {e}")
|
| 127 |
+
|
| 128 |
+
# --- BACKGROUND TASK ---
|
| 129 |
+
async def start_telegram():
|
| 130 |
+
print("Starting Telegram Connection...")
|
| 131 |
+
try:
|
| 132 |
+
await tg_client.start()
|
| 133 |
+
print("✅ Telegram Connected")
|
| 134 |
+
await tg_client.run_until_disconnected()
|
| 135 |
except Exception as e:
|
| 136 |
+
print(f"❌ Telegram Connection Error: {e}")
|
| 137 |
|
| 138 |
+
# --- FASTAPI WEB SERVER ---
|
| 139 |
@asynccontextmanager
|
| 140 |
async def lifespan(app: FastAPI):
|
| 141 |
+
# Register Webhook
|
|
|
|
|
|
|
|
|
|
| 142 |
webhook_url = "https://nvd13-test1.hf.space/bale-webhook"
|
| 143 |
requests.get(f"{BALE_API_URL}/setWebhook?url={webhook_url}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
+
# Start Telegram in background
|
| 146 |
+
asyncio.create_task(start_telegram())
|
| 147 |
+
yield
|
| 148 |
await tg_client.disconnect()
|
| 149 |
|
| 150 |
app = FastAPI(lifespan=lifespan)
|
| 151 |
|
| 152 |
@app.get("/")
|
| 153 |
+
async def status():
|
| 154 |
+
return {"status": "running", "connected": tg_client.is_connected()}
|
| 155 |
|
| 156 |
@app.post("/bale-webhook")
|
| 157 |
async def bale_webhook(request: Request):
|
| 158 |
+
try:
|
| 159 |
+
data = await request.json()
|
| 160 |
+
if "message" in data and "text" in data["message"]:
|
| 161 |
+
command = data["message"]["text"]
|
| 162 |
+
now = datetime.utcnow()
|
| 163 |
+
|
| 164 |
+
if "Today" in command:
|
| 165 |
+
start = now.replace(hour=0, minute=0, second=0)
|
| 166 |
+
end = now
|
| 167 |
+
elif "Yesterday" in command:
|
| 168 |
+
start = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0)
|
| 169 |
+
end = start + timedelta(days=1)
|
| 170 |
+
else:
|
| 171 |
+
return {"ok": True}
|
| 172 |
+
|
| 173 |
+
results = messages_collection.find({"timestamp": {"$gte": start, "$lt": end}})
|
| 174 |
+
count = 0
|
| 175 |
+
for msg in results:
|
| 176 |
+
send_to_bale(msg["encrypted_text"])
|
| 177 |
+
count += 1
|
| 178 |
+
await asyncio.sleep(0.5) # Prevents spamming Bale
|
| 179 |
|
| 180 |
+
if count == 0:
|
| 181 |
+
send_to_bale(encrypt_message("No messages found for this period."))
|
| 182 |
+
|
| 183 |
+
except Exception as e:
|
| 184 |
+
print(f"Webhook Error: {e}")
|
| 185 |
return {"ok": True}
|
| 186 |
|
| 187 |
if __name__ == "__main__":
|
|
|
|
| 188 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|