nvd commited on
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -7,7 +7,6 @@ import sqlite3
|
|
| 7 |
import aiohttp
|
| 8 |
import logging
|
| 9 |
import tempfile
|
| 10 |
-
import shutil
|
| 11 |
|
| 12 |
# ---------- Logging ----------
|
| 13 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
@@ -29,12 +28,11 @@ GITHUB_API = "https://api.github.com"
|
|
| 29 |
BALE_API = f"https://tapi.bale.ai/bot{BALE_TOKEN}/"
|
| 30 |
DB_FILE = "subscriptions.db"
|
| 31 |
|
| 32 |
-
# GitHub API headers
|
| 33 |
github_headers = {"Accept": "application/vnd.github.v3+json"}
|
| 34 |
if GITHUB_TOKEN:
|
| 35 |
github_headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
|
| 36 |
|
| 37 |
-
# ---------- Database
|
| 38 |
def init_db():
|
| 39 |
conn = sqlite3.connect(DB_FILE)
|
| 40 |
c = conn.cursor()
|
|
@@ -124,14 +122,8 @@ async def send_message(chat_id, text, reply_markup=None):
|
|
| 124 |
return await bale_request("sendMessage", params)
|
| 125 |
|
| 126 |
async def send_document_file(chat_id, file_path, caption=""):
|
| 127 |
-
"""
|
| 128 |
-
Upload a local file to Bale using sendDocument with multipart/form-data.
|
| 129 |
-
"""
|
| 130 |
url = BALE_API + "sendDocument"
|
| 131 |
-
data = {
|
| 132 |
-
"chat_id": str(chat_id),
|
| 133 |
-
"caption": caption
|
| 134 |
-
}
|
| 135 |
async with aiohttp.ClientSession() as session:
|
| 136 |
with open(file_path, "rb") as f:
|
| 137 |
form = aiohttp.FormData()
|
|
@@ -171,21 +163,17 @@ def build_inline_keyboard(release: dict):
|
|
| 171 |
|
| 172 |
# ---------- File download helper ----------
|
| 173 |
async def download_file(url, dest_path):
|
| 174 |
-
"""
|
| 175 |
-
Download a file from a URL to a local path, using a real User-Agent.
|
| 176 |
-
"""
|
| 177 |
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 178 |
async with aiohttp.ClientSession(headers=headers) as session:
|
| 179 |
async with session.get(url) as resp:
|
| 180 |
if resp.status != 200:
|
| 181 |
raise Exception(f"Download failed with status {resp.status}")
|
| 182 |
-
# Stream to file using a thread to avoid blocking the event loop
|
| 183 |
with open(dest_path, "wb") as f:
|
| 184 |
while True:
|
| 185 |
chunk = await resp.content.read(8192)
|
| 186 |
if not chunk:
|
| 187 |
break
|
| 188 |
-
# Write synchronously (small chunks, fine)
|
| 189 |
f.write(chunk)
|
| 190 |
logger.info(f"β
Downloaded file to {dest_path}")
|
| 191 |
|
|
@@ -243,19 +231,48 @@ async def handle_callback(callback: dict):
|
|
| 243 |
|
| 244 |
if data.startswith("dl:"):
|
| 245 |
url = data[3:]
|
| 246 |
-
logger.info(f"β¬οΈ
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
-
# Create a temporary file
|
| 249 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".apk")
|
| 250 |
try:
|
| 251 |
await download_file(url, tmp.name)
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
except Exception as e:
|
| 255 |
-
logger.error(f"β
|
| 256 |
-
await
|
|
|
|
| 257 |
finally:
|
| 258 |
-
# Clean up the temp file
|
| 259 |
try:
|
| 260 |
os.unlink(tmp.name)
|
| 261 |
except:
|
|
@@ -291,7 +308,7 @@ async def poll_updates():
|
|
| 291 |
logger.error(f"Polling error: {e}", exc_info=True)
|
| 292 |
await asyncio.sleep(5)
|
| 293 |
|
| 294 |
-
# ---------- Release poller
|
| 295 |
async def release_poller():
|
| 296 |
logger.info("π Release poller started")
|
| 297 |
while True:
|
|
|
|
| 7 |
import aiohttp
|
| 8 |
import logging
|
| 9 |
import tempfile
|
|
|
|
| 10 |
|
| 11 |
# ---------- Logging ----------
|
| 12 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
|
|
| 28 |
BALE_API = f"https://tapi.bale.ai/bot{BALE_TOKEN}/"
|
| 29 |
DB_FILE = "subscriptions.db"
|
| 30 |
|
|
|
|
| 31 |
github_headers = {"Accept": "application/vnd.github.v3+json"}
|
| 32 |
if GITHUB_TOKEN:
|
| 33 |
github_headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
|
| 34 |
|
| 35 |
+
# ---------- Database ----------
|
| 36 |
def init_db():
|
| 37 |
conn = sqlite3.connect(DB_FILE)
|
| 38 |
c = conn.cursor()
|
|
|
|
| 122 |
return await bale_request("sendMessage", params)
|
| 123 |
|
| 124 |
async def send_document_file(chat_id, file_path, caption=""):
|
| 125 |
+
"""Upload a local file to Bale using sendDocument with multipart/form-data."""
|
|
|
|
|
|
|
| 126 |
url = BALE_API + "sendDocument"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
async with aiohttp.ClientSession() as session:
|
| 128 |
with open(file_path, "rb") as f:
|
| 129 |
form = aiohttp.FormData()
|
|
|
|
| 163 |
|
| 164 |
# ---------- File download helper ----------
|
| 165 |
async def download_file(url, dest_path):
|
| 166 |
+
"""Download a file from a URL to a local path with a real User-Agent."""
|
|
|
|
|
|
|
| 167 |
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
|
| 168 |
async with aiohttp.ClientSession(headers=headers) as session:
|
| 169 |
async with session.get(url) as resp:
|
| 170 |
if resp.status != 200:
|
| 171 |
raise Exception(f"Download failed with status {resp.status}")
|
|
|
|
| 172 |
with open(dest_path, "wb") as f:
|
| 173 |
while True:
|
| 174 |
chunk = await resp.content.read(8192)
|
| 175 |
if not chunk:
|
| 176 |
break
|
|
|
|
| 177 |
f.write(chunk)
|
| 178 |
logger.info(f"β
Downloaded file to {dest_path}")
|
| 179 |
|
|
|
|
| 231 |
|
| 232 |
if data.startswith("dl:"):
|
| 233 |
url = data[3:]
|
| 234 |
+
logger.info(f"β¬οΈ Preparing to download: {url}")
|
| 235 |
+
|
| 236 |
+
# Send initial status message
|
| 237 |
+
status_msg = await send_message(chat_id, "β³ Downloading file from GitHub...")
|
| 238 |
+
status_message_id = status_msg.get("result", {}).get("message_id") if status_msg.get("ok") else None
|
| 239 |
|
|
|
|
| 240 |
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".apk")
|
| 241 |
try:
|
| 242 |
await download_file(url, tmp.name)
|
| 243 |
+
|
| 244 |
+
# Report downloaded size
|
| 245 |
+
file_size = os.path.getsize(tmp.name)
|
| 246 |
+
size_mb = file_size / (1024 * 1024)
|
| 247 |
+
logger.info(f"β
Downloaded: {size_mb:.2f} MB")
|
| 248 |
+
|
| 249 |
+
if status_message_id:
|
| 250 |
+
await bale_request("editMessageText", {
|
| 251 |
+
"chat_id": chat_id,
|
| 252 |
+
"message_id": status_message_id,
|
| 253 |
+
"text": f"π₯ Downloaded {size_mb:.2f} MB β uploading to Bale..."
|
| 254 |
+
})
|
| 255 |
+
else:
|
| 256 |
+
await send_message(chat_id, f"π₯ Downloaded {size_mb:.2f} MB β uploading to Bale...")
|
| 257 |
+
|
| 258 |
+
# Upload to Bale
|
| 259 |
+
result = await send_document_file(chat_id, tmp.name, caption="Here you go!")
|
| 260 |
+
if result.get("ok"):
|
| 261 |
+
# Delete the status message on success
|
| 262 |
+
if status_message_id:
|
| 263 |
+
await bale_request("deleteMessage", {
|
| 264 |
+
"chat_id": chat_id,
|
| 265 |
+
"message_id": status_message_id
|
| 266 |
+
})
|
| 267 |
+
await answer_callback(callback_id, "Sent!")
|
| 268 |
+
else:
|
| 269 |
+
await send_message(chat_id, f"β Upload failed: {result.get('description')}")
|
| 270 |
+
await answer_callback(callback_id, "Failed to send.")
|
| 271 |
except Exception as e:
|
| 272 |
+
logger.error(f"β Download/Upload error: {e}", exc_info=True)
|
| 273 |
+
await send_message(chat_id, f"β Error: {e}")
|
| 274 |
+
await answer_callback(callback_id, "Failed.")
|
| 275 |
finally:
|
|
|
|
| 276 |
try:
|
| 277 |
os.unlink(tmp.name)
|
| 278 |
except:
|
|
|
|
| 308 |
logger.error(f"Polling error: {e}", exc_info=True)
|
| 309 |
await asyncio.sleep(5)
|
| 310 |
|
| 311 |
+
# ---------- Release poller ----------
|
| 312 |
async def release_poller():
|
| 313 |
logger.info("π Release poller started")
|
| 314 |
while True:
|