nvd commited on
Commit
8cdf978
·
verified ·
1 Parent(s): 8d48cf7

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +12 -17
main.py CHANGED
@@ -4,7 +4,7 @@ import httpx
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
@@ -15,18 +15,15 @@ from contextlib import asynccontextmanager
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,10 +35,10 @@ messages_collection = db['messages']
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 ---
@@ -62,7 +59,7 @@ async def send_to_bale(text):
62
  async def send_to_rubika(text):
63
  if not rub_bot: return
64
  try:
65
- # Update: use send_message for this version of rubpy
66
  await rub_bot.send_message(RUBIKA_CHAT_ID, text)
67
  except Exception as e:
68
  print(f"❌ Rubika Bot Error: {e}")
@@ -80,14 +77,12 @@ async def handler(event):
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)
@@ -99,10 +94,10 @@ async def handler(event):
99
 
100
  @asynccontextmanager
101
  async def lifespan(app: FastAPI):
102
- # 1. Setup Mongo TTL (Auto-delete after 7 days)
103
  await messages_collection.create_index("timestamp", expireAfterSeconds=604800)
104
 
105
- # 2. Connect Telegram
106
  try:
107
  print("Connecting to Telegram...")
108
  await tg_client.connect()
@@ -114,24 +109,24 @@ async def lifespan(app: FastAPI):
114
  except Exception as e:
115
  print(f"❌ Telegram Fail: {e}")
116
 
117
- # 3. Connect Rubika Bot (FIXED PART)
118
  if rub_bot:
119
  try:
120
  print("Connecting to Rubika Bot...")
121
- await rub_bot.start() # THIS IS THE MISSING LINE
122
  print("✅ Rubika Bot Connected and Ready!")
123
  except Exception as e:
124
  print(f"❌ Rubika Startup Error: {e}")
125
 
126
  yield
127
 
128
- # Graceful shutdown
129
  await tg_client.disconnect()
130
  if rub_bot:
131
- # rubpy uses disconnect() or close() depending on version
132
- # disconnect() is usually standard
133
  await rub_bot.disconnect()
134
 
 
 
 
135
  @app.get("/")
136
  async def health():
137
  return {"status": "running", "monitoring": TARGET_CHANNELS}
 
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
9
  from motor.motor_asyncio import AsyncIOMotorClient
10
  from fastapi import FastAPI
 
15
  def get_env(name):
16
  return os.getenv(name)
17
 
 
18
  TG_API_ID = int(get_env("TG_API_ID") or 0)
19
  TG_API_HASH = get_env("TG_API_HASH")
20
+ TG_SESSION_STRING = get_env("TG_SESSION_STRING")
21
 
 
22
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
23
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
24
  RUBIKA_BOT_TOKEN = get_env("RUBIKA_BOT_TOKEN")
25
  RUBIKA_CHAT_ID = get_env("RUBIKA_CHAT_ID")
26
 
 
27
  MONGO_URI = get_env("MONGO_URI")
28
  TARGET_CHANNELS = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",")]
29
  PUB_KEY_TEXT = get_env("PUB_KEY_TEXT")
 
35
 
36
  pub_key, _ = pgpy.PGPKey.from_blob(PUB_KEY_TEXT)
37
 
38
+ # TELEGRAM: Uses StringSession for server-safe login
39
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
40
 
41
+ # RUBIKA: Uses name="rubika_bot" to prevent TypeError
42
  rub_bot = RubikaClient(name="rubika_bot", auth=RUBIKA_BOT_TOKEN) if RUBIKA_BOT_TOKEN else None
43
 
44
  # --- 3. SENDING FUNCTIONS ---
 
59
  async def send_to_rubika(text):
60
  if not rub_bot: return
61
  try:
62
+ # Using send_message for the current rubpy version
63
  await rub_bot.send_message(RUBIKA_CHAT_ID, text)
64
  except Exception as e:
65
  print(f"❌ Rubika Bot Error: {e}")
 
77
  print(f"🎯 Capturing: @{username}")
78
  encrypted = encrypt_message(f"📢 @{username}\n\n{event.raw_text or '[No Text]'}")
79
 
 
80
  await messages_collection.insert_one({
81
  "channel": username,
82
  "text": encrypted,
83
  "timestamp": datetime.utcnow()
84
  })
85
 
 
86
  await asyncio.gather(
87
  send_to_bale(encrypted),
88
  send_to_rubika(encrypted)
 
94
 
95
  @asynccontextmanager
96
  async def lifespan(app: FastAPI):
97
+ # 1. MongoDB TTL
98
  await messages_collection.create_index("timestamp", expireAfterSeconds=604800)
99
 
100
+ # 2. Telegram Start
101
  try:
102
  print("Connecting to Telegram...")
103
  await tg_client.connect()
 
109
  except Exception as e:
110
  print(f"❌ Telegram Fail: {e}")
111
 
112
+ # 3. Rubika Bot Start
113
  if rub_bot:
114
  try:
115
  print("Connecting to Rubika Bot...")
116
+ await rub_bot.start() # Fixes 'connection' attribute error
117
  print("✅ Rubika Bot Connected and Ready!")
118
  except Exception as e:
119
  print(f"❌ Rubika Startup Error: {e}")
120
 
121
  yield
122
 
 
123
  await tg_client.disconnect()
124
  if rub_bot:
 
 
125
  await rub_bot.disconnect()
126
 
127
+ # --- 6. APP DEFINITION ---
128
+ app = FastAPI(lifespan=lifespan) # <--- THIS LINE WAS MISSING
129
+
130
  @app.get("/")
131
  async def health():
132
  return {"status": "running", "monitoring": TARGET_CHANNELS}