nvd commited on
Update main.py
Browse files
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.
|
| 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.
|
| 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 |
-
#
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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
|
| 58 |
-
|
| 59 |
-
async def
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
try:
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
except Exception as e:
|
| 65 |
-
print(f"β
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# --- 4. TELEGRAM EVENT HANDLER ---
|
| 68 |
-
|
| 69 |
@tg_client.on(events.NewMessage)
|
| 70 |
async def handler(event):
|
| 71 |
-
if not event.is_channel:
|
|
|
|
| 72 |
try:
|
| 73 |
chat = await event.get_chat()
|
| 74 |
username = getattr(chat, 'username', '').lower()
|
| 75 |
-
|
| 76 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 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 |
-
|
| 108 |
-
|
|
|
|
|
|
|
| 109 |
except Exception as e:
|
| 110 |
-
print(f"
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
| 120 |
|
| 121 |
yield
|
| 122 |
-
|
| 123 |
await tg_client.disconnect()
|
| 124 |
-
if rub_bot:
|
| 125 |
-
await rub_bot.disconnect()
|
| 126 |
|
| 127 |
-
|
| 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():
|