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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# bot.py
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import asyncio
|
| 5 |
+
import sqlite3
|
| 6 |
+
import aiohttp
|
| 7 |
+
from bale import Bot, Message, CallbackQuery, Components, InlineKeyboard
|
| 8 |
+
|
| 9 |
+
# ---------- Import hardcoded tokens ----------
|
| 10 |
+
try:
|
| 11 |
+
from config import BALE_BOT_TOKEN as BALE_TOKEN, GITHUB_TOKEN
|
| 12 |
+
except ImportError:
|
| 13 |
+
BALE_TOKEN = os.getenv("BALE_BOT_TOKEN")
|
| 14 |
+
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
|
| 15 |
+
|
| 16 |
+
GITHUB_API = "https://api.github.com"
|
| 17 |
+
DB_FILE = "subscriptions.db"
|
| 18 |
+
|
| 19 |
+
# GitHub API headers
|
| 20 |
+
headers = {"Accept": "application/vnd.github.v3+json"}
|
| 21 |
+
if GITHUB_TOKEN:
|
| 22 |
+
headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
|
| 23 |
+
|
| 24 |
+
# ---------- Database helpers ----------
|
| 25 |
+
def init_db():
|
| 26 |
+
conn = sqlite3.connect(DB_FILE)
|
| 27 |
+
c = conn.cursor()
|
| 28 |
+
c.execute("""
|
| 29 |
+
CREATE TABLE IF NOT EXISTS subscriptions (
|
| 30 |
+
chat_id TEXT NOT NULL,
|
| 31 |
+
repo_url TEXT NOT NULL,
|
| 32 |
+
last_tag TEXT,
|
| 33 |
+
PRIMARY KEY (chat_id, repo_url)
|
| 34 |
+
)
|
| 35 |
+
""")
|
| 36 |
+
conn.commit()
|
| 37 |
+
conn.close()
|
| 38 |
+
|
| 39 |
+
def add_subscription(chat_id: str, repo_url: str):
|
| 40 |
+
conn = sqlite3.connect(DB_FILE)
|
| 41 |
+
conn.execute(
|
| 42 |
+
"INSERT OR IGNORE INTO subscriptions (chat_id, repo_url) VALUES (?, ?)",
|
| 43 |
+
(chat_id, repo_url)
|
| 44 |
+
)
|
| 45 |
+
conn.commit()
|
| 46 |
+
conn.close()
|
| 47 |
+
|
| 48 |
+
def get_all_distinct_repos():
|
| 49 |
+
conn = sqlite3.connect(DB_FILE)
|
| 50 |
+
rows = conn.execute("SELECT DISTINCT repo_url FROM subscriptions").fetchall()
|
| 51 |
+
conn.close()
|
| 52 |
+
return [row[0] for row in rows]
|
| 53 |
+
|
| 54 |
+
def get_chats_to_notify(repo_url: str, new_tag: str):
|
| 55 |
+
conn = sqlite3.connect(DB_FILE)
|
| 56 |
+
rows = conn.execute(
|
| 57 |
+
"SELECT chat_id FROM subscriptions WHERE repo_url = ? AND (last_tag IS NULL OR last_tag != ?)",
|
| 58 |
+
(repo_url, new_tag)
|
| 59 |
+
).fetchall()
|
| 60 |
+
chat_ids = [row[0] for row in rows]
|
| 61 |
+
# Update tags for those chats
|
| 62 |
+
if chat_ids:
|
| 63 |
+
conn.executemany(
|
| 64 |
+
"UPDATE subscriptions SET last_tag = ? WHERE chat_id = ? AND repo_url = ?",
|
| 65 |
+
[(new_tag, cid, repo_url) for cid in chat_ids]
|
| 66 |
+
)
|
| 67 |
+
conn.commit()
|
| 68 |
+
conn.close()
|
| 69 |
+
return chat_ids
|
| 70 |
+
|
| 71 |
+
# ---------- GitHub helpers ----------
|
| 72 |
+
def parse_repo_url(url: str):
|
| 73 |
+
match = re.search(r"github\.com/(?P<owner>[^/]+)/(?P<repo>[^/]+)", url)
|
| 74 |
+
if not match:
|
| 75 |
+
return None, None
|
| 76 |
+
return match.group("owner"), match.group("repo")
|
| 77 |
+
|
| 78 |
+
async def fetch_latest_release(owner: str, repo: str, prefer_prerelease: bool = True):
|
| 79 |
+
url = f"{GITHUB_API}/repos/{owner}/{repo}/releases"
|
| 80 |
+
async with aiohttp.ClientSession(headers=headers) as session:
|
| 81 |
+
async with session.get(url) as resp:
|
| 82 |
+
if resp.status != 200:
|
| 83 |
+
return None
|
| 84 |
+
releases = await resp.json()
|
| 85 |
+
if not releases:
|
| 86 |
+
return None
|
| 87 |
+
if prefer_prerelease:
|
| 88 |
+
for rel in releases:
|
| 89 |
+
if rel.get("prerelease"):
|
| 90 |
+
return rel
|
| 91 |
+
return releases[0]
|
| 92 |
+
|
| 93 |
+
def build_asset_keyboard(release: dict):
|
| 94 |
+
assets = release.get("assets", [])
|
| 95 |
+
comp = Components()
|
| 96 |
+
for i, asset in enumerate(assets):
|
| 97 |
+
comp.add_inline_keyboard(
|
| 98 |
+
InlineKeyboard(
|
| 99 |
+
text=asset["name"][:30], # btn text
|
| 100 |
+
callback_data=f"dl:{asset['browser_download_url']}"
|
| 101 |
+
),
|
| 102 |
+
row=i // 2
|
| 103 |
+
)
|
| 104 |
+
return comp
|
| 105 |
+
|
| 106 |
+
# ---------- Bot instance ----------
|
| 107 |
+
bot = Bot(token=BALE_TOKEN)
|
| 108 |
+
|
| 109 |
+
# ---------- Handlers ----------
|
| 110 |
+
@bot.event
|
| 111 |
+
async def on_message(message: Message):
|
| 112 |
+
text = message.content.strip()
|
| 113 |
+
|
| 114 |
+
# Mode 1: On-demand β any message containing a GitHub repo URL
|
| 115 |
+
if "github.com/" in text and not text.startswith("/"):
|
| 116 |
+
await handle_on_demand(message, text)
|
| 117 |
+
# Mode 2: Subscription β /watch command
|
| 118 |
+
elif text.startswith("/watch"):
|
| 119 |
+
await handle_watch(message, text)
|
| 120 |
+
else:
|
| 121 |
+
await message.reply(
|
| 122 |
+
"Send me a GitHub release URL (e.g., https://github.com/owner/repo) and I'll let you choose an asset.\n"
|
| 123 |
+
"Or use /watch <repo_url> to get notified of new releases."
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
async def handle_on_demand(message: Message, url: str):
|
| 127 |
+
owner, repo = parse_repo_url(url)
|
| 128 |
+
if not owner:
|
| 129 |
+
await message.reply("That doesn't look like a valid GitHub URL.")
|
| 130 |
+
return
|
| 131 |
+
release = await fetch_latest_release(owner, repo)
|
| 132 |
+
if not release:
|
| 133 |
+
await message.reply("Could not fetch releases. The repo may be private or empty.")
|
| 134 |
+
return
|
| 135 |
+
comp = build_asset_keyboard(release)
|
| 136 |
+
if not comp:
|
| 137 |
+
await message.reply("No assets found in the latest release.")
|
| 138 |
+
else:
|
| 139 |
+
await message.reply(f"π¦ *{release['name']}* β Choose an asset:", components=comp)
|
| 140 |
+
|
| 141 |
+
async def handle_watch(message: Message, text: str):
|
| 142 |
+
parts = text.split(maxsplit=1)
|
| 143 |
+
if len(parts) < 2:
|
| 144 |
+
await message.reply("Usage: /watch <github_repo_url>")
|
| 145 |
+
return
|
| 146 |
+
repo_url = parts[1].strip()
|
| 147 |
+
owner, repo = parse_repo_url(repo_url)
|
| 148 |
+
if not owner:
|
| 149 |
+
await message.reply("Invalid GitHub URL.")
|
| 150 |
+
return
|
| 151 |
+
# Quick check
|
| 152 |
+
rel = await fetch_latest_release(owner, repo)
|
| 153 |
+
if not rel:
|
| 154 |
+
await message.reply("Could not access releases. The repo might be private or have no releases.")
|
| 155 |
+
return
|
| 156 |
+
add_subscription(str(message.chat.id), repo_url)
|
| 157 |
+
await message.reply(f"β
Now watching {owner}/{repo} for new releases.\nLatest release: {rel['name']}")
|
| 158 |
+
|
| 159 |
+
@bot.event
|
| 160 |
+
async def on_callback(callback: CallbackQuery):
|
| 161 |
+
data = callback.data
|
| 162 |
+
if data.startswith("dl:"):
|
| 163 |
+
url = data[3:]
|
| 164 |
+
await callback.message.reply("β³ Downloading file β¦")
|
| 165 |
+
await bot.send_document(
|
| 166 |
+
chat_id=callback.message.chat.id,
|
| 167 |
+
document=url,
|
| 168 |
+
caption="Here you go!"
|
| 169 |
+
)
|
| 170 |
+
await callback.answer("Sent!")
|
| 171 |
+
|
| 172 |
+
# ---------- Background poller for subscriptions ----------
|
| 173 |
+
async def release_poller(status_callback=None):
|
| 174 |
+
while True:
|
| 175 |
+
repos = get_all_distinct_repos()
|
| 176 |
+
for repo_url in repos:
|
| 177 |
+
owner, repo = parse_repo_url(repo_url)
|
| 178 |
+
if not owner:
|
| 179 |
+
continue
|
| 180 |
+
release = await fetch_latest_release(owner, repo)
|
| 181 |
+
if not release:
|
| 182 |
+
continue
|
| 183 |
+
new_tag = release["tag_name"]
|
| 184 |
+
chat_ids = get_chats_to_notify(repo_url, new_tag)
|
| 185 |
+
for cid in chat_ids:
|
| 186 |
+
comp = build_asset_keyboard(release)
|
| 187 |
+
try:
|
| 188 |
+
await bot.send_message(
|
| 189 |
+
chat_id=int(cid),
|
| 190 |
+
text=f"π New release for {owner}/{repo}: *{release['name']}*",
|
| 191 |
+
components=comp
|
| 192 |
+
)
|
| 193 |
+
except Exception as e:
|
| 194 |
+
print(f"Failed to notify {cid}: {e}")
|
| 195 |
+
await asyncio.sleep(300) # 5 minutes
|
| 196 |
+
|
| 197 |
+
# ---------- Startup function for Hugging Face ----------
|
| 198 |
+
async def start_bot(status_callback=None):
|
| 199 |
+
init_db()
|
| 200 |
+
if status_callback:
|
| 201 |
+
status_callback("π’ Bot is online and polling GitHub for subscriptions.")
|
| 202 |
+
# Run the bot (blocking) and the poller concurrently
|
| 203 |
+
await asyncio.gather(
|
| 204 |
+
bot.run(), # This blocks forever
|
| 205 |
+
release_poller() # Runs alongside bot.run()
|
| 206 |
+
)
|