mirror of
https://github.com/laoxong/nofx.git
synced 2026-06-04 09:58:22 +08:00
9c5c976d9a
* feat(telegram): add AI agent bot with streaming and account context
- Add Telegram bot with long-polling and AI agent loop (api_call tool)
- SSE streaming with real-time message editing and ⏳ placeholder
- Account state injection at conversation start (models, exchanges,
strategies, traders, per-trader PnL and statistics)
- Lane semaphore per chat serializes concurrent messages (60s timeout)
- Idle timeout watchdog (60s) prevents hung streaming connections
- Look-ahead buffer prevents partial <api_call> tag leaking to user
- Fix PUT /strategies/:id to merge config (read-then-merge pattern)
- Add route registry with full API schema for LLM documentation
- Add TelegramConfig store and Web UI config modal
- Add GetAnyEnabled to AIModel store for bot LLM client selection
* fix(telegram): eliminate narration, add full-setup workflow and tests
- Rewrite NO NARRATION rule: response is EITHER api_call tag alone OR
final text reply — no text before api_call under any circumstances
- Ban all narration patterns: 现在我将/好的/正在/I will/Let me etc.
- Add 'create strategy + create trader + start' full setup workflow
- Add 12 automated tests covering:
- No narration leaking to user (5 narration variants tested)
- api_call tag never leaks to user
- Full setup workflow: POST strategy → verify → POST trader → start
- Start existing trader workflow
- Max iterations safety, tag stripping, parser edge cases
* refactor(agent): replace XML api_call with native function calling
Migrate the Telegram bot agent from an XML tag hack (<api_call>) to
OpenAI-native function calling via CallWithRequestFull.
Key changes:
- mcp/interface.go: add parseMCPResponseFull to clientHooks interface
- mcp/client.go: route callWithRequestFull through hooks for overridability
- mcp/claude_client.go: override parseMCPResponseFull for Claude response
format (tool_use blocks instead of choices[].message.tool_calls)
- telegram/agent/agent.go: rewrite Run() to use CallWithRequestFull;
define api_request tool with JSON Schema; implement tool-call loop
with role="tool" result messages; remove XML parsing entirely
- telegram/agent/apicall.go: remove parseAPICall (dead code)
- telegram/agent/prompt.go: simplify — remove XML format instructions,
replace with concise api_request tool usage instructions
- telegram/agent/agent_test.go: rebuild all tests using LLMResponse
objects; add TestNarrationStructurallyImpossible, TestOnChunkCalledWithFinalReply,
TestToolCallIDPropagated; remove XML-specific tests
Architecture advantage: with native function calling, the LLM returns
EITHER ToolCalls OR Content — never both. Narration is now structurally
impossible at the protocol level, not just enforced by prompt rules.
All 11 agent tests pass. mcp package tests pass.
* refactor(mcp): route buildRequestBodyFromRequest through hooks + full Anthropic format
Problem: callWithRequest/Full/Stream all called client.buildRequestBodyFromRequest
directly (not via hooks), so ClaudeClient could never override it. This meant
tool calling sent OpenAI format to Anthropic (wrong field names, wrong roles).
Changes:
mcp/interface.go
- Add buildRequestBodyFromRequest(*Request) map[string]any to clientHooks
- Improve comments: document what each hook group does and why
mcp/client.go
- All three paths (callWithRequest, callWithRequestFull, CallWithRequestStream)
now call client.hooks.buildRequestBodyFromRequest — ClaudeClient picks up
mcp/claude_client.go
- Full rewrite with format comparison table in package doc
- buildRequestBodyFromRequest: produces correct Anthropic wire format
* system prompt → top-level "system" field
* tools: parameters → input_schema, no "type:function" wrapper
* tool_choice "auto" → {"type":"auto"} object
* assistant tool calls → content[{type:tool_use, id, name, input}]
* role=tool results → role=user content[{type:tool_result,...}]
* consecutive tool results merged into single user turn
- convertMessagesToAnthropic: handles all three message types
- parseMCPResponseFull: extracts text + tool_use blocks
- parseMCPResponse: delegates to parseMCPResponseFull
All mcp and agent tests pass.
* fix(telegram): fix claude client dispatch + strategy creation workflow
- telegram/bot.go: clientForProvider now returns NewClaudeClient() for
'claude' provider (was incorrectly falling back to DeepSeekClient which
uses OpenAI wire format, breaking Anthropic API calls)
- api/server.go: fix scan_interval_minutes schema default (3, not 60);
POST /api/strategies now clearly states config is OPTIONAL with complete
working defaults; POST /api/traders removes redundant GET workflow note
- telegram/agent/prompt.go: simplify strategy creation — just POST {name}
without config (backend applies full working defaults automatically);
only include config when user requests custom settings
* test(mcp): add ClaudeClient wire format tests
Tests cover all Anthropic-specific format conversions:
- system prompt lifted to top-level field
- tools use input_schema (not parameters)
- tool_choice is object {type:auto} not string
- assistant tool calls → content[{type:tool_use}]
- consecutive tool results merged into single user turn
- parseMCPResponseFull: text, tool_use, and error cases
- x-api-key header (not Authorization: Bearer)
- /messages endpoint URL
* fix(telegram): clientForProvider returns correct client for all 7 providers
Previously qwen/kimi/grok/gemini all fell back to DeepSeekClient.
Each provider now gets its own dedicated client with correct default
base URL and model. All 7 providers now fully supported:
openai, deepseek, claude, qwen, kimi, grok, gemini
* fix(telegram): newLLMClient uses bound user's model, not any user's model
GetAnyEnabled() searched across all users in DB — if user B has an
enabled model, bot could use their API key while acting as user A.
Now uses GetDefault(botUserID) which only looks up the bound user's
enabled model, matching the same user scope as all API calls.
* fix(auth): single-user deployment by default, no open registration
Registration logic redesigned:
- Empty DB (first-time setup): registration always open, no config needed
- After first user exists: registration closed by default
- Multi-user opt-in: set REGISTRATION_ENABLED=true + MAX_USERS=N in .env
Config defaults changed:
- RegistrationEnabled: true → false (closed after first user)
- MaxUsers: 10 → 1 (single-user deployment default)
This eliminates the confusion of multiple users appearing in a personal
deployment where Telegram is bound to a single admin account.
* feat(solo): beginner-friendly onboarding — smart setup guide + direct config commands
start.sh:
- Interactive Telegram Bot Token prompt on first run
- Token format validation (must match 12345:ABC... pattern)
- Friendly step-by-step startup instructions after launch
telegram/bot.go:
- /start now shows context-aware setup guide based on actual config state:
- No AI model → explains how to configure, lists all providers
- AI model OK but no exchange → guides to configure exchange via chat
- All configured → full capabilities welcome message
- New: direct setup commands ('配置 deepseek sk-xxx') bypass LLM entirely
so AI model can be configured even before any model exists (bootstrap fix)
- All messages now in Chinese (匹配用户语言)
telegram/agent/prompt.go:
- Added first-time setup detection section
- Agent told to never ask user to visit web UI — everything via chat
* feat(i18n): bilingual EN/ZH setup guide with language selection
store/telegram_config.go:
- Add Language field to TelegramConfig (persisted in DB)
- Add SetLanguage(lang) and GetLanguage() methods
- Default language: English (en)
telegram/bot.go:
- First /start triggers language selection (1=English, 2=中文)
- /lang command to change language at any time
- awaitingLang state machine handles language choice before any other input
- buildSetupGuide() now fully bilingual (EN/ZH), context-aware:
Step 1: configure AI model (no model yet)
Step 2: configure exchange (model OK, no exchange)
Ready: show full capabilities
- tryHandleSetupCommand() bilingual: 'configure/配置 <provider> <key>'
- helpMessage(lang) fully bilingual
- All error/status messages bilingual
Default: English. isLangDefault() detects whether user has explicitly
chosen a language vs falling back to the 'en' default.
* fix(telegram): use Markdown rendering + simplify language selection condition
- sendMarkdownMsg() helper: sends with ParseMode=Markdown, falls back to plain text
- All formatted messages (langSelectionMsg, buildSetupGuide, helpMessage) now render
bold text and code blocks correctly in Telegram
- Simplify /start language check: isLangDefault(st) alone is sufficient
(lang == 'en' && isLangDefault was redundant — GetLanguage returns 'en' when empty)
* fix(start.sh): translate all user-facing text to English
Entire script was in Chinese. Now English-first throughout:
- startup banner, prompts, success/error messages
- setup_telegram(): English instructions and validation messages
- start(): English next-steps after launch
- stop/restart/clean/update/regenerate-keys/show_help: all English
* fix(telegram): remove 'default' user fallback — resolve user dynamically
- botUserID no longer captured once at startup (was 'default' if no user yet)
- resolveBotUser() reads first registered user from DB on demand:
* called on every /start (handles: registered after bot launch)
* called before every AI message (handles mid-session registration)
- If no user registered: clear English error 'No account found. Please register on the web UI first'
- start.sh: fix set_env_var appending without newline (token was concatenated to prev line)
* refactor(telegram): clean onboarding — web UI for setup, Telegram for operations
- /start shows clean status: 'setup required → open web UI' or 'ready → examples'
- Removed tryHandleSetupCommand (no more CLI-style 'configure deepseek sk-xxx')
- Removed automatic language selection on /start (use /lang anytime instead)
- newLLMClient returns nil when no model → clear guard, not fallback
- statusMsg() replaces buildSetupGuide(): two states only (missing config / ready)
- Bot is now purely an operations interface; config lives in the web UI
* refactor: single-user web-based setup — replace env config with Settings UI
Move from multi-user env-var config to single-user web-first architecture:
- Add SetupPage for first-time initialization (replaces /register)
- Add SettingsPage for AI models, exchanges, Telegram, and password management
- Enrich all API route schemas with exact ID usage documentation
- Add PUT /user/password endpoint for in-app password changes
- Remove REGISTRATION_ENABLED, MAX_USERS, TELEGRAM_BOT_TOKEN from env config
- Simplify LoginPage design, remove admin mode and registration links
- Telegram bot now resolves user email for identity display
- start.sh no longer runs interactive Telegram setup
* feat: add blockRun (x402 USDC) support to all AI model consumers
- telegram/bot.go: add blockrun-base, blockrun-sol, minimax to
clientForProvider; fix newLLMClient to prefer TelegramConfig.ModelID
over GetDefault; log USDC payment provider usage
- debate/engine.go: add blockrun-base, blockrun-sol to InitializeClients
- api/strategy.go: add blockrun-base, blockrun-sol to runRealAITest
- backtest/ai_client.go: add blockrun-base, blockrun-sol to configureMCPClient
* feat: add Claw402 (claw402.ai) x402 USDC payment provider
Add Claw402Client for claw402.ai's x402 micropayment gateway (Base USDC).
Supports 15+ AI models (GPT-5.4, Claude Opus, DeepSeek, Qwen, Grok, etc.)
with per-model endpoint routing.
- mcp/claw402.go: new client with model→endpoint mapping, x402 v2 payment flow
- mcp/blockrun_base.go: extract shared signX402Payment() for reuse
- Register "claw402" provider in all 6 consumer switch statements:
api/server.go, api/strategy.go, trader/auto_trader.go,
telegram/bot.go, debate/engine.go, backtest/ai_client.go
* feat: redesign Claw402 model config UI — friendly wallet setup, USDC guide, official logo, nginx no-cache for index.html
* refactor: centralize x402 payment flow into shared mcp/x402.go
Extract duplicated doRequestWithPayment/call/CallWithRequestFull/buildRequest/
setAuthHeader (~165 lines x3) into shared helpers in mcp/x402.go. Consolidate
shared types (x402v2PaymentRequired, x402AcceptOption, x402Resource) and remove
duplicate Solana types. Fix validAfter to 0 (official SDK standard), drain 402
body before retry, log Payment-Response tx hash, check Payment-Required before
X-Payment-Required.
* fix: stop PR template bot from overwriting user-written descriptions
The pr-template-suggester workflow was triggered on opened/edited/synchronize
events and forcefully replaced the PR body with a template when body < 100 chars.
This caused user-written descriptions to be overwritten.
Replace with a lightweight labeler (OpenClaw-style) that:
- Only adds labels (backend/frontend/docs, size: XS/S/M/L/XL)
- Never modifies the PR body
- Simplified unified PR template at .github/pull_request_template.md
* chore: simplify PR template (OpenClaw-style)
480 lines
14 KiB
Go
480 lines
14 KiB
Go
package telegram
|
|
|
|
import (
|
|
"nofx/api"
|
|
"nofx/config"
|
|
"nofx/logger"
|
|
"nofx/mcp"
|
|
"nofx/store"
|
|
"nofx/telegram/agent"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
)
|
|
|
|
// Start initializes and runs the Telegram bot in a blocking supervisor loop.
|
|
// Supports hot-reload: when a signal is sent on reloadCh, the bot restarts
|
|
// with the latest token (re-read from DB or env). Must be called as a goroutine from main.go.
|
|
func Start(cfg *config.Config, st *store.Store, reloadCh <-chan struct{}) {
|
|
for {
|
|
token := resolveToken(cfg, st)
|
|
if token == "" {
|
|
logger.Info("Telegram bot disabled (no token configured), waiting for reload signal...")
|
|
<-reloadCh
|
|
continue
|
|
}
|
|
|
|
stopped := runBot(token, cfg, st)
|
|
if !stopped {
|
|
return
|
|
}
|
|
|
|
select {
|
|
case <-reloadCh:
|
|
logger.Info("Reloading Telegram bot with new token...")
|
|
}
|
|
}
|
|
}
|
|
|
|
// resolveToken returns the bot token from DB (configured via Web UI).
|
|
func resolveToken(cfg *config.Config, st *store.Store) string {
|
|
dbCfg, err := st.TelegramConfig().Get()
|
|
if err == nil && dbCfg.BotToken != "" {
|
|
return dbCfg.BotToken
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// runBot runs the bot until the updates channel closes (clean stop → true) or a fatal error (false).
|
|
func runBot(token string, cfg *config.Config, st *store.Store) bool {
|
|
bot, err := tgbotapi.NewBotAPI(token)
|
|
if err != nil {
|
|
logger.Errorf("Telegram bot failed to start: %v", err)
|
|
return false
|
|
}
|
|
logger.Infof("Telegram bot @%s started", bot.Self.UserName)
|
|
|
|
// Allowed chat ID: read from DB binding (0 = unbound, first /start will bind).
|
|
allowedChatID := int64(0)
|
|
if id, err := st.TelegramConfig().GetBoundChatID(); err == nil && id != 0 {
|
|
allowedChatID = id
|
|
}
|
|
|
|
// botUserID / botToken / agents are resolved lazily and refresh when user registers.
|
|
var (
|
|
botUserID string
|
|
botUserEmail string
|
|
botToken string
|
|
agents *agent.Manager
|
|
)
|
|
|
|
resolveBotUser := func() bool {
|
|
users, err := st.User().GetAll()
|
|
if err != nil || len(users) == 0 {
|
|
return false
|
|
}
|
|
u := users[0]
|
|
if u.ID == botUserID {
|
|
return true
|
|
}
|
|
newToken, err := agent.GenerateBotToken(u.ID)
|
|
if err != nil {
|
|
logger.Errorf("Failed to generate bot JWT for user %s: %v", u.ID, err)
|
|
return false
|
|
}
|
|
prev := botUserID
|
|
botUserID = u.ID
|
|
botUserEmail = u.Email
|
|
botToken = newToken
|
|
agents = agent.NewManager(cfg.APIServerPort, botToken, botUserEmail, botUserID,
|
|
func() mcp.AIClient { return newLLMClient(st, botUserID) },
|
|
api.GetAPIDocs(),
|
|
)
|
|
if prev == "" {
|
|
logger.Infof("Bot: resolved user %s (%s)", botUserID, botUserEmail)
|
|
} else {
|
|
logger.Infof("Bot: user changed → %s (%s)", botUserID, botUserEmail)
|
|
}
|
|
return true
|
|
}
|
|
resolveBotUser()
|
|
|
|
u := tgbotapi.NewUpdate(0)
|
|
u.Timeout = 60
|
|
updates := bot.GetUpdatesChan(u)
|
|
|
|
// awaitingLang is set only when the user explicitly runs /lang.
|
|
awaitingLang := false
|
|
|
|
for update := range updates {
|
|
if update.Message == nil {
|
|
continue
|
|
}
|
|
chatID := update.Message.Chat.ID
|
|
text := strings.TrimSpace(update.Message.Text)
|
|
|
|
// ── Language selection (triggered only by /lang) ──────────────────────
|
|
if awaitingLang && chatID == allowedChatID {
|
|
if lang := parseLangChoice(text); lang != "" {
|
|
awaitingLang = false
|
|
st.TelegramConfig().SetLanguage(lang) //nolint:errcheck
|
|
sendMarkdownMsg(bot, chatID, statusMsg(st, botUserID, cfg.APIServerPort, lang))
|
|
} else {
|
|
sendMarkdownMsg(bot, chatID, langMenuMsg())
|
|
}
|
|
continue
|
|
}
|
|
|
|
// ── /start ────────────────────────────────────────────────────────────
|
|
if text == "/start" {
|
|
resolveBotUser()
|
|
if botUserID == "" {
|
|
sendMsg(bot, chatID,
|
|
"No account found.\nOpen the web dashboard to register, then send /start.")
|
|
continue
|
|
}
|
|
if allowedChatID == 0 {
|
|
username := update.Message.From.UserName
|
|
if err := st.TelegramConfig().BindUser(chatID, "@"+username); err != nil {
|
|
logger.Errorf("Failed to bind Telegram user: %v", err)
|
|
sendMsg(bot, chatID, "Binding failed. Please try again.")
|
|
continue
|
|
}
|
|
allowedChatID = chatID
|
|
logger.Infof("Telegram bound to @%s (chatID: %d)", username, chatID)
|
|
} else if chatID != allowedChatID {
|
|
sendMsg(bot, chatID, "This bot is already bound to another account.")
|
|
continue
|
|
} else {
|
|
agents.Reset(chatID)
|
|
}
|
|
lang := st.TelegramConfig().GetLanguage()
|
|
sendMarkdownMsg(bot, chatID, statusMsg(st, botUserID, cfg.APIServerPort, lang))
|
|
continue
|
|
}
|
|
|
|
// ── /lang ─────────────────────────────────────────────────────────────
|
|
if text == "/lang" {
|
|
awaitingLang = true
|
|
sendMarkdownMsg(bot, chatID, langMenuMsg())
|
|
continue
|
|
}
|
|
|
|
// ── /help ─────────────────────────────────────────────────────────────
|
|
if text == "/help" {
|
|
lang := st.TelegramConfig().GetLanguage()
|
|
sendMarkdownMsg(bot, chatID, helpMsg(lang))
|
|
continue
|
|
}
|
|
|
|
// ── Access control ────────────────────────────────────────────────────
|
|
if allowedChatID != 0 && chatID != allowedChatID {
|
|
sendMsg(bot, chatID, "Unauthorized.")
|
|
continue
|
|
}
|
|
if allowedChatID == 0 {
|
|
sendMsg(bot, chatID, "Send /start first.")
|
|
continue
|
|
}
|
|
if text == "" {
|
|
continue
|
|
}
|
|
|
|
// ── Refresh user before every AI call ────────────────────────────────
|
|
resolveBotUser()
|
|
if botUserID == "" {
|
|
sendMsg(bot, chatID, "No account found. Open the web dashboard to register.")
|
|
continue
|
|
}
|
|
|
|
lang := st.TelegramConfig().GetLanguage()
|
|
|
|
// ── Guard: show status if not ready for trading ───────────────────────
|
|
if newLLMClient(st, botUserID) == nil {
|
|
sendMarkdownMsg(bot, chatID, statusMsg(st, botUserID, cfg.APIServerPort, lang))
|
|
continue
|
|
}
|
|
|
|
// ── AI agent ─────────────────────────────────────────────────────────
|
|
go func(chatID int64, text string) {
|
|
sent, err := bot.Send(tgbotapi.NewMessage(chatID, "⏳"))
|
|
placeholderID := 0
|
|
if err == nil {
|
|
placeholderID = sent.MessageID
|
|
}
|
|
|
|
var (
|
|
mu sync.Mutex
|
|
lastEdit time.Time
|
|
)
|
|
onChunk := func(accumulated string) {
|
|
if placeholderID == 0 {
|
|
return
|
|
}
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
if accumulated != "⏳" && time.Since(lastEdit) < time.Second {
|
|
return
|
|
}
|
|
lastEdit = time.Now()
|
|
edit := tgbotapi.NewEditMessageText(chatID, placeholderID, accumulated)
|
|
bot.Send(edit) //nolint:errcheck
|
|
}
|
|
|
|
reply := agents.Run(chatID, text, onChunk)
|
|
|
|
if placeholderID != 0 {
|
|
edit := tgbotapi.NewEditMessageText(chatID, placeholderID, reply)
|
|
edit.ParseMode = "Markdown"
|
|
if _, err := bot.Send(edit); err != nil {
|
|
edit2 := tgbotapi.NewEditMessageText(chatID, placeholderID, reply)
|
|
bot.Send(edit2) //nolint:errcheck
|
|
}
|
|
} else {
|
|
msg := tgbotapi.NewMessage(chatID, reply)
|
|
msg.ParseMode = "Markdown"
|
|
if _, err := bot.Send(msg); err != nil {
|
|
msg.ParseMode = ""
|
|
bot.Send(msg) //nolint:errcheck
|
|
}
|
|
}
|
|
}(chatID, text)
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────────────────────
|
|
|
|
func sendMsg(bot *tgbotapi.BotAPI, chatID int64, text string) {
|
|
msg := tgbotapi.NewMessage(chatID, text)
|
|
bot.Send(msg) //nolint:errcheck
|
|
}
|
|
|
|
func sendMarkdownMsg(bot *tgbotapi.BotAPI, chatID int64, text string) {
|
|
msg := tgbotapi.NewMessage(chatID, text)
|
|
msg.ParseMode = "Markdown"
|
|
if _, err := bot.Send(msg); err != nil {
|
|
plain := tgbotapi.NewMessage(chatID, text)
|
|
bot.Send(plain) //nolint:errcheck
|
|
}
|
|
}
|
|
|
|
// ── LLM client ───────────────────────────────────────────────────────────────
|
|
|
|
func newLLMClient(st *store.Store, userID string) mcp.AIClient {
|
|
// 1. Prefer the model explicitly configured for Telegram (Settings → Telegram → AI Model)
|
|
if tgCfg, err := st.TelegramConfig().Get(); err == nil && tgCfg.ModelID != "" {
|
|
if model, err := st.AIModel().Get(userID, tgCfg.ModelID); err == nil && model.Enabled {
|
|
apiKey := string(model.APIKey)
|
|
if apiKey != "" {
|
|
client := clientForProvider(model.Provider)
|
|
client.SetAPIKey(apiKey, model.CustomAPIURL, model.CustomModelName)
|
|
if isUSDCProvider(model.Provider) {
|
|
logger.Infof("Telegram agent: provider=%s (USDC payment) user=%s", model.Provider, userID)
|
|
} else {
|
|
logger.Infof("Telegram agent: provider=%s user=%s", model.Provider, userID)
|
|
}
|
|
return client
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Fall back to first enabled model
|
|
if model, err := st.AIModel().GetDefault(userID); err == nil {
|
|
apiKey := string(model.APIKey)
|
|
if apiKey != "" {
|
|
client := clientForProvider(model.Provider)
|
|
client.SetAPIKey(apiKey, model.CustomAPIURL, model.CustomModelName)
|
|
if isUSDCProvider(model.Provider) {
|
|
logger.Infof("Telegram agent: provider=%s (USDC payment) user=%s", model.Provider, userID)
|
|
} else {
|
|
logger.Infof("Telegram agent: provider=%s user=%s", model.Provider, userID)
|
|
}
|
|
return client
|
|
}
|
|
}
|
|
|
|
// 3. Environment variable fallback
|
|
for _, pair := range []struct{ provider, key, url string }{
|
|
{"deepseek", os.Getenv("DEEPSEEK_API_KEY"), mcp.DefaultDeepSeekBaseURL},
|
|
{"openai", os.Getenv("OPENAI_API_KEY"), ""},
|
|
{"claude", os.Getenv("ANTHROPIC_API_KEY"), ""},
|
|
} {
|
|
if pair.key != "" {
|
|
client := clientForProvider(pair.provider)
|
|
client.SetAPIKey(pair.key, pair.url, "")
|
|
return client
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// isUSDCProvider returns true for providers that pay per call with USDC (x402 protocol).
|
|
func isUSDCProvider(provider string) bool {
|
|
return provider == "blockrun-base" || provider == "blockrun-sol" || provider == "claw402"
|
|
}
|
|
|
|
func clientForProvider(provider string) mcp.AIClient {
|
|
switch provider {
|
|
case "openai":
|
|
return mcp.NewOpenAIClient()
|
|
case "deepseek":
|
|
return mcp.NewDeepSeekClient()
|
|
case "claude":
|
|
return mcp.NewClaudeClient()
|
|
case "qwen":
|
|
return mcp.NewQwenClient()
|
|
case "kimi":
|
|
return mcp.NewKimiClient()
|
|
case "grok":
|
|
return mcp.NewGrokClient()
|
|
case "gemini":
|
|
return mcp.NewGeminiClient()
|
|
case "minimax":
|
|
return mcp.NewMiniMaxClient()
|
|
case "blockrun-base":
|
|
return mcp.NewBlockRunBaseClient()
|
|
case "blockrun-sol":
|
|
return mcp.NewBlockRunSolClient()
|
|
case "claw402":
|
|
return mcp.NewClaw402Client()
|
|
default:
|
|
return mcp.NewDeepSeekClient()
|
|
}
|
|
}
|
|
|
|
// ── Status message ────────────────────────────────────────────────────────────
|
|
|
|
// statusMsg is the single entry-point message shown after /start.
|
|
// It checks what's configured and shows either a setup prompt or the ready state.
|
|
func statusMsg(st *store.Store, userID string, apiPort int, lang string) string {
|
|
webURL := "http://localhost:3000"
|
|
|
|
// Determine what's missing.
|
|
hasModel := false
|
|
if _, err := st.AIModel().GetDefault(userID); err == nil {
|
|
hasModel = true
|
|
}
|
|
|
|
hasExchange := false
|
|
if exchanges, err := st.Exchange().List(userID); err == nil {
|
|
for _, e := range exchanges {
|
|
if e.Enabled {
|
|
hasExchange = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if !hasModel || !hasExchange {
|
|
missing := ""
|
|
if lang == "zh" {
|
|
if !hasModel {
|
|
missing += "\n❌ AI 模型 → 设置 → AI 模型 → 添加"
|
|
}
|
|
if !hasExchange {
|
|
missing += "\n❌ 交易所 → 设置 → 交易所 → 添加"
|
|
}
|
|
return "⚙️ *需要完成初始配置*\n\n打开 Web 管理界面完成配置:\n→ " + webURL + "\n" + missing + "\n\n配置完成后发送 /start"
|
|
}
|
|
if !hasModel {
|
|
missing += "\n❌ AI Model → Settings → AI Models → Add"
|
|
}
|
|
if !hasExchange {
|
|
missing += "\n❌ Exchange → Settings → Exchanges → Add"
|
|
}
|
|
return "⚙️ *Setup required*\n\nOpen the web dashboard to complete setup:\n→ " + webURL + "\n" + missing + "\n\nSend /start when done."
|
|
}
|
|
|
|
// All configured — show ready state.
|
|
if lang == "zh" {
|
|
return `✅ *NOFX 就绪,开始交易吧!*
|
|
|
|
直接告诉我你想做什么:
|
|
|
|
📊 "查看我的持仓"
|
|
💰 "账户余额多少"
|
|
🤖 "帮我创建 BTC 趋势策略并启动"
|
|
⏹ "停止所有交易员"
|
|
|
|
/help 查看更多 · /lang 切换语言`
|
|
}
|
|
return `✅ *NOFX is ready!*
|
|
|
|
Just tell me what you want:
|
|
|
|
📊 "Show my positions"
|
|
💰 "What's my balance?"
|
|
🤖 "Create a BTC trend strategy and start it"
|
|
⏹ "Stop all traders"
|
|
|
|
/help for more · /lang to change language`
|
|
}
|
|
|
|
// ── Language ──────────────────────────────────────────────────────────────────
|
|
|
|
func langMenuMsg() string {
|
|
return "🌐 *Choose your language*\n\n1 — English\n2 — 中文\n\nReply with 1 or 2"
|
|
}
|
|
|
|
func parseLangChoice(text string) string {
|
|
switch strings.TrimSpace(text) {
|
|
case "1", "en", "EN", "English", "english":
|
|
return "en"
|
|
case "2", "zh", "ZH", "中文", "chinese", "Chinese":
|
|
return "zh"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// ── Help ──────────────────────────────────────────────────────────────────────
|
|
|
|
func helpMsg(lang string) string {
|
|
if lang == "zh" {
|
|
return `*NOFX 使用指南*
|
|
|
|
*查询*
|
|
• "查看我的持仓"
|
|
• "账户余额多少"
|
|
• "列出我的交易员"
|
|
|
|
*创建 & 启动*
|
|
• "帮我创建 BTC 趋势策略并跑起来"
|
|
• "保守型策略,只交易 BTC 和 ETH"
|
|
|
|
*控制*
|
|
• "启动交易员"
|
|
• "暂停交易员"
|
|
• "停止所有交易"
|
|
|
|
*命令*
|
|
/start — 刷新状态
|
|
/lang — 切换语言
|
|
/help — 帮助`
|
|
}
|
|
return `*NOFX Help*
|
|
|
|
*Query*
|
|
• "Show my positions"
|
|
• "What's my balance?"
|
|
• "List my traders"
|
|
|
|
*Create & start*
|
|
• "Create a BTC trend strategy and start it"
|
|
• "Conservative strategy, BTC and ETH only"
|
|
|
|
*Control*
|
|
• "Start trader"
|
|
• "Stop trader"
|
|
• "Stop all trading"
|
|
|
|
*Commands*
|
|
/start — refresh status
|
|
/lang — change language
|
|
/help — show this`
|
|
}
|