Files
ops-assistant/internal/module/rate/module.go
T

42 lines
1.2 KiB
Go

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 138 sgd to cny\n\n也支持:\n/rate 138sgd to cny\n/rate 100 usd to cny\n/rate 50 eur -> sgd\n/rate 1000 php/cny\n\n数据源:Google Finance、Visa、Mastercard。Visa/万事达为官方结算汇率;Google 为市场参考价。"
}