nvd commited on
Commit
5eb10de
·
verified ·
1 Parent(s): 95b7f8e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +125 -82
main.py CHANGED
@@ -1,17 +1,14 @@
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
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
 
@@ -21,111 +18,157 @@ 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")
30
 
31
- # --- 2. INITIALIZE CLIENTS ---
32
- db_client = AsyncIOMotorClient(MONGO_URI)
33
- db = db_client['telegram_dual_db']
34
- messages_collection = db['messages']
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 ---
45
-
46
- def encrypt_message(text):
47
- msg = pgpy.PGPMessage.new(text)
48
- return str(pub_key.encrypt(msg))
49
-
50
- async def send_to_bale(text):
51
- if not BALE_BOT_TOKEN: return
52
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
53
  async with httpx.AsyncClient() as client:
54
  try:
55
  await client.post(url, json={"chat_id": BALE_CHAT_ID, "text": text}, timeout=10)
56
  except Exception as e:
57
- print(f"❌ Bale Error: {e}")
58
-
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}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  # --- 4. TELEGRAM EVENT HANDLER ---
68
-
69
  @tg_client.on(events.NewMessage)
70
  async def handler(event):
71
- if not event.is_channel: return
 
72
  try:
73
  chat = await event.get_chat()
74
  username = getattr(chat, 'username', '').lower()
75
-
76
- if username in TARGET_CHANNELS:
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)
89
- )
90
- except Exception as e:
91
- print(f"Handler Error: {e}")
92
 
93
- # --- 5. SERVER-SAFE LIFESPAN ---
 
 
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()
104
- if not await tg_client.is_user_authorized():
105
- print("❌ TELEGRAM NOT AUTHORIZED!")
106
  else:
107
- print("✅ Telegram Connected!")
108
- asyncio.create_task(tg_client.run_until_disconnected())
 
 
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():
 
1
  import os
2
  import asyncio
3
+ import tempfile
4
  import httpx
 
 
5
  from telethon import TelegramClient, events
6
  from telethon.sessions import StringSession
 
 
7
  from fastapi import FastAPI
8
  import uvicorn
9
  from contextlib import asynccontextmanager
10
 
11
+ # --- 1. CONFIGURATION ---
12
  def get_env(name):
13
  return os.getenv(name)
14
 
 
18
 
19
  BALE_BOT_TOKEN = get_env("BALE_BOT_TOKEN")
20
  BALE_CHAT_ID = get_env("BALE_CHAT_ID")
 
 
21
 
 
22
  TARGET_CHANNELS = [c.strip().lower() for c in (get_env("TARGET_CHANNELS") or "").split(",")]
 
23
 
24
+ # --- 2. TELEGRAM CLIENT ---
 
 
 
 
 
 
 
25
  tg_client = TelegramClient(StringSession(TG_SESSION_STRING), TG_API_ID, TG_API_HASH)
26
 
27
+ # --- 3. BALE SENDING HELPERS ---
28
+ async def send_text_to_bale(text):
29
+ if not BALE_BOT_TOKEN:
30
+ return
 
 
 
 
 
 
 
31
  url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/sendMessage"
32
  async with httpx.AsyncClient() as client:
33
  try:
34
  await client.post(url, json={"chat_id": BALE_CHAT_ID, "text": text}, timeout=10)
35
  except Exception as e:
36
+ print(f"❌ Bale text error: {e}")
37
+
38
+ async def send_media_to_bale(file_path, caption, media_type):
39
+ """Send a photo/video/document/etc. to Bale."""
40
+ if not BALE_BOT_TOKEN:
41
+ return
42
+
43
+ endpoint_map = {
44
+ "photo": "sendPhoto",
45
+ "video": "sendVideo",
46
+ "document": "sendDocument",
47
+ "audio": "sendAudio",
48
+ "voice": "sendVoice",
49
+ "sticker": "sendSticker",
50
+ "video_note": "sendVideoNote",
51
+ }
52
+ endpoint = endpoint_map.get(media_type, "sendDocument")
53
+ url = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}/{endpoint}"
54
+
55
+ data = {"chat_id": BALE_CHAT_ID}
56
+ if caption:
57
+ data["caption"] = caption
58
+
59
+ # Use the proper field name for the file
60
+ field_name = media_type if media_type in endpoint_map else "document"
61
+ with open(file_path, "rb") as f:
62
+ files = {field_name: f}
63
+ async with httpx.AsyncClient() as client:
64
+ try:
65
+ resp = await client.post(url, data=data, files=files, timeout=30)
66
+ if resp.status_code != 200:
67
+ print(f"❌ Bale media error ({media_type}): {resp.text}")
68
+ except Exception as e:
69
+ print(f"❌ Bale media request failed: {e}")
70
+
71
+ async def download_media(message):
72
+ """Download Telegram media to a temp file, return the path."""
73
+ if not message.media:
74
+ return None
75
  try:
76
+ suffix = ""
77
+ if message.photo:
78
+ suffix = ".jpg"
79
+ elif message.video:
80
+ suffix = ".mp4"
81
+ elif getattr(message, 'document', None):
82
+ attrs = message.document.attributes
83
+ for attr in attrs:
84
+ if hasattr(attr, 'file_name'):
85
+ if '.' in attr.file_name:
86
+ suffix = f".{attr.file_name.split('.')[-1]}"
87
+ break
88
+ if not suffix:
89
+ mime = message.document.mime_type
90
+ if mime and '/' in mime:
91
+ suffix = f".{mime.split('/')[-1]}"
92
+ elif message.audio:
93
+ suffix = ".mp3"
94
+ elif message.voice:
95
+ suffix = ".ogg"
96
+ elif message.sticker:
97
+ suffix = ".webp"
98
+ elif message.video_note:
99
+ suffix = ".mp4"
100
+
101
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
102
+ path = tmp.name
103
+ await message.download_media(file=path)
104
+ return path
105
  except Exception as e:
106
+ print(f"❌ Media download error: {e}")
107
+ return None
108
+
109
+ def detect_media_type(event):
110
+ """Return the media type string based on event attributes."""
111
+ if event.photo:
112
+ return "photo"
113
+ if event.video:
114
+ return "video"
115
+ if event.audio:
116
+ return "audio"
117
+ if event.voice:
118
+ return "voice"
119
+ if event.sticker:
120
+ return "sticker"
121
+ if event.video_note:
122
+ return "video_note"
123
+ if event.document:
124
+ return "document"
125
+ return None
126
 
127
  # --- 4. TELEGRAM EVENT HANDLER ---
 
128
  @tg_client.on(events.NewMessage)
129
  async def handler(event):
130
+ if not event.is_channel:
131
+ return
132
  try:
133
  chat = await event.get_chat()
134
  username = getattr(chat, 'username', '').lower()
135
+ if username not in TARGET_CHANNELS:
136
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
+ print(f"🎯 Capturing: @{username}")
139
+ caption = event.raw_text or ""
140
+ header = f"📢 @{username}\n\n"
141
 
142
+ media_type = detect_media_type(event)
143
+ media_path = await download_media(event) if media_type else None
144
+
145
+ if media_path:
146
+ # Send media with caption
147
+ await send_media_to_bale(media_path, caption, media_type)
148
+ os.unlink(media_path) # clean up
 
 
 
 
149
  else:
150
+ # Plain text
151
+ full_text = header + caption
152
+ await send_text_to_bale(full_text)
153
+
154
  except Exception as e:
155
+ print(f"Handler Error: {e}")
156
 
157
+ # --- 5. SERVER LIFESPAN ---
158
+ @asynccontextmanager
159
+ async def lifespan(app: FastAPI):
160
+ print("Connecting to Telegram...")
161
+ await tg_client.connect()
162
+ if not await tg_client.is_user_authorized():
163
+ print("❌ TELEGRAM NOT AUTHORIZED!")
164
+ else:
165
+ print("✅ Telegram Connected!")
166
+ asyncio.create_task(tg_client.run_until_disconnected())
167
 
168
  yield
 
169
  await tg_client.disconnect()
 
 
170
 
171
+ app = FastAPI(lifespan=lifespan)
 
172
 
173
  @app.get("/")
174
  async def health():