nvd commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
import requests
|
|
@@ -6,23 +8,18 @@ from telethon import TelegramClient, events
|
|
| 6 |
import pgpy
|
| 7 |
from pymongo import MongoClient
|
| 8 |
from fastapi import FastAPI, Request
|
|
|
|
| 9 |
import uvicorn
|
| 10 |
|
| 11 |
# --- CONFIGURATION ---
|
| 12 |
-
TELEGRAM_API_ID =
|
| 13 |
TELEGRAM_API_HASH = 'a2bc0931f3ee06130ceab419802d5703'
|
| 14 |
BALE_BOT_TOKEN = '736303401:8hhKYE6A0Kg0O7rm_dBDWka8MHCS15aHBcE'
|
| 15 |
-
BALE_CHAT_ID = '447422307'
|
| 16 |
MONGO_URI = 'mongodb+srv://test1:Kjs93&kh39@cluster0.tx7plhr.mongodb.net/?appName=Cluster0'
|
| 17 |
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
# 1. MongoDB
|
| 21 |
-
db_client = MongoClient(MONGO_URI)
|
| 22 |
-
db = db_client['telegram_bale_db']
|
| 23 |
-
messages_collection = db['messages']
|
| 24 |
-
|
| 25 |
-
# 2. PGP Encryption (Load your public key here)
|
| 26 |
PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
|
| 27 |
Version: Mailvelope v6.2.1
|
| 28 |
Comment: https://mailvelope.com
|
|
@@ -79,14 +76,17 @@ H8KJTDlU8JXRiccVFnJITD2pXmrYh0ETyKfmfvKyClnZlYvWyj38p+/49+E5
|
|
| 79 |
/kXlE3cLOpFBlL+Q/29qExVOHFaBq073N0oqk+iKlXncLY14AQ==
|
| 80 |
=yiS/
|
| 81 |
-----END PGP PUBLIC KEY BLOCK-----"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
|
| 83 |
|
| 84 |
-
#
|
| 85 |
tg_client = TelegramClient('session_name', TELEGRAM_API_ID, TELEGRAM_API_HASH)
|
| 86 |
|
| 87 |
-
# 4. FastAPI (For Bale Webhooks / Buttons)
|
| 88 |
-
app = FastAPI()
|
| 89 |
-
|
| 90 |
def encrypt_message(text):
|
| 91 |
msg = pgpy.PGPMessage.new(text)
|
| 92 |
encrypted_msg = pub_key.encrypt(msg)
|
|
@@ -94,79 +94,81 @@ def encrypt_message(text):
|
|
| 94 |
|
| 95 |
def send_to_bale(text, show_keyboard=False):
|
| 96 |
payload = {"chat_id": BALE_CHAT_ID, "text": text}
|
| 97 |
-
|
| 98 |
-
# Add buttons for fetching Today/Yesterday messages
|
| 99 |
if show_keyboard:
|
| 100 |
payload["reply_markup"] = {
|
| 101 |
-
"keyboard":[
|
| 102 |
-
[{"text": "Fetch Today's Messages"}],[{"text": "Fetch Yesterday's Messages"}]
|
| 103 |
-
],
|
| 104 |
"resize_keyboard": True
|
| 105 |
}
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
# --- TELEGRAM
|
| 110 |
-
@tg_client.on(events.NewMessage(chats=['@
|
| 111 |
async def handler(event):
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
#
|
| 119 |
-
messages_collection.insert_one({
|
| 120 |
-
"channel": channel_name,
|
| 121 |
-
"encrypted_text": encrypted_text,
|
| 122 |
-
"timestamp": datetime.utcnow()
|
| 123 |
-
})
|
| 124 |
|
| 125 |
-
#
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
# --- BALE WEBHOOK (BUTTON HANDLER) ---
|
| 129 |
@app.post("/bale-webhook")
|
| 130 |
async def bale_webhook(request: Request):
|
| 131 |
data = await request.json()
|
| 132 |
-
|
| 133 |
if "message" in data and "text" in data["message"]:
|
| 134 |
user_text = data["message"]["text"]
|
| 135 |
-
|
| 136 |
now = datetime.utcnow()
|
| 137 |
-
|
|
|
|
| 138 |
start_time = now.replace(hour=0, minute=0, second=0)
|
| 139 |
end_time = now
|
| 140 |
-
elif
|
| 141 |
start_time = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0)
|
| 142 |
end_time = start_time + timedelta(days=1)
|
| 143 |
else:
|
| 144 |
-
return {"
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
count = 0
|
| 151 |
-
for msg in saved_messages:
|
| 152 |
-
send_to_bale(msg["encrypted_text"])
|
| 153 |
-
count += 1
|
| 154 |
|
| 155 |
-
|
| 156 |
-
send_to_bale("No messages found for this timeframe.")
|
| 157 |
-
|
| 158 |
-
return {"status": "ok"}
|
| 159 |
-
|
| 160 |
-
# --- STARTUP SCRIPT ---
|
| 161 |
-
@app.on_event("startup")
|
| 162 |
-
async def startup_event():
|
| 163 |
-
# Set Bale webhook to point to your hosted server
|
| 164 |
-
# (Replace 'your-server-url.com' with your actual HuggingFace/Render URL)
|
| 165 |
-
requests.get(f"{BALE_API_URL}/setWebhook?url=https://nvd13-test1.hf.space/bale-webhook")
|
| 166 |
-
|
| 167 |
-
# Start Telegram background task
|
| 168 |
-
await tg_client.start()
|
| 169 |
-
asyncio.create_task(tg_client.run_until_disconnected())
|
| 170 |
|
| 171 |
if __name__ == "__main__":
|
|
|
|
| 172 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import types
|
| 3 |
import os
|
| 4 |
import asyncio
|
| 5 |
import requests
|
|
|
|
| 8 |
import pgpy
|
| 9 |
from pymongo import MongoClient
|
| 10 |
from fastapi import FastAPI, Request
|
| 11 |
+
from contextlib import asynccontextmanager
|
| 12 |
import uvicorn
|
| 13 |
|
| 14 |
# --- CONFIGURATION ---
|
| 15 |
+
TELEGRAM_API_ID = 35190771 # YOUR ID
|
| 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
|
| 25 |
Comment: https://mailvelope.com
|
|
|
|
| 76 |
/kXlE3cLOpFBlL+Q/29qExVOHFaBq073N0oqk+iKlXncLY14AQ==
|
| 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 |
encrypted_msg = pub_key.encrypt(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's Messages"}],[{"text": "Fetch Yesterday's Messages"}]],
|
|
|
|
|
|
|
| 100 |
"resize_keyboard": True
|
| 101 |
}
|
| 102 |
+
try:
|
| 103 |
+
requests.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=10)
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"Bale send error: {e}")
|
| 106 |
|
| 107 |
+
# --- TELEGRAM HANDLER ---
|
| 108 |
+
@tg_client.on(events.NewMessage(chats=['@channel1'])) # ADD YOUR CHANNELS
|
| 109 |
async def handler(event):
|
| 110 |
+
try:
|
| 111 |
+
raw_text = event.raw_text
|
| 112 |
+
channel_name = event.chat.username or str(event.chat_id)
|
| 113 |
+
enc_text = encrypt_message(f"From: {channel_name}\n\n{raw_text}")
|
| 114 |
+
|
| 115 |
+
messages_collection.insert_one({
|
| 116 |
+
"channel": channel_name,
|
| 117 |
+
"encrypted_text": enc_text,
|
| 118 |
+
"timestamp": datetime.utcnow()
|
| 119 |
+
})
|
| 120 |
+
send_to_bale(enc_text, show_keyboard=True)
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f"Error in TG handler: {e}")
|
| 123 |
+
|
| 124 |
+
# --- LIFESPAN (The modern way to start) ---
|
| 125 |
+
@asynccontextmanager
|
| 126 |
+
async def lifespan(app: FastAPI):
|
| 127 |
+
# This runs when the server starts
|
| 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 |
+
yield # The app runs here
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
+
# This runs when the server stops
|
| 142 |
+
await tg_client.disconnect()
|
| 143 |
+
|
| 144 |
+
app = FastAPI(lifespan=lifespan)
|
| 145 |
+
|
| 146 |
+
@app.get("/")
|
| 147 |
+
def read_root():
|
| 148 |
+
return {"status": "Bot is running"}
|
| 149 |
|
|
|
|
| 150 |
@app.post("/bale-webhook")
|
| 151 |
async def bale_webhook(request: Request):
|
| 152 |
data = await request.json()
|
|
|
|
| 153 |
if "message" in data and "text" in data["message"]:
|
| 154 |
user_text = data["message"]["text"]
|
|
|
|
| 155 |
now = datetime.utcnow()
|
| 156 |
+
|
| 157 |
+
if "Today" in user_text:
|
| 158 |
start_time = now.replace(hour=0, minute=0, second=0)
|
| 159 |
end_time = now
|
| 160 |
+
elif "Yesterday" in user_text:
|
| 161 |
start_time = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0)
|
| 162 |
end_time = start_time + timedelta(days=1)
|
| 163 |
else:
|
| 164 |
+
return {"ok": True}
|
| 165 |
|
| 166 |
+
msgs = messages_collection.find({"timestamp": {"$gte": start_time, "$lt": end_time}})
|
| 167 |
+
for m in msgs:
|
| 168 |
+
send_to_bale(m["encrypted_text"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|