nvd commited on
Commit
9443cfb
·
verified ·
1 Parent(s): 565e9ba

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +85 -57
main.py CHANGED
@@ -1,100 +1,128 @@
1
  import os
2
  import asyncio
3
  import httpx
4
- from datetime import datetime, timedelta
 
5
  from telethon import TelegramClient, events
6
  from telethon.sessions import StringSession
7
- import pgpy
8
  from motor.motor_asyncio import AsyncIOMotorClient
9
- from fastapi import FastAPI, Request
10
  import uvicorn
11
  from contextlib import asynccontextmanager
12
 
13
- print("--- 🏁 System Starting ---")
14
-
15
- # --- 1. SAFE ENV LOADING ---
16
  def get_env(name):
17
- val = os.getenv(name)
18
- if not val:
19
- print(f"❌ MISSING CONFIG: {name} is not set in Environment Variables")
20
- return None
21
- return val
22
 
23
- TG_API_ID = get_env("TG_API_ID")
 
24
  TG_API_HASH = get_env("TG_API_HASH")
 
 
 
25
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
26
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
 
 
 
 
 
 
27
  MONGO_URI = get_env("MONGO_URI")
28
- TARGET_CHANNELS_RAW = get_env("TARGET_CHANNELS")
29
  PUB_KEY_TEXT = get_env("PUB_KEY_TEXT")
30
- # For Telegram, we use a SESSION_STRING to avoid the phone login crash
31
- TG_SESSION_STRING = os.getenv("TG_SESSION_STRING")
32
 
33
- # --- 2. INITIALIZATION CHECK ---
34
- if not all([TG_API_ID, TG_API_HASH, BALE_BOT_TOKEN, MONGO_URI, PUB_KEY_TEXT]):
35
- print("FATAL: Critical variables missing. Check your Hugging Face Secrets.")
36
- # We don't exit(1) immediately so we can see the logs
37
- else:
38
- print("✅ Environment Variables Loaded")
39
-
40
- # Clients (Lazy init)
41
  db_client = AsyncIOMotorClient(MONGO_URI)
42
- db = db_client['telegram_bale_db']
43
  messages_collection = db['messages']
44
 
45
- try:
46
- pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
47
- print("✅ PGP Public Key Loaded")
48
- except Exception as e:
49
- print(f"❌ PGP Key Error: {e}")
 
50
 
51
- # Telegram Client Setup
52
- # If no SESSION_STRING is provided, it will use a local file (might fail on HF)
53
- if TG_SESSION_STRING:
54
- tg_client = TelegramClient(StringSession(TG_SESSION_STRING), int(TG_API_ID), TG_API_HASH)
55
- else:
56
- tg_client = TelegramClient('session_name', int(TG_API_ID), TG_API_HASH)
57
 
58
- # --- 3. LOGIC ---
59
  async def send_to_bale(text):
 
60
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
61
  async with httpx.AsyncClient() as client:
62
- await client.post(url, json={"chat_id": BALE_CHAT_ID, "text": text})
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  @tg_client.on(events.NewMessage)
65
  async def handler(event):
66
- if event.is_channel:
 
 
67
  chat = await event.get_chat()
68
  username = getattr(chat, 'username', '').lower()
69
- if username in [c.strip().lower() for c in TARGET_CHANNELS_RAW.split(",")]:
70
- msg = pgpy.PGPMessage.new(f"📢 @{username}\n\n{event.raw_text}")
71
- encrypted = str(pub_key.encrypt(msg))
72
- await messages_collection.insert_one({"channel": username, "text": encrypted, "ts": datetime.utcnow()})
73
- await send_to_bale(encrypted)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- # --- 4. FASTAPI ---
76
  @asynccontextmanager
77
  async def lifespan(app: FastAPI):
78
- print("--- 🚀 Lifespan Starting ---")
79
- try:
80
- await tg_client.start()
81
- print("✅ Telegram Connected")
82
- asyncio.create_task(tg_client.run_until_disconnected())
83
- except Exception as e:
84
- print(f"❌ Telegram Connection Failed: {e}")
 
 
 
 
85
  yield
86
  await tg_client.disconnect()
 
 
87
 
88
  app = FastAPI(lifespan=lifespan)
89
 
90
  @app.get("/")
91
  async def health():
92
- return {"status": "running", "time": str(datetime.now())}
93
-
94
- @app.post("/bale-webhook")
95
- async def webhook(request: Request):
96
- return {"ok": True}
97
 
98
  if __name__ == "__main__":
99
- # Hugging Face MUST run on port 7860
100
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  import os
2
  import asyncio
3
  import httpx
4
+ import pgpy
5
+ from datetime import datetime
6
  from telethon import TelegramClient, events
7
  from telethon.sessions import StringSession
8
+ from rubpy import Client as RubikaClient # rubpy supports both bots and users
9
  from motor.motor_asyncio import AsyncIOMotorClient
10
+ from fastapi import FastAPI
11
  import uvicorn
12
  from contextlib import asynccontextmanager
13
 
14
+ # --- 1. LOAD CONFIGURATION ---
 
 
15
  def get_env(name):
16
+ return os.getenv(name)
 
 
 
 
17
 
18
+ # Telegram Config
19
+ TG_API_ID = int(get_env("TG_API_ID") or 0)
20
  TG_API_HASH = get_env("TG_API_HASH")
21
+ TG_SESSION_STRING = get_env("TG_SESSION_STRING")
22
+
23
+ # Bale Config
24
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
25
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
26
+
27
+ # Rubika BOT Config
28
+ RUBIKA_BOT_TOKEN = get_env("RUBIKA_BOT_TOKEN") # The token from BotFather
29
+ RUBIKA_CHAT_ID = get_env("RUBIKA_CHAT_ID") # The GUID (g0..., c0..., or u0...)
30
+
31
+ # Global Config
32
  MONGO_URI = get_env("MONGO_URI")
33
+ TARGET_CHANNELS = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",")]
34
  PUB_KEY_TEXT = get_env("PUB_KEY_TEXT")
 
 
35
 
36
+ # --- 2. INITIALIZE CLIENTS ---
 
 
 
 
 
 
 
37
  db_client = AsyncIOMotorClient(MONGO_URI)
38
+ db = db_client['telegram_dual_db']
39
  messages_collection = db['messages']
40
 
41
+ pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
42
+
43
+ tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
44
+
45
+ # rubpy uses the bot token in the 'auth' parameter
46
+ rub_bot = RubikaClient(auth=RUBIKA_BOT_TOKEN) if RUBIKA_BOT_TOKEN else None
47
 
48
+ # --- 3. HELPER FUNCTIONS ---
49
+
50
+ def encrypt_message(text):
51
+ msg = pgpy.PGPMessage.new(text)
52
+ return str(pub_key.encrypt(msg))
 
53
 
 
54
  async def send_to_bale(text):
55
+ if not BALE_BOT_TOKEN: return
56
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
57
  async with httpx.AsyncClient() as client:
58
+ try:
59
+ await client.post(url, json={"chat_id": BALE_CHAT_ID, "text": text}, timeout=10)
60
+ except Exception as e:
61
+ print(f"❌ Bale Error: {e}")
62
+
63
+ async def send_to_rubika_bot(text):
64
+ if not rub_bot: return
65
+ try:
66
+ # For Bots, rubpy uses the same send_text method
67
+ await rub_bot.send_text(RUBIKA_CHAT_ID, text)
68
+ except Exception as e:
69
+ print(f"❌ Rubika Bot Error: {e}")
70
+
71
+ # --- 4. TELEGRAM HANDLER ---
72
 
73
  @tg_client.on(events.NewMessage)
74
  async def handler(event):
75
+ if not event.is_channel: return
76
+
77
+ try:
78
  chat = await event.get_chat()
79
  username = getattr(chat, 'username', '').lower()
80
+
81
+ if username in TARGET_CHANNELS:
82
+ print(f"🎯 Capturing from @{username}")
83
+ raw_text = event.raw_text or "[No Text]"
84
+ encrypted = encrypt_message(f"📢 @{username}\n\n{raw_text}")
85
+
86
+ # Save to Mongo with 7-day expiry
87
+ await messages_collection.insert_one({
88
+ "channel": username,
89
+ "text": encrypted,
90
+ "timestamp": datetime.utcnow()
91
+ })
92
+
93
+ # Send to Bale and Rubika simultaneously
94
+ await asyncio.gather(
95
+ send_to_bale(encrypted),
96
+ send_to_rubika_bot(encrypted)
97
+ )
98
+ except Exception as e:
99
+ print(f"Handler Error: {e}")
100
+
101
+ # --- 5. LIFECYCLE ---
102
 
 
103
  @asynccontextmanager
104
  async def lifespan(app: FastAPI):
105
+ # Set Auto-Delete for MongoDB (7 days)
106
+ await messages_collection.create_index("timestamp", expireAfterSeconds=604800)
107
+
108
+ # Start Telegram
109
+ await tg_client.start()
110
+ asyncio.create_task(tg_client.run_until_disconnected())
111
+
112
+ # Start Rubika Bot
113
+ if rub_bot:
114
+ print("🚀 Rubika Bot Client Initialized")
115
+
116
  yield
117
  await tg_client.disconnect()
118
+ if rub_bot:
119
+ await rub_bot.disconnect()
120
 
121
  app = FastAPI(lifespan=lifespan)
122
 
123
  @app.get("/")
124
  async def health():
125
+ return {"status": "online", "monitoring": TARGET_CHANNELS}
 
 
 
 
126
 
127
  if __name__ == "__main__":
 
128
  uvicorn.run(app, host="0.0.0.0", port=7860)