nvd commited on
Commit
79a55c7
·
verified ·
1 Parent(s): ee0003e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +29 -63
main.py CHANGED
@@ -9,7 +9,7 @@ from fastapi import FastAPI, Request
9
  from contextlib import asynccontextmanager
10
  import uvicorn
11
 
12
- # --- CONFIGURATION ---
13
  TELEGRAM_API_ID = 35190771
14
  TELEGRAM_API_HASH = 'a2bc0931f3ee06130ceab419802d5703'
15
  BALE_BOT_TOKEN = '736303401:8hhKYE6A0Kg0O7rm_dBDWka8MHCS15aHBcE'
@@ -17,10 +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 (Lowercase for matching)
21
- TARGET_CHANNELS = ['iranintltv', 'vahidonline', 'indypersian', 'mamlekate', 'nvd13']
22
 
23
- # PGP Public Key
24
  PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
25
  Version: Mailvelope v6.2.1
26
  Comment: https://mailvelope.com
@@ -78,11 +76,10 @@ Sh4SNrYn/11tjtY80WYDxm9SCo0OQC6Kp1dBKt/ZTw+e+Hc=
78
  =ZGjw
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
 
@@ -93,64 +90,38 @@ def encrypt_message(text):
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
- # --- 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,7 +129,7 @@ app = FastAPI(lifespan=lifespan)
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):
@@ -167,28 +138,23 @@ async def bale_webhook(request: Request):
167
  if "message" in data and "text" in data["message"]:
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
 
193
  if __name__ == "__main__":
194
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
9
  from contextlib import asynccontextmanager
10
  import uvicorn
11
 
12
+ # --- CONFIGURATION (Your correct keys) ---
13
  TELEGRAM_API_ID = 35190771
14
  TELEGRAM_API_HASH = 'a2bc0931f3ee06130ceab419802d5703'
15
  BALE_BOT_TOKEN = '736303401:8hhKYE6A0Kg0O7rm_dBDWka8MHCS15aHBcE'
 
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 = ['iranintltv', 'vahidonline', 'indypersian', 'mamlekate']
 
21
 
 
22
  PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
23
  Version: Mailvelope v6.2.1
24
  Comment: https://mailvelope.com
 
76
  =ZGjw
77
  -----END PGP PUBLIC KEY BLOCK-----"""
78
 
79
+ # Initialize basic clients
80
  db_client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
81
  db = db_client['telegram_bale_db']
82
  messages_collection = db['messages']
 
83
  pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
84
  tg_client = TelegramClient('session_name', TELEGRAM_API_ID, TELEGRAM_API_HASH)
85
 
 
90
  def send_to_bale(text, show_keyboard=False):
91
  payload = {"chat_id": BALE_CHAT_ID, "text": text}
92
  if show_keyboard:
93
+ payload["reply_markup"] = {"keyboard":[[{"text": "Fetch Today"}],[{"text": "Fetch Yesterday"}]],"resize_keyboard": True}
94
+ try: requests.post(f"{BALE_API_URL}/sendMessage", json=payload, timeout=5)
95
+ except: pass
 
 
 
 
 
96
 
97
+ @tg_client.on(events.NewMessage)
 
98
  async def broad_handler(event):
99
  try:
100
+ if not event.is_channel: return
 
 
 
 
101
  chat = await event.get_chat()
102
  username = getattr(chat, 'username', '').lower()
 
 
 
 
 
103
  if username in TARGET_CHANNELS:
104
+ print(f"🎯 MATCH: @{username}")
105
+ enc = encrypt_message(f"📢 @{username}\n\n{event.raw_text}")
106
+ messages_collection.insert_one({"channel": username, "encrypted_text": enc, "timestamp": datetime.utcnow()})
107
+ send_to_bale(enc, show_keyboard=True)
108
+ except Exception as e: print(f"Error: {e}")
109
+
110
+ async def run_telegram_bg():
111
+ print("--- Background: Connecting to Telegram ---")
112
+ try:
113
+ await tg_client.start()
114
+ print("✅ TELEGRAM CONNECTED AND LISTENING")
115
+ await tg_client.run_until_disconnected()
 
116
  except Exception as e:
117
+ print(f"❌ Telegram Background Error: {e}")
118
 
 
119
  @asynccontextmanager
120
  async def lifespan(app: FastAPI):
121
+ # 1. Set Webhook immediately
122
  requests.get(f"{BALE_API_URL}/setWebhook?url=https://nvd13-test1.hf.space/bale-webhook")
123
+ # 2. Start Telegram in background so it doesn't block startup
124
+ asyncio.create_task(run_telegram_bg())
 
 
 
 
 
 
 
 
 
125
  yield
126
  await tg_client.disconnect()
127
 
 
129
 
130
  @app.get("/")
131
  async def status():
132
+ return {"status": "online", "tg": tg_client.is_connected()}
133
 
134
  @app.post("/bale-webhook")
135
  async def bale_webhook(request: Request):
 
138
  if "message" in data and "text" in data["message"]:
139
  command = data["message"]["text"]
140
  now = datetime.utcnow()
 
141
  if "Today" in command or command == "/start":
142
  start = now.replace(hour=0, minute=0, second=0, microsecond=0)
143
  end = now + timedelta(hours=2)
144
  elif "Yesterday" in command:
145
  start = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
146
  end = start + timedelta(days=1)
147
+ else: return {"ok": True}
 
148
 
149
+ results = list(messages_collection.find({"timestamp": {"$gte": start, "$lt": end}}).limit(30))
150
  if not results:
151
+ if command != "/start": send_to_bale(encrypt_message("No messages in DB."))
 
152
  else:
153
  for msg in results:
154
  send_to_bale(msg["encrypted_text"])
155
  await asyncio.sleep(0.3)
156
+ except: pass
 
157
  return {"ok": True}
 
158
 
159
  if __name__ == "__main__":
160
  uvicorn.run(app, host="0.0.0.0", port=7860)