nvd commited on
Commit
e4f86d4
Β·
verified Β·
1 Parent(s): 3ffc9ec

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +29 -24
bot.py CHANGED
@@ -4,6 +4,7 @@ import re
4
  import asyncio
5
  import sqlite3
6
  import aiohttp
 
7
  from bale import Bot, Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
8
 
9
  # ---------- Import hardcoded tokens ----------
@@ -94,8 +95,6 @@ def build_asset_keyboard(release: dict):
94
  assets = release.get("assets", [])
95
  if not assets:
96
  return None
97
-
98
- # Create a list of rows, each row is a list of InlineKeyboardButton
99
  keyboard_rows = []
100
  row = []
101
  for i, asset in enumerate(assets):
@@ -107,9 +106,8 @@ def build_asset_keyboard(release: dict):
107
  if len(row) == 2:
108
  keyboard_rows.append(row)
109
  row = []
110
- if row: # leftover button
111
  keyboard_rows.append(row)
112
-
113
  return InlineKeyboardMarkup(keyboard_rows)
114
 
115
  # ---------- Bot instance ----------
@@ -119,11 +117,8 @@ bot = Bot(token=BALE_TOKEN)
119
  @bot.event
120
  async def on_message(message: Message):
121
  text = message.content.strip()
122
-
123
- # Mode 1: On-demand – any message containing a GitHub repo URL
124
  if "github.com/" in text and not text.startswith("/"):
125
  await handle_on_demand(message, text)
126
- # Mode 2: Subscription – /watch command
127
  elif text.startswith("/watch"):
128
  await handle_watch(message, text)
129
  else:
@@ -143,10 +138,7 @@ async def handle_on_demand(message: Message, url: str):
143
  return
144
  markup = build_asset_keyboard(release)
145
  if markup:
146
- await message.reply(
147
- f"πŸ“¦ *{release['name']}* – Choose an asset:",
148
- reply_markup=markup
149
- )
150
  else:
151
  await message.reply("No assets found in the latest release.")
152
 
@@ -160,7 +152,6 @@ async def handle_watch(message: Message, text: str):
160
  if not owner:
161
  await message.reply("Invalid GitHub URL.")
162
  return
163
- # Quick check that the repo exists and has releases
164
  rel = await fetch_latest_release(owner, repo)
165
  if not rel:
166
  await message.reply("Could not access releases. The repo might be private or have no releases.")
@@ -174,7 +165,6 @@ async def on_callback(callback: CallbackQuery):
174
  if data.startswith("dl:"):
175
  url = data[3:]
176
  await callback.message.reply("⏳ Downloading file …")
177
- # The library supports sending a file via a direct URL
178
  await bot.send_document(
179
  chat_id=callback.message.chat.id,
180
  document=url,
@@ -182,7 +172,7 @@ async def on_callback(callback: CallbackQuery):
182
  )
183
  await callback.answer("Sent!")
184
 
185
- # ---------- Background poller for subscriptions ----------
186
  async def release_poller():
187
  while True:
188
  repos = get_all_distinct_repos()
@@ -207,15 +197,30 @@ async def release_poller():
207
  )
208
  except Exception as e:
209
  print(f"Failed to notify {cid}: {e}")
210
- await asyncio.sleep(300) # 5 minutes
 
 
 
 
 
 
 
211
 
212
- # ---------- Startup function for Hugging Face ----------
213
- async def start_bot(status_callback=None):
214
  init_db()
215
- if status_callback:
216
- status_callback("🟒 Bot is online and polling GitHub for subscriptions.")
217
- # Use start_polling() instead of run() – it’s a coroutine that works inside an existing event loop
218
- await asyncio.gather(
219
- bot.start_polling(),
220
- release_poller()
221
- )
 
 
 
 
 
 
 
 
 
4
  import asyncio
5
  import sqlite3
6
  import aiohttp
7
+ import threading
8
  from bale import Bot, Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
9
 
10
  # ---------- Import hardcoded tokens ----------
 
95
  assets = release.get("assets", [])
96
  if not assets:
97
  return None
 
 
98
  keyboard_rows = []
99
  row = []
100
  for i, asset in enumerate(assets):
 
106
  if len(row) == 2:
107
  keyboard_rows.append(row)
108
  row = []
109
+ if row:
110
  keyboard_rows.append(row)
 
111
  return InlineKeyboardMarkup(keyboard_rows)
112
 
113
  # ---------- Bot instance ----------
 
117
  @bot.event
118
  async def on_message(message: Message):
119
  text = message.content.strip()
 
 
120
  if "github.com/" in text and not text.startswith("/"):
121
  await handle_on_demand(message, text)
 
122
  elif text.startswith("/watch"):
123
  await handle_watch(message, text)
124
  else:
 
138
  return
139
  markup = build_asset_keyboard(release)
140
  if markup:
141
+ await message.reply(f"πŸ“¦ *{release['name']}* – Choose an asset:", reply_markup=markup)
 
 
 
142
  else:
143
  await message.reply("No assets found in the latest release.")
144
 
 
152
  if not owner:
153
  await message.reply("Invalid GitHub URL.")
154
  return
 
155
  rel = await fetch_latest_release(owner, repo)
156
  if not rel:
157
  await message.reply("Could not access releases. The repo might be private or have no releases.")
 
165
  if data.startswith("dl:"):
166
  url = data[3:]
167
  await callback.message.reply("⏳ Downloading file …")
 
168
  await bot.send_document(
169
  chat_id=callback.message.chat.id,
170
  document=url,
 
172
  )
173
  await callback.answer("Sent!")
174
 
175
+ # ---------- Background poller ----------
176
  async def release_poller():
177
  while True:
178
  repos = get_all_distinct_repos()
 
197
  )
198
  except Exception as e:
199
  print(f"Failed to notify {cid}: {e}")
200
+ await asyncio.sleep(300)
201
+
202
+ # ---------- Combined async main for the bot's own thread ----------
203
+ async def combined_main():
204
+ # Use the internal polling method (private but necessary)
205
+ poll_task = asyncio.create_task(bot._start_polling())
206
+ poller_task = asyncio.create_task(release_poller())
207
+ await asyncio.gather(poll_task, poller_task)
208
 
209
+ def start_bot_thread():
210
+ """Runs the bot's event loop in a new thread."""
211
  init_db()
212
+ loop = asyncio.new_event_loop()
213
+ asyncio.set_event_loop(loop)
214
+ try:
215
+ loop.run_until_complete(combined_main())
216
+ except KeyboardInterrupt:
217
+ pass
218
+ finally:
219
+ loop.close()
220
+
221
+ # ---------- Public function called from app.py ----------
222
+ def start_bot():
223
+ """Launch the bot in a separate daemon thread."""
224
+ thread = threading.Thread(target=start_bot_thread, daemon=True)
225
+ thread.start()
226
+ print("🟒 Bot thread started.")