feat: /help, /balance, inline-кнопки в Telegram

- /help — справка по командам с inline-кнопками
- /balance — баланс на бирже (USDC, BTC, etc.)
- /start → /help
- Inline keyboard: кнопки для всех команд
- Callback query handling для кнопок

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-09 06:38:34 +10:00
co-authored by Claude Opus 4.6
parent 38b02fd05b
commit 71466386ab
+99 -11
View File
@@ -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 <b>RemizovTrader — Команды</b>\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 <b>Баланс на бирже</b>", ""]
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" <b>{coin}:</b> {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)