diff --git a/ops/brovops/app.py b/ops/brovops/app.py index 2cd613e..e7309f7 100644 --- a/ops/brovops/app.py +++ b/ops/brovops/app.py @@ -49,14 +49,32 @@ def locked(fn, *a, **kw): # 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): async def wrapped(update: Update, ctx: ContextTypes.DEFAULT_TYPE): 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": - await update.message.reply_text( - f"Это личный бот. Твой chat id: {chat.id if chat else '?'} — " - "впиши его в OWNER_CHAT_ID на сервере и перезапусти службу.") + await update.message.reply_text("Это личный бот.") return await handler(update, ctx) return wrapped @@ -151,7 +169,7 @@ def reminder_buttons(it: dict) -> InlineKeyboardMarkup: async def on_button(update: Update, ctx): q = update.callback_query - if not q or q.message.chat.id != CFG["owner"]: + if not q or q.message.chat.id != owner(): return action, kind, ref = q.data.split(":") ref = int(ref) @@ -183,7 +201,8 @@ async def reminder_loop(bot): while True: try: 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: digest_due = not ops.con.execute( "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 items = ops.due_reminders() if digest_due: - await bot.send_message(CFG["owner"], "☀️ Доброе утро! " + fmt.agenda(agenda), + await bot.send_message(chat, "☀️ Доброе утро! " + fmt.agenda(agenda), parse_mode=ParseMode.HTML) locked(ops.mark_reminded, "digest", 0) today = ops.today() 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)) locked(ops.mark_reminded, it["kind"], it["id"]) except Exception: diff --git a/ops/brovops/db.py b/ops/brovops/db.py index 17016bc..53098cf 100644 --- a/ops/brovops/db.py +++ b/ops/brovops/db.py @@ -52,6 +52,10 @@ CREATE TABLE IF NOT EXISTS routine_log ( done_on TEXT NOT NULL, 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 ( kind TEXT NOT NULL, -- task | sub | routine | digest ref INTEGER NOT NULL, diff --git a/ops/deploy/config.env.example b/ops/deploy/config.env.example index ebd0a3d..cfdf828 100644 --- a/ops/deploy/config.env.example +++ b/ops/deploy/config.env.example @@ -2,7 +2,7 @@ # Telegram bot token from @BotFather (revoke and reissue if it was ever pasted anywhere). 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= # Token BroV uses for the API (install.sh generates one). diff --git a/ops/deploy/install.sh b/ops/deploy/install.sh index 3fa79b0..66c0f75 100644 --- a/ops/deploy/install.sh +++ b/ops/deploy/install.sh @@ -6,8 +6,8 @@ # /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). # -# Before the first run put the VLESS subscription URL into /etc/brov-ops/proxy/vless.sub -# (one line). After it: fill /etc/brov-ops/config.env, log Claude in (printed at the end). +# Asks (hidden input) for the VLESS subscription URL and the Telegram bot token on the +# first run. The first person to send /start to the bot becomes its owner. set -e [ "$(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 rm -rf "$TMP" 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 ') umask 077 cat > $PROXY_DIR/config.yaml < $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 chown root:root $ETC/config.env 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 <