feat(controller): add source for command handling.

feat(telegram): switch message type to markdown
feat(controller): add welcome message for telegram bot.
This commit is contained in:
2026-08-13 17:07:55 +08:00
parent 8589654ba4
commit f2cc16177c
8 changed files with 90 additions and 65 deletions
+3
View File
@@ -94,6 +94,9 @@ func LoadConfig(configPath string) (*Config, error) {
if cfg.ControllerMessage.BotHelp == "" { if cfg.ControllerMessage.BotHelp == "" {
cfg.ControllerMessage.BotHelp = "Available commands:\n/help - Show this help message\n/list - List all servers\n/status <uuid> - Show status of a specific server\n/shutdown <uuid> - Shutdown a specific server\n/reboot <uuid> - Reboot a specific server\n/run <uuid> <command> - Run a command on a specific server\n/info - Show bot information" cfg.ControllerMessage.BotHelp = "Available commands:\n/help - Show this help message\n/list - List all servers\n/status <uuid> - Show status of a specific server\n/shutdown <uuid> - Shutdown a specific server\n/reboot <uuid> - Reboot a specific server\n/run <uuid> <command> - Run a command on a specific server\n/info - Show bot information"
} }
if cfg.ControllerMessage.Tg_BotStart == "" {
cfg.ControllerMessage.Tg_BotStart = "Welcome to use Nukumizu Alert Bot!\nUse /help to see available commands."
}
if cfg.ControllerMessage.ServerStatusChanged == "" { if cfg.ControllerMessage.ServerStatusChanged == "" {
cfg.ControllerMessage.ServerStatusChanged = "Server Status Changed Alert\n{{ serverName }} - {{ upStatus }}\nEvent: {{ event }}\nServer Name: {{ serverName }}\nMessage: {{ message }}\nTime: {{ time }}" cfg.ControllerMessage.ServerStatusChanged = "Server Status Changed Alert\n{{ serverName }} - {{ upStatus }}\nEvent: {{ event }}\nServer Name: {{ serverName }}\nMessage: {{ message }}\nTime: {{ time }}"
} }
+1
View File
@@ -99,6 +99,7 @@ type ControllerMethodConfig struct {
type ControllerMessageConfig struct { type ControllerMessageConfig struct {
BotStarted string `json:"BOT_STARTED"` BotStarted string `json:"BOT_STARTED"`
BotHelp string `json:"BOT_HELP"` BotHelp string `json:"BOT_HELP"`
Tg_BotStart string `json:"TG_BOT_START"`
ServerStatusChanged string `json:"SERVER_STATUS_CHANGED"` ServerStatusChanged string `json:"SERVER_STATUS_CHANGED"`
ServerList string `json:"SERVER_LIST"` ServerList string `json:"SERVER_LIST"`
ServerExecuteResult string `json:"SERVER_EXECUTE_RESULT"` ServerExecuteResult string `json:"SERVER_EXECUTE_RESULT"`
+2 -1
View File
@@ -12,7 +12,8 @@ import (
// Command represents a parsed bot command. // Command represents a parsed bot command.
type Command struct { type Command struct {
RawText string Source string // The source pipe (e.g., "telegram", "qq", "napcat")
RawText string // The raw text of the command message
Command string // The command word (e.g., "list", "status") Command string // The command word (e.g., "list", "status")
Args []string // Command arguments Args []string // Command arguments
ChatID int64 // Chat/group ID where the command was issued ChatID int64 // Chat/group ID where the command was issued
+2 -2
View File
@@ -179,12 +179,12 @@ func (q *QQController) processCommand(cmd controller.Command) string {
parsed.ChatID = cmd.ChatID parsed.ChatID = cmd.ChatID
parsed.ChatType = cmd.ChatType parsed.ChatType = cmd.ChatType
parsed.SenderID = cmd.SenderID parsed.SenderID = cmd.SenderID
parsed.Source = "qq_napcat"
// Hand the complete command to the unified processor, which checks group // Hand the complete command to the unified processor, which checks group
// vs private, trusted groups, admin permissions, and executes it. // vs private, trusted groups, admin permissions, and executes it.
response, err := controller.GetManager().Trigger(parsed, q.cfg.TrustedGroups, q.cfg.Admins, q.cfg.ListenMethod) response, err := controller.GetManager().Trigger(parsed, q.cfg.TrustedGroups, q.cfg.Admins, q.cfg.ListenMethod)
cfg := config.GetConfig() if config.GetConfig().System.DebugMode && config.GetConfig().Debug.ShowTriggerCmdEcho {
if cfg.System.DebugMode && cfg.Debug.ShowTriggerCmdEcho {
postLog.Debug(fmt.Sprintf("[qq_napcat] triggered command: \"/%s\" with args: \"%s\" from chatID: %d and senderID: %d", parsed.Command, strings.Join(parsed.Args, ", "), cmd.ChatID, cmd.SenderID)) postLog.Debug(fmt.Sprintf("[qq_napcat] triggered command: \"/%s\" with args: \"%s\" from chatID: %d and senderID: %d", parsed.Command, strings.Join(parsed.Args, ", "), cmd.ChatID, cmd.SenderID))
} }
if err != nil { if err != nil {
+8 -4
View File
@@ -182,8 +182,11 @@ func (c *Client) getUpdates(offset int64, limit, timeout int) ([]Update, error)
} }
// SendMessage sends a text message to a chat, splitting it into chunks that // SendMessage sends a text message to a chat, splitting it into chunks that
// fit Telegram's 4096-character limit. The text is sent without a parse mode so // fit Telegram's 4096-character limit. All messages are sent with
// template asterisks render literally. // parse_mode=Markdown so fenced code blocks and inline formatting render as
// rich text. Templates must stay valid under Telegram's legacy Markdown:
// unpaired '*' or '_' characters (e.g. a lone '*Event: ...' label) make the
// API reject the whole message.
func (c *Client) SendMessage(chatID int64, text string) error { func (c *Client) SendMessage(chatID int64, text string) error {
if strings.TrimSpace(text) == "" { if strings.TrimSpace(text) == "" {
return nil return nil
@@ -198,8 +201,9 @@ func (c *Client) SendMessage(chatID int64, text string) error {
func (c *Client) sendMessageChunk(chatID int64, text string) error { func (c *Client) sendMessageChunk(chatID int64, text string) error {
params := url.Values{ params := url.Values{
"chat_id": {strconv.FormatInt(chatID, 10)}, "chat_id": {strconv.FormatInt(chatID, 10)},
"text": {text}, "text": {text},
"parse_mode": {"Markdown"},
} }
return c.call("sendMessage", params, nil) return c.call("sendMessage", params, nil)
} }
@@ -169,10 +169,14 @@ func (t *TelegramController) processCommand(cmd controller.Command) string {
parsed.ChatID = cmd.ChatID parsed.ChatID = cmd.ChatID
parsed.ChatType = cmd.ChatType parsed.ChatType = cmd.ChatType
parsed.SenderID = cmd.SenderID parsed.SenderID = cmd.SenderID
parsed.Source = "telegram"
// Hand the complete command to the unified processor, which checks group // Hand the complete command to the unified processor, which checks group
// vs private, trusted groups, admin permissions, and executes it. // vs private, trusted groups, admin permissions, and executes it.
response, err := controller.GetManager().Trigger(parsed, t.cfg.TrustedGroups, t.resolvedAdminList(), t.cfg.ListenMethod) response, err := controller.GetManager().Trigger(parsed, t.cfg.TrustedGroups, t.resolvedAdminList(), t.cfg.ListenMethod)
if config.GetConfig().System.DebugMode && config.GetConfig().Debug.ShowTriggerCmdEcho {
postLog.Debug(fmt.Sprintf("[telegram] triggered command: \"/%s\" with args: \"%s\" from chatID: %d and senderID: %d", parsed.Command, strings.Join(parsed.Args, ", "), cmd.ChatID, cmd.SenderID))
}
if err != nil { if err != nil {
postLog.Error("Telegram command processing failed: " + err.Error()) postLog.Error("Telegram command processing failed: " + err.Error())
return "" return ""
+6 -58
View File
@@ -10,64 +10,6 @@ import (
"nukumizu-backend/internal/template" "nukumizu-backend/internal/template"
) )
// Trigger validates an incoming command against the pipe's authorization
// config (trusted groups / admins) and, if authorized, processes it through
// RouteCommand. It returns the response text to reply with; an empty response means
// the command was discarded.
//
// All command handling across pipes is unified here: pipes only decide whether
// a received message is a command, then hand the complete command over.
func (m *Manager) Trigger(cmd Command, trustedGroups, admins []string, listenMethod string) (string, error) {
// Check whether the command arrived in a group or a private chat.
if cmd.ChatType == "group" {
// Group commands are only honored from trusted groups, otherwise discard.
if !IsTrustedGroup(cmd.ChatID, trustedGroups) {
return "", nil
}
}
// Commands that require special permission must be sent by an admin.
if IsAdminCommand(cmd.Command) {
if !IsAdmin(cmd.SenderID, admins) {
return "", nil
}
}
response, err := m.RouteCommand(cmd)
if err != nil {
return "", err
}
// In "at" listen mode, give feedback for unknown commands.
if response == "" && listenMethod == "at" {
return "Unknown command: /" + cmd.Command, nil
}
return response, nil
}
// RouteCommand processes a parsed bot command and returns the response text.
// The actual command execution for every pipe is unified here.
func (m *Manager) RouteCommand(cmd Command) (string, error) {
switch cmd.Command {
case "help":
return handleHelp()
case "list":
return handleList()
case "status":
return handleStatus(cmd)
case "shutdown":
return handleShutdown(cmd)
case "reboot":
return handleReboot(cmd)
case "run":
return handleRun(cmd)
case "info":
return handleInfo(cmd)
default:
return "", nil
}
}
func handleHelp() (string, error) { func handleHelp() (string, error) {
cfg := config.GetConfig() cfg := config.GetConfig()
params := template.BuildBotInitializationMsgParams() params := template.BuildBotInitializationMsgParams()
@@ -235,6 +177,12 @@ func handleInfo(cmd Command) (string, error) {
return sb.String(), nil return sb.String(), nil
} }
func telegram_handleStart() (string, error) {
cfg := config.GetConfig()
params := template.BuildBotInitializationMsgParams()
return template.Render(cfg.ControllerMessage.Tg_BotStart, params), nil
}
// formatBytes renders a byte count in a human-readable form. // formatBytes renders a byte count in a human-readable form.
func formatBytes(b int64) string { func formatBytes(b int64) string {
const ( const (
+64
View File
@@ -5,6 +5,70 @@ import (
"strings" "strings"
) )
// Trigger validates an incoming command against the pipe's authorization
// config (trusted groups / admins) and, if authorized, processes it through
// RouteCommand. It returns the response text to reply with; an empty response means
// the command was discarded.
//
// All command handling across pipes is unified here: pipes only decide whether
// a received message is a command, then hand the complete command over.
func (m *Manager) Trigger(cmd Command, trustedGroups, admins []string, listenMethod string) (string, error) {
// Check whether the command arrived in a group or a private chat.
if cmd.ChatType == "group" {
// Group commands are only honored from trusted groups, otherwise discard.
if !IsTrustedGroup(cmd.ChatID, trustedGroups) {
return "", nil
}
}
// Commands that require special permission must be sent by an admin.
if IsAdminCommand(cmd.Command) {
if !IsAdmin(cmd.SenderID, admins) {
return "", nil
}
}
response, err := m.RouteCommand(cmd)
if err != nil {
return "", err
}
// In "at" listen mode, give feedback for unknown commands.
if response == "" && listenMethod == "at" {
return "Unknown command: /" + cmd.Command, nil
}
return response, nil
}
// RouteCommand processes a parsed bot command and returns the response text.
// The actual command execution for every pipe is unified here.
func (m *Manager) RouteCommand(cmd Command) (string, error) {
if cmd.Source == "telegram"{
switch cmd.Command {
case "start":
return telegram_handleStart()
}
}
switch cmd.Command {
case "help":
return handleHelp()
case "list":
return handleList()
case "status":
return handleStatus(cmd)
case "shutdown":
return handleShutdown(cmd)
case "reboot":
return handleReboot(cmd)
case "run":
return handleRun(cmd)
case "info":
return handleInfo(cmd)
default:
return "", nil
}
}
// ParseCommand parses a raw message text into a Command. // ParseCommand parses a raw message text into a Command.
// Format: /{{command}} {{args...}} // Format: /{{command}} {{args...}}
func ParseCommand(rawText string) (cmd Command, ok bool) { func ParseCommand(rawText string) (cmd Command, ok bool) {