From 71466386ab8c7822b0f09bb6b93cca0454b079ad Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 9 Mar 2026 06:38:34 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20/help,=20/balance,=20inline-=D0=BA?= =?UTF-8?q?=D0=BD=D0=BE=D0=BF=D0=BA=D0=B8=20=D0=B2=20Telegram?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /help — справка по командам с inline-кнопками - /balance — баланс на бирже (USDC, BTC, etc.) - /start → /help - Inline keyboard: кнопки для всех команд - Callback query handling для кнопок Co-Authored-By: Claude Opus 4.6 --- src/remizov_trader/cli.py | 110 ++++++++++++++++++++++++++++++++++---- 1 file changed, 99 insertions(+), 11 deletions(-) diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py index 302cd5b..24f41bc 100644 --- a/src/remizov_trader/cli.py +++ b/src/remizov_trader/cli.py @@ -247,8 +247,67 @@ def daemon(): send_status(cfg.telegram, "stop") +def _send_with_keyboard(cfg, text: str, keyboard=None): + """Send Telegram message with optional inline keyboard.""" + import httpx + url = f"https://api.telegram.org/bot{cfg.telegram.bot_token}/sendMessage" + payload = { + "chat_id": cfg.telegram.chat_id, + "text": text, + "parse_mode": "HTML", + } + if keyboard: + payload["reply_markup"] = {"inline_keyboard": keyboard} + try: + httpx.post(url, json=payload, timeout=10) + except Exception: + pass + + +def _send_help(cfg): + """Send help message with command buttons.""" + text = ( + "\U0001f916 RemizovTrader — Команды\n" + "\n" + "/status — портфель, позиции, статистика\n" + "/balance — баланс на бирже\n" + "/leverage — текущее плечо\n" + "/leverage N — установить плечо (1-10)\n" + "/help — эта справка" + ) + keyboard = [ + [{"text": "\U0001f4ca Статус", "callback_data": "/status"}, + {"text": "\U0001f4b0 Баланс", "callback_data": "/balance"}], + [{"text": "\u2696\ufe0f Плечо", "callback_data": "/leverage"}, + {"text": "\u2753 Помощь", "callback_data": "/help"}], + ] + _send_with_keyboard(cfg, text, keyboard) + + +def _send_balance(cfg): + """Fetch and send exchange balance.""" + try: + from .core.spot import SpotExecutor + spot = SpotExecutor(cfg.exchange, leverage=cfg.risk.leverage) + spot._ensure_markets() + b = spot.exchange.fetch_balance() + lines = ["\U0001f4b0 Баланс на бирже", ""] + for coin in ["USDC", "USDT", "BTC", "ETH", "SOL"]: + free = float(b.get(coin, {}).get("free", 0) or 0) + total = float(b.get(coin, {}).get("total", 0) or 0) + if total > 0.0001: + locked = total - free + lock_str = f" (заблокировано: {locked:.6f})" if locked > 0.0001 else "" + lines.append(f" {coin}: {free:.6f}{lock_str}") + from .notify import send_telegram + send_telegram(cfg.telegram, "\n".join(lines)) + except Exception as e: + from .notify import send_telegram + send_telegram(cfg.telegram, f"\u26a0\ufe0f Ошибка баланса: {e}") + + def _start_telegram_listener(cfg, get_db_fn): - """Poll Telegram for /status command in a background thread.""" + """Poll Telegram for commands in a background thread.""" import threading import time @@ -256,30 +315,59 @@ def _start_telegram_listener(cfg, get_db_fn): from .notify import format_status_report, send_telegram + def handle_command(text: str): + cmd = text.strip().split()[0].lower() + if cmd == "/status": + conn = get_db_fn() + report = format_status_report(cfg, conn) + conn.close() + send_telegram(cfg.telegram, report) + elif cmd == "/leverage": + _handle_leverage(cfg, text.strip(), send_telegram) + elif cmd == "/balance": + _send_balance(cfg) + elif cmd in ("/help", "/start"): + _send_help(cfg) + def poll_loop(): offset = 0 - url = f"https://api.telegram.org/bot{cfg.telegram.bot_token}/getUpdates" + base_url = f"https://api.telegram.org/bot{cfg.telegram.bot_token}" while True: try: - resp = httpx.get(url, params={"offset": offset, "timeout": 30}, timeout=35) + # Poll for both messages and callback queries (button presses) + resp = httpx.get(f"{base_url}/getUpdates", + params={"offset": offset, "timeout": 30, + "allowed_updates": '["message","callback_query"]'}, + timeout=35) if resp.status_code != 200: time.sleep(5) continue updates = resp.json().get("result", []) for upd in updates: offset = upd["update_id"] + 1 + + # Regular message msg = upd.get("message", {}) text = msg.get("text", "") chat_id = str(msg.get("chat", {}).get("id", "")) - if chat_id != cfg.telegram.chat_id: + if text and chat_id == cfg.telegram.chat_id: + handle_command(text) continue - if text.strip() == "/status": - conn = get_db_fn() - report = format_status_report(cfg, conn) - conn.close() - send_telegram(cfg.telegram, report) - elif text.strip().startswith("/leverage"): - _handle_leverage(cfg, text.strip(), send_telegram) + + # Callback query (inline button press) + cb = upd.get("callback_query", {}) + if cb: + cb_chat = str(cb.get("message", {}).get("chat", {}).get("id", "")) + cb_data = cb.get("data", "") + cb_id = cb.get("id", "") + if cb_chat == cfg.telegram.chat_id and cb_data: + # Answer callback to remove loading indicator + try: + httpx.post(f"{base_url}/answerCallbackQuery", + json={"callback_query_id": cb_id}, timeout=5) + except Exception: + pass + handle_command(cb_data) except Exception: time.sleep(10)