nvd commited on
Update bot.py
Browse files
bot.py
CHANGED
|
@@ -4,16 +4,13 @@ import re
|
|
| 4 |
import asyncio
|
| 5 |
import sqlite3
|
| 6 |
import aiohttp
|
| 7 |
-
import threading
|
| 8 |
import logging
|
| 9 |
-
import traceback
|
| 10 |
-
from bale import Bot, Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
|
| 11 |
|
| 12 |
-
#
|
| 13 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
-
# ---------- Import
|
| 17 |
try:
|
| 18 |
from config import BALE_BOT_TOKEN as BALE_TOKEN, GITHUB_TOKEN
|
| 19 |
logger.info("Tokens loaded from config.py")
|
|
@@ -23,21 +20,18 @@ except ImportError:
|
|
| 23 |
logger.info("Tokens loaded from environment variables")
|
| 24 |
|
| 25 |
if not BALE_TOKEN:
|
| 26 |
-
|
| 27 |
-
raise ValueError("BALE_BOT_TOKEN missing")
|
| 28 |
|
| 29 |
GITHUB_API = "https://api.github.com"
|
|
|
|
| 30 |
DB_FILE = "subscriptions.db"
|
| 31 |
|
| 32 |
# GitHub API headers
|
| 33 |
-
|
| 34 |
if GITHUB_TOKEN:
|
| 35 |
-
|
| 36 |
-
logger.info("GitHub token provided β rate limit increased")
|
| 37 |
-
else:
|
| 38 |
-
logger.warning("No GitHub token β you may hit rate limits quickly")
|
| 39 |
|
| 40 |
-
# ---------- Database helpers ----------
|
| 41 |
def init_db():
|
| 42 |
conn = sqlite3.connect(DB_FILE)
|
| 43 |
c = conn.cursor()
|
|
@@ -51,7 +45,6 @@ def init_db():
|
|
| 51 |
""")
|
| 52 |
conn.commit()
|
| 53 |
conn.close()
|
| 54 |
-
logger.info("Database initialized")
|
| 55 |
|
| 56 |
def add_subscription(chat_id: str, repo_url: str):
|
| 57 |
conn = sqlite3.connect(DB_FILE)
|
|
@@ -93,10 +86,10 @@ def parse_repo_url(url: str):
|
|
| 93 |
|
| 94 |
async def fetch_latest_release(owner: str, repo: str, prefer_prerelease: bool = True):
|
| 95 |
url = f"{GITHUB_API}/repos/{owner}/{repo}/releases"
|
| 96 |
-
async with aiohttp.ClientSession(headers=
|
| 97 |
async with session.get(url) as resp:
|
| 98 |
if resp.status != 200:
|
| 99 |
-
logger.error(f"GitHub API error
|
| 100 |
return None
|
| 101 |
releases = await resp.json()
|
| 102 |
if not releases:
|
|
@@ -107,97 +100,155 @@ async def fetch_latest_release(owner: str, repo: str, prefer_prerelease: bool =
|
|
| 107 |
return rel
|
| 108 |
return releases[0]
|
| 109 |
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
assets = release.get("assets", [])
|
| 112 |
if not assets:
|
| 113 |
return None
|
| 114 |
-
|
| 115 |
row = []
|
| 116 |
for i, asset in enumerate(assets):
|
| 117 |
-
btn =
|
| 118 |
-
text
|
| 119 |
-
callback_data
|
| 120 |
-
|
| 121 |
row.append(btn)
|
| 122 |
if len(row) == 2:
|
| 123 |
-
|
| 124 |
row = []
|
| 125 |
if row:
|
| 126 |
-
|
| 127 |
-
return
|
| 128 |
|
| 129 |
-
# ----------
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
# ---------- Handlers (with logging) ----------
|
| 133 |
-
@bot.event
|
| 134 |
-
async def on_message(message: Message):
|
| 135 |
-
logger.info(f"π© Received message from {message.chat.id}: {message.content[:100]}")
|
| 136 |
-
text = message.content.strip()
|
| 137 |
if "github.com/" in text and not text.startswith("/"):
|
| 138 |
-
await handle_on_demand(
|
| 139 |
elif text.startswith("/watch"):
|
| 140 |
-
await handle_watch(
|
| 141 |
else:
|
| 142 |
-
await
|
| 143 |
"Send me a GitHub release URL (e.g., https://github.com/owner/repo) and I'll let you choose an asset.\n"
|
| 144 |
"Or use /watch <repo_url> to get notified of new releases."
|
| 145 |
)
|
| 146 |
|
| 147 |
-
async def handle_on_demand(
|
| 148 |
-
logger.info(f"βοΈ Handling on-demand request: {url}")
|
| 149 |
owner, repo = parse_repo_url(url)
|
| 150 |
if not owner:
|
| 151 |
-
await
|
| 152 |
return
|
| 153 |
release = await fetch_latest_release(owner, repo)
|
| 154 |
if not release:
|
| 155 |
-
await
|
| 156 |
return
|
| 157 |
-
|
| 158 |
-
if
|
| 159 |
-
await
|
| 160 |
else:
|
| 161 |
-
await
|
| 162 |
|
| 163 |
-
async def handle_watch(
|
| 164 |
parts = text.split(maxsplit=1)
|
| 165 |
if len(parts) < 2:
|
| 166 |
-
await
|
| 167 |
return
|
| 168 |
repo_url = parts[1].strip()
|
| 169 |
owner, repo = parse_repo_url(repo_url)
|
| 170 |
if not owner:
|
| 171 |
-
await
|
| 172 |
return
|
| 173 |
rel = await fetch_latest_release(owner, repo)
|
| 174 |
if not rel:
|
| 175 |
-
await
|
| 176 |
return
|
| 177 |
-
add_subscription(str(
|
| 178 |
-
await
|
| 179 |
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
| 184 |
if data.startswith("dl:"):
|
| 185 |
url = data[3:]
|
| 186 |
-
await
|
| 187 |
-
await
|
| 188 |
-
chat_id=callback.message.chat.id,
|
| 189 |
-
document=url,
|
| 190 |
-
caption="Here you go!"
|
| 191 |
-
)
|
| 192 |
-
await callback.answer("Sent!")
|
| 193 |
|
| 194 |
-
#
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
# ----------
|
| 200 |
async def release_poller():
|
|
|
|
| 201 |
logger.info("π Release poller started")
|
| 202 |
while True:
|
| 203 |
try:
|
|
@@ -215,49 +266,22 @@ async def release_poller():
|
|
| 215 |
chat_ids = get_chats_to_notify(repo_url, new_tag)
|
| 216 |
if not chat_ids:
|
| 217 |
continue
|
| 218 |
-
|
| 219 |
for cid in chat_ids:
|
| 220 |
try:
|
| 221 |
-
await
|
| 222 |
-
chat_id=int(cid),
|
| 223 |
-
text=f"π New release for {owner}/{repo}: *{release['name']}*",
|
| 224 |
-
reply_markup=markup
|
| 225 |
-
)
|
| 226 |
logger.info(f"π Notified {cid} about {repo_url}")
|
| 227 |
except Exception as e:
|
| 228 |
logger.error(f"Failed to notify {cid}: {e}")
|
| 229 |
except Exception as e:
|
| 230 |
logger.error(f"Release poller error: {e}")
|
| 231 |
-
await asyncio.sleep(300)
|
| 232 |
|
| 233 |
-
# ----------
|
| 234 |
async def bot_main():
|
| 235 |
-
"""
|
| 236 |
-
logger.info("π€ Starting bot polling and release poller...")
|
| 237 |
-
# The only reliable async starter for python-bale-bot is `_start_polling`
|
| 238 |
-
# We'll start both concurrently
|
| 239 |
-
tasks = [
|
| 240 |
-
asyncio.create_task(bot._start_polling()),
|
| 241 |
-
asyncio.create_task(release_poller())
|
| 242 |
-
]
|
| 243 |
-
await asyncio.gather(*tasks)
|
| 244 |
-
|
| 245 |
-
def start_bot_thread():
|
| 246 |
-
"""Runs the bot in a dedicated thread with its own event loop."""
|
| 247 |
init_db()
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
loop.run_until_complete(bot_main())
|
| 253 |
-
except Exception as e:
|
| 254 |
-
logger.critical(f"π₯ Bot thread crashed: {e}\n{traceback.format_exc()}")
|
| 255 |
-
finally:
|
| 256 |
-
loop.close()
|
| 257 |
-
logger.warning("π Bot thread event loop closed")
|
| 258 |
-
|
| 259 |
-
def start_bot():
|
| 260 |
-
"""Entry point β launches the bot thread."""
|
| 261 |
-
logger.info("π’ Starting bot in background thread...")
|
| 262 |
-
thread = threading.Thread(target=start_bot_thread, daemon=True)
|
| 263 |
-
thread.start()
|
|
|
|
| 4 |
import asyncio
|
| 5 |
import sqlite3
|
| 6 |
import aiohttp
|
|
|
|
| 7 |
import logging
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# ---------- Logging ----------
|
| 10 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
+
# ---------- Import tokens ----------
|
| 14 |
try:
|
| 15 |
from config import BALE_BOT_TOKEN as BALE_TOKEN, GITHUB_TOKEN
|
| 16 |
logger.info("Tokens loaded from config.py")
|
|
|
|
| 20 |
logger.info("Tokens loaded from environment variables")
|
| 21 |
|
| 22 |
if not BALE_TOKEN:
|
| 23 |
+
raise ValueError("β BALE_BOT_TOKEN not set!")
|
|
|
|
| 24 |
|
| 25 |
GITHUB_API = "https://api.github.com"
|
| 26 |
+
BALE_API = f"https://tapi.bale.ai/bot{BALE_TOKEN}/"
|
| 27 |
DB_FILE = "subscriptions.db"
|
| 28 |
|
| 29 |
# GitHub API headers
|
| 30 |
+
github_headers = {"Accept": "application/vnd.github.v3+json"}
|
| 31 |
if GITHUB_TOKEN:
|
| 32 |
+
github_headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# ---------- Database helpers (unchanged) ----------
|
| 35 |
def init_db():
|
| 36 |
conn = sqlite3.connect(DB_FILE)
|
| 37 |
c = conn.cursor()
|
|
|
|
| 45 |
""")
|
| 46 |
conn.commit()
|
| 47 |
conn.close()
|
|
|
|
| 48 |
|
| 49 |
def add_subscription(chat_id: str, repo_url: str):
|
| 50 |
conn = sqlite3.connect(DB_FILE)
|
|
|
|
| 86 |
|
| 87 |
async def fetch_latest_release(owner: str, repo: str, prefer_prerelease: bool = True):
|
| 88 |
url = f"{GITHUB_API}/repos/{owner}/{repo}/releases"
|
| 89 |
+
async with aiohttp.ClientSession(headers=github_headers) as session:
|
| 90 |
async with session.get(url) as resp:
|
| 91 |
if resp.status != 200:
|
| 92 |
+
logger.error(f"GitHub API error {resp.status} for {url}")
|
| 93 |
return None
|
| 94 |
releases = await resp.json()
|
| 95 |
if not releases:
|
|
|
|
| 100 |
return rel
|
| 101 |
return releases[0]
|
| 102 |
|
| 103 |
+
# ---------- Bale API helpers ----------
|
| 104 |
+
async def bale_request(method: str, params: dict = None):
|
| 105 |
+
"""Send a request to the Bale Bot API."""
|
| 106 |
+
url = BALE_API + method
|
| 107 |
+
async with aiohttp.ClientSession() as session:
|
| 108 |
+
if method == "sendDocument" and isinstance(params.get("document"), str):
|
| 109 |
+
# For file URL, we send as a JSON body
|
| 110 |
+
async with session.post(url, json=params) as resp:
|
| 111 |
+
return await resp.json()
|
| 112 |
+
else:
|
| 113 |
+
async with session.post(url, data=params) as resp:
|
| 114 |
+
return await resp.json()
|
| 115 |
+
|
| 116 |
+
async def send_message(chat_id, text, reply_markup=None):
|
| 117 |
+
"""Send a text message, optionally with an inline keyboard."""
|
| 118 |
+
params = {
|
| 119 |
+
"chat_id": chat_id,
|
| 120 |
+
"text": text,
|
| 121 |
+
"parse_mode": "Markdown"
|
| 122 |
+
}
|
| 123 |
+
if reply_markup:
|
| 124 |
+
params["reply_markup"] = reply_markup
|
| 125 |
+
return await bale_request("sendMessage", params)
|
| 126 |
+
|
| 127 |
+
async def send_document(chat_id, document_url, caption=""):
|
| 128 |
+
"""Send a document by URL (Bale downloads it directly)."""
|
| 129 |
+
params = {
|
| 130 |
+
"chat_id": chat_id,
|
| 131 |
+
"document": document_url,
|
| 132 |
+
"caption": caption
|
| 133 |
+
}
|
| 134 |
+
return await bale_request("sendDocument", params)
|
| 135 |
+
|
| 136 |
+
async def answer_callback(callback_id, text=""):
|
| 137 |
+
"""Acknowledge a callback query."""
|
| 138 |
+
params = {
|
| 139 |
+
"callback_query_id": callback_id,
|
| 140 |
+
"text": text
|
| 141 |
+
}
|
| 142 |
+
return await bale_request("answerCallbackQuery", params)
|
| 143 |
+
|
| 144 |
+
def build_inline_keyboard(release: dict):
|
| 145 |
+
"""Build an inline keyboard markup from release assets."""
|
| 146 |
assets = release.get("assets", [])
|
| 147 |
if not assets:
|
| 148 |
return None
|
| 149 |
+
buttons = []
|
| 150 |
row = []
|
| 151 |
for i, asset in enumerate(assets):
|
| 152 |
+
btn = {
|
| 153 |
+
"text": asset["name"][:30],
|
| 154 |
+
"callback_data": f"dl:{asset['browser_download_url']}"
|
| 155 |
+
}
|
| 156 |
row.append(btn)
|
| 157 |
if len(row) == 2:
|
| 158 |
+
buttons.append(row)
|
| 159 |
row = []
|
| 160 |
if row:
|
| 161 |
+
buttons.append(row)
|
| 162 |
+
return {"inline_keyboard": buttons}
|
| 163 |
|
| 164 |
+
# ---------- Message handling ----------
|
| 165 |
+
async def handle_message(message: dict):
|
| 166 |
+
"""Process an incoming message."""
|
| 167 |
+
chat_id = message["chat"]["id"]
|
| 168 |
+
text = message.get("text", "").strip()
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
if "github.com/" in text and not text.startswith("/"):
|
| 171 |
+
await handle_on_demand(chat_id, text)
|
| 172 |
elif text.startswith("/watch"):
|
| 173 |
+
await handle_watch(chat_id, text)
|
| 174 |
else:
|
| 175 |
+
await send_message(chat_id,
|
| 176 |
"Send me a GitHub release URL (e.g., https://github.com/owner/repo) and I'll let you choose an asset.\n"
|
| 177 |
"Or use /watch <repo_url> to get notified of new releases."
|
| 178 |
)
|
| 179 |
|
| 180 |
+
async def handle_on_demand(chat_id: int, url: str):
|
|
|
|
| 181 |
owner, repo = parse_repo_url(url)
|
| 182 |
if not owner:
|
| 183 |
+
await send_message(chat_id, "That doesn't look like a valid GitHub URL.")
|
| 184 |
return
|
| 185 |
release = await fetch_latest_release(owner, repo)
|
| 186 |
if not release:
|
| 187 |
+
await send_message(chat_id, "Could not fetch releases. The repo may be private or empty.")
|
| 188 |
return
|
| 189 |
+
keyboard = build_inline_keyboard(release)
|
| 190 |
+
if keyboard:
|
| 191 |
+
await send_message(chat_id, f"π¦ *{release['name']}* β Choose an asset:", reply_markup=keyboard)
|
| 192 |
else:
|
| 193 |
+
await send_message(chat_id, "No assets found in the latest release.")
|
| 194 |
|
| 195 |
+
async def handle_watch(chat_id: int, text: str):
|
| 196 |
parts = text.split(maxsplit=1)
|
| 197 |
if len(parts) < 2:
|
| 198 |
+
await send_message(chat_id, "Usage: /watch <github_repo_url>")
|
| 199 |
return
|
| 200 |
repo_url = parts[1].strip()
|
| 201 |
owner, repo = parse_repo_url(repo_url)
|
| 202 |
if not owner:
|
| 203 |
+
await send_message(chat_id, "Invalid GitHub URL.")
|
| 204 |
return
|
| 205 |
rel = await fetch_latest_release(owner, repo)
|
| 206 |
if not rel:
|
| 207 |
+
await send_message(chat_id, "Could not access releases. The repo might be private or have no releases.")
|
| 208 |
return
|
| 209 |
+
add_subscription(str(chat_id), repo_url)
|
| 210 |
+
await send_message(chat_id, f"β
Now watching {owner}/{repo} for new releases.\nLatest release: {rel['name']}")
|
| 211 |
|
| 212 |
+
async def handle_callback(callback: dict):
|
| 213 |
+
"""Process an inline button press."""
|
| 214 |
+
callback_id = callback["id"]
|
| 215 |
+
chat_id = callback["message"]["chat"]["id"]
|
| 216 |
+
data = callback.get("data", "")
|
| 217 |
if data.startswith("dl:"):
|
| 218 |
url = data[3:]
|
| 219 |
+
await send_document(chat_id, url, caption="Here you go!")
|
| 220 |
+
await answer_callback(callback_id, "Sent!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
+
# ---------- Polling loop ----------
|
| 223 |
+
async def poll_updates():
|
| 224 |
+
"""Long-poll for updates from Bale."""
|
| 225 |
+
offset = 0
|
| 226 |
+
logger.info("π Starting update polling...")
|
| 227 |
+
while True:
|
| 228 |
+
try:
|
| 229 |
+
params = {"offset": offset, "timeout": 30}
|
| 230 |
+
async with aiohttp.ClientSession() as session:
|
| 231 |
+
async with session.post(BALE_API + "getUpdates", data=params) as resp:
|
| 232 |
+
result = await resp.json()
|
| 233 |
+
if not result.get("ok"):
|
| 234 |
+
logger.error(f"getUpdates failed: {result}")
|
| 235 |
+
await asyncio.sleep(1)
|
| 236 |
+
continue
|
| 237 |
+
for update in result["result"]:
|
| 238 |
+
offset = update["update_id"] + 1
|
| 239 |
+
if "message" in update:
|
| 240 |
+
logger.info(f"π© Message from {update['message']['chat']['id']}: {update['message'].get('text', '[no text]')[:100]}")
|
| 241 |
+
await handle_message(update["message"])
|
| 242 |
+
elif "callback_query" in update:
|
| 243 |
+
logger.info(f"π Callback from {update['callback_query']['message']['chat']['id']}: {update['callback_query'].get('data', '')}")
|
| 244 |
+
await handle_callback(update["callback_query"])
|
| 245 |
+
except Exception as e:
|
| 246 |
+
logger.error(f"Polling error: {e}")
|
| 247 |
+
await asyncio.sleep(5)
|
| 248 |
|
| 249 |
+
# ---------- Release poller (subscription notifications) ----------
|
| 250 |
async def release_poller():
|
| 251 |
+
"""Periodically check watched repos and notify subscribers."""
|
| 252 |
logger.info("π Release poller started")
|
| 253 |
while True:
|
| 254 |
try:
|
|
|
|
| 266 |
chat_ids = get_chats_to_notify(repo_url, new_tag)
|
| 267 |
if not chat_ids:
|
| 268 |
continue
|
| 269 |
+
keyboard = build_inline_keyboard(release)
|
| 270 |
for cid in chat_ids:
|
| 271 |
try:
|
| 272 |
+
await send_message(int(cid), f"π New release for {owner}/{repo}: *{release['name']}*", reply_markup=keyboard)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
logger.info(f"π Notified {cid} about {repo_url}")
|
| 274 |
except Exception as e:
|
| 275 |
logger.error(f"Failed to notify {cid}: {e}")
|
| 276 |
except Exception as e:
|
| 277 |
logger.error(f"Release poller error: {e}")
|
| 278 |
+
await asyncio.sleep(300) # 5 minutes
|
| 279 |
|
| 280 |
+
# ---------- Entry point for local_run.py ----------
|
| 281 |
async def bot_main():
|
| 282 |
+
"""Start polling for updates and the release poller concurrently."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
init_db()
|
| 284 |
+
await asyncio.gather(
|
| 285 |
+
poll_updates(),
|
| 286 |
+
release_poller()
|
| 287 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|