nvd commited on
Commit
e462f31
Β·
verified Β·
1 Parent(s): aa64ef3

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +34 -43
main.py CHANGED
@@ -4,8 +4,8 @@ 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
@@ -15,20 +15,18 @@ from contextlib import asynccontextmanager
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")
@@ -40,11 +38,13 @@ 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
  rub_bot = RubikaClient(name="rubika_bot", auth=RUBIKA_BOT_TOKEN) if RUBIKA_BOT_TOKEN else None
46
 
47
- # --- 3. HELPER FUNCTIONS ---
48
 
49
  def encrypt_message(text):
50
  msg = pgpy.PGPMessage.new(text)
@@ -59,85 +59,76 @@ async def send_to_bale(text):
59
  except Exception as e:
60
  print(f"❌ Bale Error: {e}")
61
 
62
- async def send_to_rubika_bot(text):
63
  if not rub_bot: return
64
  try:
65
- # For Bots, rubpy uses the same send_text method
66
  await rub_bot.send_text(RUBIKA_CHAT_ID, text)
67
  except Exception as e:
68
  print(f"❌ Rubika Bot Error: {e}")
69
 
70
- # --- 4. TELEGRAM HANDLER ---
71
 
72
  @tg_client.on(events.NewMessage)
73
  async def handler(event):
74
  if not event.is_channel: return
75
-
76
  try:
77
  chat = await event.get_chat()
78
  username = getattr(chat, 'username', '').lower()
79
 
80
  if username in TARGET_CHANNELS:
81
- print(f"🎯 Capturing from @{username}")
82
- raw_text = event.raw_text or "[No Text]"
83
- encrypted = encrypt_message(f"πŸ“’ @{username}\n\n{raw_text}")
84
 
85
- # Save to Mongo with 7-day expiry
86
  await messages_collection.insert_one({
87
  "channel": username,
88
  "text": encrypted,
89
  "timestamp": datetime.utcnow()
90
  })
91
 
92
- # Send to Bale and Rubika simultaneously
93
  await asyncio.gather(
94
  send_to_bale(encrypted),
95
- send_to_rubika_bot(encrypted)
96
  )
97
  except Exception as e:
98
  print(f"Handler Error: {e}")
99
 
100
- # --- 5. LIFECYCLE ---
101
 
102
  @asynccontextmanager
103
  async def lifespan(app: FastAPI):
104
- # 1. Setup MongoDB TTL (7 days)
105
- try:
106
- await messages_collection.create_index("timestamp", expireAfterSeconds=604800)
107
- print("βœ… MongoDB TTL Index active")
108
- except Exception as e:
109
- print(f"⚠️ Mongo Index Error: {e}")
110
-
111
- # 2. Start Telegram (Server-Safe Mode)
112
  try:
113
  print("Connecting to Telegram...")
114
- await tg_client.connect() # Use connect(), NOT start()
115
-
116
  if not await tg_client.is_user_authorized():
117
- print("❌ ERROR: Telegram is NOT authorized.")
118
- print("Your TG_SESSION_STRING is either missing, invalid, or expired.")
119
- print("The app will stay online but Telegram messages won't be captured.")
120
  else:
121
- print("βœ… Telegram Authorized & Connected!")
122
- # Run Telegram listener in the background
123
  asyncio.create_task(tg_client.run_until_disconnected())
124
-
125
  except Exception as e:
126
- print(f"❌ Telegram Connection Error: {e}")
127
 
128
- # 3. Rubika Bot Initialization
129
  if rub_bot:
130
- print("πŸš€ Rubika Bot Initialized")
131
 
132
  yield
133
- # Shutdown
134
  await tg_client.disconnect()
135
  if rub_bot:
136
  await rub_bot.disconnect()
137
 
 
 
138
  @app.get("/")
139
  async def health():
140
- return {"status": "online", "monitoring": TARGET_CHANNELS}
141
 
142
  if __name__ == "__main__":
143
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
4
  import pgpy
5
  from datetime import datetime
6
  from telethon import TelegramClient, events
7
+ from telethon.sessions import StringSession # Added for the String Session
8
+ from rubpy import Client as RubikaClient
9
  from motor.motor_asyncio import AsyncIOMotorClient
10
  from fastapi import FastAPI
11
  import uvicorn
 
15
  def get_env(name):
16
  return os.getenv(name)
17
 
18
+ # Telegram (Using the new String Session)
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") # The long 1B... string
22
 
23
+ # Bale & Rubika
24
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
25
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
26
+ RUBIKA_BOT_TOKEN = get_env("RUBIKA_BOT_TOKEN")
27
+ RUBIKA_CHAT_ID = get_env("RUBIKA_CHAT_ID")
28
 
29
+ # Global
 
 
 
 
30
  MONGO_URI = get_env("MONGO_URI")
31
  TARGET_CHANNELS = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",")]
32
  PUB_KEY_TEXT = get_env("PUB_KEY_TEXT")
 
38
 
39
  pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
40
 
41
+ # TELEGRAM: Now uses StringSession to avoid file issues and login crashes
42
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
43
 
44
+ # RUBIKA: Uses name="rubika_bot" to fix the TypeError you saw earlier
45
  rub_bot = RubikaClient(name="rubika_bot", auth=RUBIKA_BOT_TOKEN) if RUBIKA_BOT_TOKEN else None
46
 
47
+ # --- 3. SENDING FUNCTIONS ---
48
 
49
  def encrypt_message(text):
50
  msg = pgpy.PGPMessage.new(text)
 
59
  except Exception as e:
60
  print(f"❌ Bale Error: {e}")
61
 
62
+ async def send_to_rubika(text):
63
  if not rub_bot: return
64
  try:
65
+ # For Rubika bots, we use send_text
66
  await rub_bot.send_text(RUBIKA_CHAT_ID, text)
67
  except Exception as e:
68
  print(f"❌ Rubika Bot Error: {e}")
69
 
70
+ # --- 4. TELEGRAM EVENT HANDLER ---
71
 
72
  @tg_client.on(events.NewMessage)
73
  async def handler(event):
74
  if not event.is_channel: return
 
75
  try:
76
  chat = await event.get_chat()
77
  username = getattr(chat, 'username', '').lower()
78
 
79
  if username in TARGET_CHANNELS:
80
+ print(f"🎯 Capturing: @{username}")
81
+ encrypted = encrypt_message(f"πŸ“’ @{username}\n\n{event.raw_text or '[No Text]'}")
 
82
 
83
+ # Save to Mongo
84
  await messages_collection.insert_one({
85
  "channel": username,
86
  "text": encrypted,
87
  "timestamp": datetime.utcnow()
88
  })
89
 
90
+ # Send to both platforms at once
91
  await asyncio.gather(
92
  send_to_bale(encrypted),
93
+ send_to_rubika(encrypted)
94
  )
95
  except Exception as e:
96
  print(f"Handler Error: {e}")
97
 
98
+ # --- 5. SERVER-SAFE LIFESPAN ---
99
 
100
  @asynccontextmanager
101
  async def lifespan(app: FastAPI):
102
+ # Setup Mongo TTL (Auto-delete after 7 days)
103
+ await messages_collection.create_index("timestamp", expireAfterSeconds=604800)
104
+
105
+ # Connect Telegram (Safe method)
 
 
 
 
106
  try:
107
  print("Connecting to Telegram...")
108
+ await tg_client.connect()
 
109
  if not await tg_client.is_user_authorized():
110
+ print("❌ TELEGRAM NOT AUTHORIZED! Check your TG_SESSION_STRING.")
 
 
111
  else:
112
+ print("βœ… Telegram Connected!")
 
113
  asyncio.create_task(tg_client.run_until_disconnected())
 
114
  except Exception as e:
115
+ print(f"❌ Telegram Fail: {e}")
116
 
117
+ # Rubika Bot Status
118
  if rub_bot:
119
+ print("βœ… Rubika Bot Initialized")
120
 
121
  yield
122
+ # Graceful shutdown
123
  await tg_client.disconnect()
124
  if rub_bot:
125
  await rub_bot.disconnect()
126
 
127
+ app = FastAPI(lifespan=lifespan)
128
+
129
  @app.get("/")
130
  async def health():
131
+ return {"status": "running", "monitoring": TARGET_CHANNELS}
132
 
133
  if __name__ == "__main__":
134
  uvicorn.run(app, host="0.0.0.0", port=7860)