nvd commited on
Commit
0b2da50
Β·
verified Β·
1 Parent(s): 3d54252

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +50 -57
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 (Verify you have JOINED these on your Telegram account)
21
- TARGET_CHANNELS = ['IranintlTV', 'vahidonline', 'Indypersian', 'mamlekate', 'nvd13']
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 Exception as e:
103
- print(f"Bale Send Error: {e}")
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
- chat = await event.get_chat()
111
- channel_name = getattr(chat, 'username', 'Unknown')
112
-
113
- print(f"πŸ“₯ MESSAGE RECEIVED from @{channel_name}")
114
 
115
- formatted_text = f"πŸ“’ Channel: @{channel_name}\n⏰ {datetime.now().strftime('%H:%M')}\n\n{raw_text}"
116
- encrypted = encrypt_message(formatted_text)
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
- # Instant forward
126
- send_to_bale(encrypted, show_keyboard=True)
127
- print("βœ… Message encrypted, saved to DB, and sent to Bale.")
128
-
129
- except Exception as e:
130
- print(f"❌ Telegram Handler Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
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"❌ TELEGRAM CONNECTION FAILED: {e}")
141
 
142
  # --- WEB SERVER ---
143
  @asynccontextmanager
144
  async def lifespan(app: FastAPI):
145
- # Register Webhook
146
- webhook_url = "https://nvd13-test1.hf.space/bale-webhook"
147
- requests.get(f"{BALE_API_URL}/setWebhook?url={webhook_url}")
148
- print(f"Webhook set to {webhook_url}")
 
 
 
 
 
 
149
 
150
- # Start Telegram
151
- asyncio.create_task(start_telegram())
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 {"status": "running", "connected": tg_client.is_connected()}
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) # Buffer
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
- print(f"πŸ” Searching DB between {start} and {end}...")
182
- results = list(messages_collection.find({"timestamp": {"$gte": start, "$lt": end}}))
183
- print(f"πŸ“Š Found {len(results)} messages.")
184
-
185
- if len(results) == 0:
186
  if command != "/start":
187
- send_to_bale(encrypt_message("No messages found for this period yet."))
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
- except Exception as e:
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__":