nvd commited on
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -6,6 +6,8 @@ import asyncio
|
|
| 6 |
import sqlite3
|
| 7 |
import aiohttp
|
| 8 |
import logging
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# ---------- Logging ----------
|
| 11 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
@@ -32,7 +34,7 @@ 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()
|
|
@@ -103,41 +105,45 @@ async def fetch_latest_release(owner: str, repo: str, prefer_prerelease: bool =
|
|
| 103 |
|
| 104 |
# ---------- Bale API helpers ----------
|
| 105 |
async def bale_request(method: str, params: dict = None):
|
| 106 |
-
"""Send a request to the Bale Bot API."""
|
| 107 |
url = BALE_API + method
|
| 108 |
async with aiohttp.ClientSession() as session:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
else:
|
| 114 |
-
async with session.post(url, data=params) as resp:
|
| 115 |
-
return await resp.json()
|
| 116 |
|
| 117 |
async def send_message(chat_id, text, reply_markup=None):
|
| 118 |
-
"""Send a text message, optionally with an inline keyboard."""
|
| 119 |
params = {
|
| 120 |
"chat_id": chat_id,
|
| 121 |
"text": text,
|
| 122 |
"parse_mode": "Markdown"
|
| 123 |
}
|
| 124 |
if reply_markup:
|
| 125 |
-
# The API requires reply_markup to be a JSON-encoded string
|
| 126 |
-
# when sending as form-data.
|
| 127 |
params["reply_markup"] = json.dumps(reply_markup)
|
| 128 |
return await bale_request("sendMessage", params)
|
| 129 |
|
| 130 |
-
async def
|
| 131 |
-
"""
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
| 135 |
"caption": caption
|
| 136 |
}
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
async def answer_callback(callback_id, text=""):
|
| 140 |
-
"""Acknowledge a callback query."""
|
| 141 |
params = {
|
| 142 |
"callback_query_id": callback_id,
|
| 143 |
"text": text
|
|
@@ -145,7 +151,6 @@ async def answer_callback(callback_id, text=""):
|
|
| 145 |
return await bale_request("answerCallbackQuery", params)
|
| 146 |
|
| 147 |
def build_inline_keyboard(release: dict):
|
| 148 |
-
"""Build an inline keyboard markup from release assets."""
|
| 149 |
assets = release.get("assets", [])
|
| 150 |
if not assets:
|
| 151 |
return None
|
|
@@ -164,12 +169,30 @@ def build_inline_keyboard(release: dict):
|
|
| 164 |
buttons.append(row)
|
| 165 |
return {"inline_keyboard": buttons}
|
| 166 |
|
| 167 |
-
# ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
async def handle_message(message: dict):
|
| 169 |
-
"""Process an incoming message."""
|
| 170 |
chat_id = message["chat"]["id"]
|
| 171 |
text = message.get("text", "").strip()
|
| 172 |
-
|
| 173 |
if "github.com/" in text and not text.startswith("/"):
|
| 174 |
await handle_on_demand(chat_id, text)
|
| 175 |
elif text.startswith("/watch"):
|
|
@@ -213,18 +236,35 @@ async def handle_watch(chat_id: int, text: str):
|
|
| 213 |
await send_message(chat_id, f"โ
Now watching {owner}/{repo} for new releases.\nLatest release: {rel['name']}")
|
| 214 |
|
| 215 |
async def handle_callback(callback: dict):
|
| 216 |
-
"""Process an inline button press."""
|
| 217 |
callback_id = callback["id"]
|
| 218 |
chat_id = callback["message"]["chat"]["id"]
|
| 219 |
data = callback.get("data", "")
|
|
|
|
|
|
|
| 220 |
if data.startswith("dl:"):
|
| 221 |
url = data[3:]
|
| 222 |
-
|
| 223 |
-
await answer_callback(callback_id, "Sent!")
|
| 224 |
|
| 225 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
async def poll_updates():
|
| 227 |
-
"""Long-poll for updates from Bale."""
|
| 228 |
offset = 0
|
| 229 |
logger.info("๐ Starting update polling...")
|
| 230 |
while True:
|
|
@@ -243,15 +283,16 @@ async def poll_updates():
|
|
| 243 |
logger.info(f"๐ฉ Message from {update['message']['chat']['id']}: {update['message'].get('text', '[no text]')[:100]}")
|
| 244 |
await handle_message(update["message"])
|
| 245 |
elif "callback_query" in update:
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
| 248 |
except Exception as e:
|
| 249 |
-
logger.error(f"Polling error: {e}")
|
| 250 |
await asyncio.sleep(5)
|
| 251 |
|
| 252 |
-
# ---------- Release poller (
|
| 253 |
async def release_poller():
|
| 254 |
-
"""Periodically check watched repos and notify subscribers."""
|
| 255 |
logger.info("๐ Release poller started")
|
| 256 |
while True:
|
| 257 |
try:
|
|
@@ -277,12 +318,10 @@ async def release_poller():
|
|
| 277 |
except Exception as e:
|
| 278 |
logger.error(f"Failed to notify {cid}: {e}")
|
| 279 |
except Exception as e:
|
| 280 |
-
logger.error(f"Release poller error: {e}")
|
| 281 |
-
await asyncio.sleep(300)
|
| 282 |
|
| 283 |
-
# ---------- Entry point for local_run.py ----------
|
| 284 |
async def bot_main():
|
| 285 |
-
"""Start polling for updates and the release poller concurrently."""
|
| 286 |
init_db()
|
| 287 |
await asyncio.gather(
|
| 288 |
poll_updates(),
|
|
|
|
| 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")
|
|
|
|
| 34 |
if GITHUB_TOKEN:
|
| 35 |
github_headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
|
| 36 |
|
| 37 |
+
# ---------- Database (unchanged) ----------
|
| 38 |
def init_db():
|
| 39 |
conn = sqlite3.connect(DB_FILE)
|
| 40 |
c = conn.cursor()
|
|
|
|
| 105 |
|
| 106 |
# ---------- Bale API helpers ----------
|
| 107 |
async def bale_request(method: str, params: dict = None):
|
| 108 |
+
"""Send a formโdata request to the Bale Bot API."""
|
| 109 |
url = BALE_API + method
|
| 110 |
async with aiohttp.ClientSession() as session:
|
| 111 |
+
async with session.post(url, data=params) as resp:
|
| 112 |
+
result = await resp.json()
|
| 113 |
+
logger.debug(f"API response for {method}: {result}")
|
| 114 |
+
return result
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
async def send_message(chat_id, text, reply_markup=None):
|
|
|
|
| 117 |
params = {
|
| 118 |
"chat_id": chat_id,
|
| 119 |
"text": text,
|
| 120 |
"parse_mode": "Markdown"
|
| 121 |
}
|
| 122 |
if reply_markup:
|
|
|
|
|
|
|
| 123 |
params["reply_markup"] = json.dumps(reply_markup)
|
| 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()
|
| 138 |
+
form.add_field("chat_id", str(chat_id))
|
| 139 |
+
form.add_field("caption", caption)
|
| 140 |
+
form.add_field("document", f, filename=os.path.basename(file_path))
|
| 141 |
+
async with session.post(url, data=form) as resp:
|
| 142 |
+
result = await resp.json()
|
| 143 |
+
logger.info(f"๐จ sendDocument (file) response: {result}")
|
| 144 |
+
return result
|
| 145 |
|
| 146 |
async def answer_callback(callback_id, text=""):
|
|
|
|
| 147 |
params = {
|
| 148 |
"callback_query_id": callback_id,
|
| 149 |
"text": text
|
|
|
|
| 151 |
return await bale_request("answerCallbackQuery", params)
|
| 152 |
|
| 153 |
def build_inline_keyboard(release: dict):
|
|
|
|
| 154 |
assets = release.get("assets", [])
|
| 155 |
if not assets:
|
| 156 |
return None
|
|
|
|
| 169 |
buttons.append(row)
|
| 170 |
return {"inline_keyboard": buttons}
|
| 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 |
+
|
| 192 |
+
# ---------- Message / Callback handlers ----------
|
| 193 |
async def handle_message(message: dict):
|
|
|
|
| 194 |
chat_id = message["chat"]["id"]
|
| 195 |
text = message.get("text", "").strip()
|
|
|
|
| 196 |
if "github.com/" in text and not text.startswith("/"):
|
| 197 |
await handle_on_demand(chat_id, text)
|
| 198 |
elif text.startswith("/watch"):
|
|
|
|
| 236 |
await send_message(chat_id, f"โ
Now watching {owner}/{repo} for new releases.\nLatest release: {rel['name']}")
|
| 237 |
|
| 238 |
async def handle_callback(callback: dict):
|
|
|
|
| 239 |
callback_id = callback["id"]
|
| 240 |
chat_id = callback["message"]["chat"]["id"]
|
| 241 |
data = callback.get("data", "")
|
| 242 |
+
logger.info(f"๐ Callback received: data='{data}', chat_id={chat_id}")
|
| 243 |
+
|
| 244 |
if data.startswith("dl:"):
|
| 245 |
url = data[3:]
|
| 246 |
+
logger.info(f"โฌ๏ธ Downloading file from URL: {url}")
|
|
|
|
| 247 |
|
| 248 |
+
# Create a temporary file
|
| 249 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".apk")
|
| 250 |
+
try:
|
| 251 |
+
await download_file(url, tmp.name)
|
| 252 |
+
await send_document_file(chat_id, tmp.name, caption="Here you go!")
|
| 253 |
+
await answer_callback(callback_id, "Sent!")
|
| 254 |
+
except Exception as e:
|
| 255 |
+
logger.error(f"โ Error sending file: {e}", exc_info=True)
|
| 256 |
+
await answer_callback(callback_id, "Failed to send file.")
|
| 257 |
+
finally:
|
| 258 |
+
# Clean up the temp file
|
| 259 |
+
try:
|
| 260 |
+
os.unlink(tmp.name)
|
| 261 |
+
except:
|
| 262 |
+
pass
|
| 263 |
+
else:
|
| 264 |
+
await answer_callback(callback_id, "Unknown action.")
|
| 265 |
+
|
| 266 |
+
# ---------- Polling ----------
|
| 267 |
async def poll_updates():
|
|
|
|
| 268 |
offset = 0
|
| 269 |
logger.info("๐ Starting update polling...")
|
| 270 |
while True:
|
|
|
|
| 283 |
logger.info(f"๐ฉ Message from {update['message']['chat']['id']}: {update['message'].get('text', '[no text]')[:100]}")
|
| 284 |
await handle_message(update["message"])
|
| 285 |
elif "callback_query" in update:
|
| 286 |
+
try:
|
| 287 |
+
await handle_callback(update["callback_query"])
|
| 288 |
+
except Exception as e:
|
| 289 |
+
logger.error(f"โ Error in callback handler: {e}", exc_info=True)
|
| 290 |
except Exception as e:
|
| 291 |
+
logger.error(f"Polling error: {e}", exc_info=True)
|
| 292 |
await asyncio.sleep(5)
|
| 293 |
|
| 294 |
+
# ---------- Release poller (unchanged) ----------
|
| 295 |
async def release_poller():
|
|
|
|
| 296 |
logger.info("๐ Release poller started")
|
| 297 |
while True:
|
| 298 |
try:
|
|
|
|
| 318 |
except Exception as e:
|
| 319 |
logger.error(f"Failed to notify {cid}: {e}")
|
| 320 |
except Exception as e:
|
| 321 |
+
logger.error(f"Release poller error: {e}", exc_info=True)
|
| 322 |
+
await asyncio.sleep(300)
|
| 323 |
|
|
|
|
| 324 |
async def bot_main():
|
|
|
|
| 325 |
init_db()
|
| 326 |
await asyncio.gather(
|
| 327 |
poll_updates(),
|