nvd commited on
Commit
50bba6b
·
verified ·
1 Parent(s): af3831c

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +69 -55
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 # 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
@@ -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
- encrypted_msg = pub_key.encrypt(msg)
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'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)
 
 
 
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)