feat: add realtime rate command

This commit is contained in:
2026-09-15 07:54:13 +08:00
parent c78e3be829
commit d2697221d1
4 changed files with 156 additions and 0 deletions
+41
View File
@@ -0,0 +1,41 @@
package rate
import (
"fmt"
"regexp"
"strconv"
"strings"
"ops-assistant/internal/core/command"
)
type Module struct{}
func New() *Module { return &Module{} }
var re = regexp.MustCompile(`(?i)^/rate\s+([0-9]+(?:\.[0-9]+)?)\s*([a-z]{3})\s*(?:(?:to)\s*|->\s*|/\s*)([a-z]{3})\s*$`)
func (m *Module) Handle(_ int64, cmd *command.ParsedCommand) (string, error) {
text := strings.TrimSpace(cmd.Raw)
if strings.EqualFold(text, "/rate") || strings.HasPrefix(strings.ToLower(text), "/rate help") {
return help(), nil
}
hit := re.FindStringSubmatch(text)
if hit == nil {
return help(), nil
}
amount, err := strconv.ParseFloat(hit[1], 64)
if err != nil || amount <= 0 {
return "❌ 金额无效", nil
}
base := strings.ToUpper(hit[2])
quote := strings.ToUpper(hit[3])
if base == quote {
return fmt.Sprintf("💱 %s → %s\n\n%s %s = %s %s", base, quote, hit[1], base, hit[1], quote), nil
}
return query(amount, base, quote)
}
func help() string {
return "💱 汇率转换\n\n用法:/rate 138sgd to cny\n\n也支持:\n/rate 100 usd to cny\n/rate 50 eur -> sgd\n/rate 1000 php/cny\n\n数据源:Google Finance、Visa、Mastercard。Visa/万事达为官方结算汇率;Google 为市场参考价。"
}
+28
View File
@@ -0,0 +1,28 @@
package rate
import (
"context"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
)
func query(amount float64, base, quote string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 190*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "python3", "scripts/rate_query.py", strconv.FormatFloat(amount, 'f', -1, 64), base, quote)
out, err := cmd.Output()
if ctx.Err() == context.DeadlineExceeded {
return "", fmt.Errorf("汇率服务超时,请稍后重试")
}
if err != nil {
return "", fmt.Errorf("汇率查询失败")
}
text := strings.TrimSpace(string(out))
if text == "" {
return "", fmt.Errorf("未获取到汇率")
}
return text, nil
}