nvd commited on
Commit
9865552
·
verified ·
1 Parent(s): b808ebc

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -7
main.py CHANGED
@@ -18,7 +18,7 @@ MONGO_URI = 'mongodb+srv://test1:Kjs93&kh39@cluster0.tx7plhr.mongodb.net/?appNam
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-----
@@ -102,23 +102,73 @@ def send_to_bale(text, show_keyboard=False):
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)
 
18
  BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
19
 
20
  # Target Channels
21
+ TARGET_CHANNELS = ['IranintlTV', 'vahidonline', 'Indypersian', 'mamlekate', 'nvd13']
22
 
23
  # PGP Public Key
24
  PUB_KEY_TEXT = """-----BEGIN PGP PUBLIC KEY BLOCK-----
 
102
  except:
103
  pass
104
 
105
+ # --- UPDATED 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
+ # Telethon sometimes returns the ID, let's make sure we get the username correctly
111
+ chat = await event.get_chat()
112
+ channel_name = getattr(chat, 'username', 'Unknown')
113
 
114
+ print(f"📥 NEW MESSAGE DETECTED from @{channel_name}") # DEBUG LOG
115
+
116
  formatted_text = f"📢 Channel: @{channel_name}\n⏰ {datetime.now().strftime('%H:%M')}\n\n{raw_text}"
117
  encrypted = encrypt_message(formatted_text)
118
 
119
+ # SAVE TO DB
120
+ doc = {
121
  "channel": channel_name,
122
  "encrypted_text": encrypted,
123
  "timestamp": datetime.utcnow()
124
+ }
125
+ result = messages_collection.insert_one(doc)
126
+ print(f"✅ Saved to MongoDB. ID: {result.inserted_id}") # DEBUG LOG
127
+
128
+ # SEND TO BALE
129
+ send_to_bale(encrypted, show_keyboard=True)
130
+ print(f"📤 Forwarded to Bale.") # DEBUG LOG
131
+
132
+ except Exception as e:
133
+ print(f"❌ Error in Telegram Handler: {e}")
134
+
135
+ # --- UPDATED WEBHOOK ---
136
+ @app.post("/bale-webhook")
137
+ async def bale_webhook(request: Request):
138
+ try:
139
+ data = await request.json()
140
+ if "message" in data and "text" in data["message"]:
141
+ command = data["message"]["text"]
142
+ now = datetime.utcnow()
143
+
144
+ print(f"🕹️ User clicked: {command}") # DEBUG LOG
145
+
146
+ if "Today" in command:
147
+ # Set start to the very beginning of today (UTC)
148
+ start = now.replace(hour=0, minute=0, second=0, microsecond=0)
149
+ end = now + timedelta(hours=1) # Buffer
150
+ elif "Yesterday" in command:
151
+ start = (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
152
+ end = start + timedelta(days=1)
153
+ else:
154
+ send_to_bale(encrypt_message("Menu updated."), show_keyboard=True)
155
+ return {"ok": True}
156
+
157
+ print(f"🔍 Searching DB from {start} to {end}") # DEBUG LOG
158
+
159
+ results = list(messages_collection.find({"timestamp": {"$gte": start, "$lt": end}}))
160
+ print(f"📊 Found {len(results)} messages in database.") # DEBUG LOG
161
+
162
+ if len(results) == 0:
163
+ send_to_bale(encrypt_message("No messages found in database for this period."))
164
+ else:
165
+ for m in results:
166
+ send_to_bale(m["encrypted_text"])
167
+ await asyncio.sleep(0.3)
168
+
169
+ except Exception as e:
170
+ print(f"❌ Webhook Error: {e}")
171
+ return {"ok": True}
172
 
173
  # Send to Bale
174
  send_to_bale(encrypted, show_keyboard=True)