ops: installer asks for the subscription and bot token; first /start claims the bot

- install.sh prompts (hidden) for the VLESS subscription URL and the Telegram token on
  the first run, and picks Whisper base on VMs under 3.5 GB RAM.
- The owner chat no longer has to be looked up: whoever sends /start first becomes the
  owner (saved in the settings table); OWNER_CHAT_ID still overrides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-10 02:55:02 +03:00
parent 80990bbbcd
commit 14c1f740d9
4 changed files with 59 additions and 18 deletions
+27 -8
View File
@@ -49,14 +49,32 @@ def locked(fn, *a, **kw):
# MARK: - Telegram # MARK: - Telegram
def owner() -> int:
"""OWNER_CHAT_ID, or whoever sent /start first (saved in the database)."""
if CFG["owner"]:
return CFG["owner"]
with lock:
row = ops.con.execute("SELECT value FROM settings WHERE key = 'owner'").fetchone()
return int(row["value"]) if row else 0
def claim_owner(chat_id: int) -> bool:
with lock:
if CFG["owner"] or ops.con.execute("SELECT 1 FROM settings WHERE key = 'owner'").fetchone():
return False
ops.con.execute("INSERT INTO settings (key, value) VALUES ('owner', ?)", (str(chat_id),))
log.info("owner claimed: %s", chat_id)
return True
def owner_only(handler): def owner_only(handler):
async def wrapped(update: Update, ctx: ContextTypes.DEFAULT_TYPE): async def wrapped(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
chat = update.effective_chat chat = update.effective_chat
if not chat or chat.id != CFG["owner"]: if chat and update.message and update.message.text == "/start" and claim_owner(chat.id):
await update.message.reply_text("Готово: этот чат — владелец бота. Чужим он отвечать не будет.")
if not chat or chat.id != owner():
if update.message and update.message.text == "/start": if update.message and update.message.text == "/start":
await update.message.reply_text( await update.message.reply_text("Это личный бот.")
f"Это личный бот. Твой chat id: {chat.id if chat else '?'} — "
"впиши его в OWNER_CHAT_ID на сервере и перезапусти службу.")
return return
await handler(update, ctx) await handler(update, ctx)
return wrapped return wrapped
@@ -151,7 +169,7 @@ def reminder_buttons(it: dict) -> InlineKeyboardMarkup:
async def on_button(update: Update, ctx): async def on_button(update: Update, ctx):
q = update.callback_query q = update.callback_query
if not q or q.message.chat.id != CFG["owner"]: if not q or q.message.chat.id != owner():
return return
action, kind, ref = q.data.split(":") action, kind, ref = q.data.split(":")
ref = int(ref) ref = int(ref)
@@ -183,7 +201,8 @@ async def reminder_loop(bot):
while True: while True:
try: try:
now = datetime.now(ops.tz) now = datetime.now(ops.tz)
if CFG["owner"] and CFG["digest_hour"] <= now.hour < CFG["quiet_from"]: chat = owner()
if chat and CFG["digest_hour"] <= now.hour < CFG["quiet_from"]:
with lock: with lock:
digest_due = not ops.con.execute( digest_due = not ops.con.execute(
"SELECT 1 FROM reminders_sent WHERE kind = 'digest' AND day = ?", "SELECT 1 FROM reminders_sent WHERE kind = 'digest' AND day = ?",
@@ -191,12 +210,12 @@ async def reminder_loop(bot):
agenda = ops.agenda() if digest_due else None agenda = ops.agenda() if digest_due else None
items = ops.due_reminders() items = ops.due_reminders()
if digest_due: if digest_due:
await bot.send_message(CFG["owner"], "☀️ Доброе утро! " + fmt.agenda(agenda), await bot.send_message(chat, "☀️ Доброе утро! " + fmt.agenda(agenda),
parse_mode=ParseMode.HTML) parse_mode=ParseMode.HTML)
locked(ops.mark_reminded, "digest", 0) locked(ops.mark_reminded, "digest", 0)
today = ops.today() today = ops.today()
for it in items: for it in items:
await bot.send_message(CFG["owner"], "Напоминание: " + fmt.item_line(it, today), await bot.send_message(chat, "Напоминание: " + fmt.item_line(it, today),
parse_mode=ParseMode.HTML, reply_markup=reminder_buttons(it)) parse_mode=ParseMode.HTML, reply_markup=reminder_buttons(it))
locked(ops.mark_reminded, it["kind"], it["id"]) locked(ops.mark_reminded, it["kind"], it["id"])
except Exception: except Exception:
+4
View File
@@ -52,6 +52,10 @@ CREATE TABLE IF NOT EXISTS routine_log (
done_on TEXT NOT NULL, done_on TEXT NOT NULL,
note TEXT NOT NULL DEFAULT '' note TEXT NOT NULL DEFAULT ''
); );
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS reminders_sent ( CREATE TABLE IF NOT EXISTS reminders_sent (
kind TEXT NOT NULL, -- task | sub | routine | digest kind TEXT NOT NULL, -- task | sub | routine | digest
ref INTEGER NOT NULL, ref INTEGER NOT NULL,
+1 -1
View File
@@ -2,7 +2,7 @@
# Telegram bot token from @BotFather (revoke and reissue if it was ever pasted anywhere). # Telegram bot token from @BotFather (revoke and reissue if it was ever pasted anywhere).
TELEGRAM_TOKEN= TELEGRAM_TOKEN=
# Your chat id: start the bot, send /start, it tells you the number. # Optional: fixed owner chat id. Empty = whoever sends /start first becomes the owner.
OWNER_CHAT_ID= OWNER_CHAT_ID=
# Token BroV uses for the API (install.sh generates one). # Token BroV uses for the API (install.sh generates one).
+27 -9
View File
@@ -6,8 +6,8 @@
# /etc/brov-ops (root, 600). Telegram and Claude go through a local proxy core (mihomo in # /etc/brov-ops (root, 600). Telegram and Claude go through a local proxy core (mihomo in
# proxy mode on 127.0.0.1:7890 — only this service uses it, the VM itself is not tunnelled). # proxy mode on 127.0.0.1:7890 — only this service uses it, the VM itself is not tunnelled).
# #
# Before the first run put the VLESS subscription URL into /etc/brov-ops/proxy/vless.sub # Asks (hidden input) for the VLESS subscription URL and the Telegram bot token on the
# (one line). After it: fill /etc/brov-ops/config.env, log Claude in (printed at the end). # first run. The first person to send /start to the bot becomes its owner.
set -e set -e
[ "$(id -u)" -eq 0 ] || { echo "Запусти через sudo: sudo sh $0"; exit 1; } [ "$(id -u)" -eq 0 ] || { echo "Запусти через sudo: sudo sh $0"; exit 1; }
@@ -38,7 +38,15 @@ if [ "$(sha256sum /usr/local/bin/mihomo 2>/dev/null | cut -d' ' -f1)" != "$MIHOM
install -m 755 "$TMP/mihomo" /usr/local/bin/mihomo install -m 755 "$TMP/mihomo" /usr/local/bin/mihomo
rm -rf "$TMP" rm -rf "$TMP"
fi fi
[ -s $PROXY_DIR/vless.sub ] || { echo "✗ положи ссылку подписки VLESS в $PROXY_DIR/vless.sub и запусти снова"; exit 1; } ask_secret() { # prompt → stdout, input not echoed
printf "%s" "$1" > /dev/tty
stty -echo < /dev/tty; read -r v < /dev/tty; stty echo < /dev/tty; echo > /dev/tty
printf "%s" "$v"
}
if [ ! -s $PROXY_DIR/vless.sub ]; then
ask_secret "Ссылка подписки VLESS (ввод скрыт): " > $PROXY_DIR/vless.sub
[ -s $PROXY_DIR/vless.sub ] || { echo "✗ подписка не введена"; exit 1; }
fi
SUB=$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ') SUB=$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ')
umask 077 umask 077
cat > $PROXY_DIR/config.yaml <<EOF cat > $PROXY_DIR/config.yaml <<EOF
@@ -87,8 +95,19 @@ fi
echo "→ Настройки" echo "→ Настройки"
if [ ! -f $ETC/config.env ]; then if [ ! -f $ETC/config.env ]; then
# Whisper "small" needs ~1 GB on top of Claude: on a small VM take "base".
MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
WHISPER=small; [ "$MEM_MB" -lt 3500 ] && WHISPER=base
sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^CLAUDE_BIN=.*|CLAUDE_BIN=$CLAUDE|" \ sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^CLAUDE_BIN=.*|CLAUDE_BIN=$CLAUDE|" \
"$HERE/deploy/config.env.example" > $ETC/config.env -e "s|^WHISPER_MODEL=.*|WHISPER_MODEL=$WHISPER|" "$HERE/deploy/config.env.example" > $ETC/config.env
fi
if ! grep -q "^TELEGRAM_TOKEN=." $ETC/config.env; then
TOK=$(ask_secret "Токен бота от @BotFather (ввод скрыт): ")
if [ -n "$TOK" ]; then
grep -v "^TELEGRAM_TOKEN=" $ETC/config.env > $ETC/config.env.new
echo "TELEGRAM_TOKEN=$TOK" >> $ETC/config.env.new
mv $ETC/config.env.new $ETC/config.env
fi
fi fi
chown root:root $ETC/config.env chown root:root $ETC/config.env
chmod 600 $ETC/config.env # systemd reads it as root; the service only sees its variables chmod 600 $ETC/config.env # systemd reads it as root; the service only sees its variables
@@ -103,10 +122,9 @@ systemctl is-active --quiet brov-ops && echo "✓ brov-ops работает" ||
cat <<EOF cat <<EOF
Дальше (один раз): Дальше (один раз):
1. sudo nano $ETC/config.env — TELEGRAM_TOKEN (новый, после /revoke), потом OWNER_CHAT_ID 1. Войти в Claude под своей подпиской:
2. Войти в Claude под своей подпиской:
sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY $CLAUDE sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY $CLAUDE
(в нём /login, потом /exit) (в нём /login, потом /exit), затем: sudo systemctl restart brov-ops
3. sudo systemctl restart brov-ops 2. Написать боту /start — первый, кто напишет, станет владельцем.
Токен для BroV (API_TOKEN) — в $ETC/config.env. Токен для BroV (API_TOKEN): sudo grep API_TOKEN $ETC/config.env
EOF EOF