style(qq_onebot): rename all NapCat related to OneBot
Build / ubuntu-latest (push) Failing after 3m56s
Build / windows-latest (push) Canceled after 34m52s

This commit is contained in:
NanamiAdmin committed 2026-10-11 13:58:26 +08:00
1 parent 72d0d587cb
commit 1b11be2427
11 files changed
+122 -125

No files matched your search

@@ -0,0 +1,330 @@
package qq_onebot
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
"nukumizu-backend/config"
"nukumizu-backend/internal/netproxy"
"nukumizu-backend/postLog"
)
// actionLogEnabled reports whether the OneBot HTTP API methods echo each action
// they send, per the showOneBotAction toggle. Unlike the WebSocket message path
// in qq.go it deliberately does not also require debugMode: these methods have
// always logged on this toggle alone, and preserving that is intentional.
func actionLogEnabled() bool {
cfg := config.Current()
return cfg != nil && cfg.Debug.ShowOneBotAction
}
// APIResponse mirrors OneBot's HTTP API response envelope.
type APIResponse struct {
Status string `json:"status"`
RetCode int `json:"retcode"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
// Client is the HTTP + WebSocket client for a single OneBot instance.
// It both listens for incoming OneBot events over WebSocket and issues
// outbound OneBot API calls over HTTP.
type Client struct {
addr string
port string
token string
useProxy bool
httpClient *http.Client
connMu sync.Mutex
conn *websocket.Conn
stopCh chan struct{}
stopOnce sync.Once
}
// NewClient creates a OneBot client for the given host/port/token. When
// useProxy is set, HTTP API calls and the WebSocket connection are routed
// through the system-wide network proxy.
func NewClient(addr, port, token string, useProxy bool) *Client {
return &Client{
addr: addr,
port: port,
token: token,
useProxy: useProxy,
httpClient: netproxy.HTTPClient(useProxy, 30*time.Second),
stopCh: make(chan struct{}),
}
}
func (c *Client) baseURL() string {
return fmt.Sprintf("http://%s:%s", c.addr, c.port)
}
// sendRequest performs an HTTP call to OneBot, injecting access_token into POST
// bodies AND setting Authorization: Bearer (compatible with HTTP Server adapters
// created in the OneBot Web UI).
func (c *Client) sendRequest(method, endpoint string, body []byte) ([]byte, error) {
url := c.baseURL() + endpoint
// For POST requests, inject access_token into the JSON body before sending.
var finalBody []byte
if body != nil && c.token != "" {
var bodyMap map[string]interface{}
if err := json.Unmarshal(body, &bodyMap); err == nil {
bodyMap["access_token"] = c.token
finalBody, _ = json.Marshal(bodyMap)
}
}
if finalBody == nil {
finalBody = body
}
var req *http.Request
var err error
if finalBody != nil {
req, err = http.NewRequest(method, url, bytes.NewReader(finalBody))
} else {
req, err = http.NewRequest(method, url, nil)
}
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request to onebot: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read onebot response: %w", err)
}
return respBody, nil
}
// parseResponse unmarshals OneBot's raw response body into an APIResponse.
func (c *Client) parseResponse(respBody []byte, caller string) (*APIResponse, error) {
var onebotResp APIResponse
if err := json.Unmarshal(respBody, &onebotResp); err != nil {
return nil, fmt.Errorf("failed to unmarshal onebot response (%s): %w\n%s", caller, err, string(respBody))
}
return &onebotResp, nil
}
// SendMsg sends a message via OneBot.
// targetType: "group" or "private"
// targetID: QQ group ID or user ID
// msg: message content
// hasAt: whether to prepend an @mention
// atTargetID: the QQ ID to @mention
func (c *Client) SendMsg(targetType string, targetID int64, msg string, hasAt bool, atTargetID int64) (*APIResponse, error) {
// Build message with optional @mention.
message := msg
if hasAt && atTargetID > 0 {
message = fmt.Sprintf("[CQ:at,qq=%d] %s", atTargetID, msg)
}
var endpoint string
var onebotReq map[string]interface{}
switch targetType {
case "group":
endpoint = "/send_group_msg"
onebotReq = map[string]interface{}{
"group_id": targetID,
"message": message,
}
case "private":
endpoint = "/send_private_msg"
onebotReq = map[string]interface{}{
"user_id": targetID,
"message": message,
}
default:
return nil, fmt.Errorf("invalid targetType: %s, must be 'group' or 'private'", targetType)
}
reqBody, err := json.Marshal(onebotReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[OneBot] SendMsg -> %s (%s): %s", endpoint, targetType, message))
}
respBody, err := c.sendRequest(http.MethodPost, endpoint, reqBody)
if err != nil {
return nil, err
}
return c.parseResponse(respBody, "SendMsg")
}
// RecallMsg recalls (deletes) a sent message via OneBot.
func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
reqBody, err := json.Marshal(map[string]interface{}{
"message_id": msgID,
})
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[OneBot] RecallMsg -> /delete_msg: %d", msgID))
}
respBody, err := c.sendRequest(http.MethodPost, "/delete_msg", reqBody)
if err != nil {
return nil, err
}
return c.parseResponse(respBody, "RecallMsg")
}
// GetGroupList retrieves the list of joined groups from OneBot.
func (c *Client) GetGroupList() (*APIResponse, error) {
if actionLogEnabled() {
postLog.Debug("[OneBot] GetGroupList -> /get_group_list")
}
respBody, err := c.sendRequest(http.MethodGet, "/get_group_list", nil)
if err != nil {
return nil, err
}
return c.parseResponse(respBody, "GetGroupList")
}
// GetGroupInfo retrieves detailed information about a specific group from OneBot.
func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
reqBody, err := json.Marshal(map[string]interface{}{
"group_id": groupID,
})
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[OneBot] GetGroupInfo -> /get_group_info: %d", groupID))
}
respBody, err := c.sendRequest(http.MethodPost, "/get_group_info", reqBody)
if err != nil {
return nil, err
}
return c.parseResponse(respBody, "GetGroupInfo")
}
// GetFriendsList retrieves the friends list from OneBot.
func (c *Client) GetFriendsList() (*APIResponse, error) {
if actionLogEnabled() {
postLog.Debug("[OneBot] GetFriendsList -> /get_friend_list")
}
respBody, err := c.sendRequest(http.MethodGet, "/get_friend_list", nil)
if err != nil {
return nil, err
}
return c.parseResponse(respBody, "GetFriendsList")
}
// Listen connects to the OneBot WebSocket server and calls onEvent for every raw
// message. It blocks forever, reconnecting every 5s after a disconnect, until
// Stop is called. Run it in a goroutine.
func (c *Client) Listen(onEvent func(raw []byte)) {
for {
select {
case <-c.stopCh:
return
default:
}
c.listenOnce(onEvent)
postLog.Warning("[OneBot] WebSocket disconnected, reconnecting in 5s...")
select {
case <-c.stopCh:
return
case <-time.After(5 * time.Second):
}
}
}
// listenOnce connects to the OneBot WebSocket and reads events until the
// connection drops or Stop is called.
func (c *Client) listenOnce(onEvent func(raw []byte)) {
wsURL := fmt.Sprintf("ws://%s:%s/", c.addr, c.port)
header := http.Header{}
if c.token != "" {
wsURL += "?access_token=" + url.QueryEscape(c.token)
header.Set("Authorization", "Bearer "+c.token)
}
dialer := *websocket.DefaultDialer
dialer.Proxy = netproxy.ProxyFunc(c.useProxy)
conn, _, err := dialer.Dial(wsURL, header)
if err != nil {
postLog.Error(fmt.Sprintf("[OneBot] Failed to connect to OneBot WebSocket: %v", err))
return
}
c.connMu.Lock()
c.conn = conn
c.connMu.Unlock()
defer func() {
c.connMu.Lock()
if c.conn == conn {
c.conn = nil
}
c.connMu.Unlock()
conn.Close()
}()
postLog.Info(fmt.Sprintf("[OneBot] Connected to OneBot WebSocket at %s", wsURL))
for {
select {
case <-c.stopCh:
return
default:
}
_, msgBytes, err := conn.ReadMessage()
if err != nil {
postLog.Error(fmt.Sprintf("[OneBot] WebSocket read error: %v", err))
return
}
onEvent(msgBytes)
}
}
// Stop closes any open WebSocket connection and unblocks the Listen reconnect loop.
func (c *Client) Stop() {
c.stopOnce.Do(func() { close(c.stopCh) })
c.connMu.Lock()
defer c.connMu.Unlock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
}
+375
View File
@@ -0,0 +1,375 @@
package qq_onebot
import (
"encoding/json"
"fmt"
"strings"
"nukumizu-backend/config"
"nukumizu-backend/internal/controller"
"nukumizu-backend/internal/node"
"nukumizu-backend/internal/template"
"nukumizu-backend/postLog"
)
// oneBotEvent mirrors a OneBot 11 event pushed over the OneBot WebSocket.
// Only "message" events are handled; notice/request/meta_event are ignored.
type oneBotEvent struct {
PostType string `json:"post_type"` // Identifies "message", "notice", "request", or "meta_event"
MessageType string `json:"message_type"` // Identifies "private" or "group"
GroupID int64 `json:"group_id"` // Only present for group messages
UserID int64 `json:"user_id"` // The sender's QQ ID
RawMessage string `json:"raw_message"` // The raw message text
Message json.RawMessage `json:"message"` // The message content, which may include CQ codes
Sender struct { // The sender's information
UserID int64 `json:"user_id"` // The sender's QQ ID
Nickname string `json:"nickname"` // The sender's nickname
} `json:"sender"`
SelfID int64 `json:"self_id"` // The bot's QQ ID
SubType string `json:"sub_type"` // The subtype of the message, e.g., "normal", "anonymous", etc.
}
// QQController handles QQ Bot interactions by connecting directly to OneBot.
type QQController struct {
cfg config.OneBotConfig
onebotClient *Client
}
// NewQQController creates a new QQ (OneBot) controller.
func NewQQController(cfg config.OneBotConfig) *QQController {
q := &QQController{cfg: cfg}
if cfg.Enabled {
q.onebotClient = NewClient(cfg.OneBotAddr, cfg.OneBotPort, cfg.OneBotToken, cfg.NetworkUseProxy)
}
return q
}
// Name returns the controller name.
func (q *QQController) Name() string {
return "qq_onebot"
}
// Start initializes the QQ controller and starts the NapCat WebSocket listener.
func (q *QQController) Start() error {
if !q.cfg.Enabled {
// postLog.Info("QQ (Napcat) controller is disabled")
return nil
}
if q.onebotClient == nil {
postLog.Warning("QQ (OneBot) controller enabled but OneBot client is nil")
return nil
}
postLog.Info("QQ (OneBot) controller started, connecting to OneBot WebSocket...")
go func() {
defer func() {
if r := recover(); r != nil {
postLog.Error(fmt.Sprintf("OneBot WS listener panic recovered: %v", r))
}
}()
q.onebotClient.Listen(q.handleOneBotEvent)
}()
return nil
}
// Stop shuts down the QQ controller and its WebSocket listener.
func (q *QQController) Stop() {
if q.onebotClient != nil {
q.onebotClient.Stop()
}
postLog.Info("QQ (OneBot) controller stopped")
}
// IsEnabled returns whether the controller is enabled.
func (q *QQController) IsEnabled() bool {
return q.cfg.Enabled
}
// IsMarkdown returns whether the channel renders Markdown, per its markdown
// setting in config.json.
func (q *QQController) IsMarkdown() bool {
return q.cfg.Markdown
}
// handleOneBotEvent processes a raw OneBot event received from the OneBot WebSocket.
func (q *QQController) handleOneBotEvent(raw []byte) {
var ev oneBotEvent
if err := json.Unmarshal(raw, &ev); err != nil {
postLog.Debug("Failed to parse OneBot WS event: " + err.Error())
return
}
// The configuration is read once per event: the debug guards below are
// evaluated several times, and taking them all from one version keeps a
// concurrent reload from splitting them mid-event.
cfg := config.Current()
if cfg == nil {
return
}
debugMode := cfg.System.DebugMode
showAction := debugMode && cfg.Debug.ShowOneBotAction
if debugMode && cfg.Debug.ShowOneBotMsg {
postLog.Debug("OneBot WS event received: " + string(raw))
}
// Only handle message events; ignore notice/request/meta_event.
if ev.PostType != "message" {
if showAction {
postLog.Debug("Ignoring OneBot WS event: " + string(raw))
}
return
}
// Ignore messages the bot itself sent (echo prevention).
if q.isSelfMessage(ev) && !debugMode {
return
}
if q.isSelfMessage(ev) && debugMode && cfg.Debug.OneBotIgnoreSelfMsg {
if showAction {
postLog.Debug("Ignoring OneBot WS self message: " + string(raw))
}
return
}
// Determine chat information.
chatID := ev.GroupID
if ev.MessageType == "private" {
chatID = ev.UserID
}
cmd := controller.Command{
RawText: ev.RawMessage,
ChatID: chatID,
ChatType: ev.MessageType,
SenderID: ev.UserID,
}
response := q.processCommand(cmd)
if response == "" {
if showAction {
postLog.Debug("OneBot WS command discarded: " + string(raw))
}
return
}
// Reply in the same chat.
if ev.MessageType == "private" {
if _, err := q.onebotClient.SendMsg("private", ev.UserID, response, false, 0); err != nil {
postLog.Warning("Failed to send OneBot private reply: " + err.Error())
}
} else {
if _, err := q.onebotClient.SendMsg("group", ev.GroupID, response, false, 0); err != nil {
postLog.Warning("Failed to send OneBot group reply: " + err.Error())
}
}
}
// processCommand validates an incoming message as a command and hands the
// complete command to the unified processor. It returns the response text to
// reply with; an empty response means the message was discarded.
func (q *QQController) processCommand(cmd controller.Command) string {
cfg := config.Current()
text := cmd.RawText
// In "at" listen mode, require an @mention of the bot and strip it before
// parsing, otherwise raw_message like "[CQ:at,qq=123] /list" fails the
// "/" prefix check.
if q.cfg.ListenMethod == "at" {
atMention := fmt.Sprintf("[CQ:at,qq=%d]", q.cfg.BotQQID)
if !strings.Contains(text, atMention) {
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowOneBotAction {
postLog.Debug("OneBot WS message ignored (no @mention): " + text)
}
return "" // Not mentioned, ignore.
}
text = strings.ReplaceAll(text, atMention, "")
}
// First check whether the received message is a command.
parsed, ok := controller.ParseCommand(text)
if !ok {
return "" // Not a command, discard.
}
parsed.ChatID = cmd.ChatID
parsed.ChatType = cmd.ChatType
parsed.SenderID = cmd.SenderID
parsed.Source = q.Name()
// Hand the complete command to the unified processor, which checks group
// vs private, trusted groups, admin permissions, and executes it.
response, err := controller.GetManager().Trigger(parsed, q.trustedGroupIDs(), q.adminIDs(), q.cfg.ListenMethod)
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowTriggerCmdEcho {
postLog.Debug(fmt.Sprintf("[qq_onebot] 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 {
postLog.Error("OneBot command processing failed: " + err.Error())
return ""
}
return response
}
// isSelfMessage returns true when the event was generated by the bot itself.
func (q *QQController) isSelfMessage(ev oneBotEvent) bool {
if q.cfg.BotQQID > 0 && ev.SelfID == q.cfg.BotQQID {
return true
}
if ev.UserID == ev.SelfID {
return true
}
return false
}
// adminIDs returns the QQ admin IDs from bot_user_config.json.
func (q *QQController) adminIDs() []string {
if c := config.BotUsers(); c != nil {
return c.QQ.Admins.IDs()
}
return nil
}
// trustedGroupIDs returns the QQ trusted group IDs from bot_user_config.json.
func (q *QQController) trustedGroupIDs() []string {
if c := config.BotUsers(); c != nil {
return c.QQ.TrustedGroups.IDs()
}
return nil
}
// SendMessage sends an automatic message (e.g. the bot initialization message
// and the startup server list) to all QQ trusted groups and admins. Each
// member's opt-out options in bot_user_config.json (e.g. EventBotStarted for
// event_bot_started messages) are honored per recipient.
func (q *QQController) SendMessage(message controller.Message) error {
if !q.cfg.Enabled {
return nil
}
// Only notify trusted groups and admins whose options allow this message type.
if uc := config.BotUsers(); uc != nil {
for groupID, opts := range uc.QQ.TrustedGroups {
if !controller.MemberReceives(opts, message.Type) {
continue
}
q.sendGroupMessage(groupID, message.Content)
}
for adminID, opts := range uc.QQ.Admins {
if !controller.MemberReceives(opts, message.Type) {
continue
}
q.sendPrivateMessage(adminID, message.Content)
}
}
return nil
}
// SendStatusChange sends a status change notification via QQ.
func (q *QQController) SendStatusChange(change node.StatusChange) error {
if !q.cfg.Enabled {
return nil
}
cfg := config.Current()
params := template.BuildParamsFromStatusChange(change)
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, q.cfg.Markdown)
// Only notify trusted groups and admins whose event_status_notify is true.
if uc := config.BotUsers(); uc != nil {
for groupID, opts := range uc.QQ.TrustedGroups {
if !opts.EventStatusNotify {
continue
}
q.sendGroupMessage(groupID, message)
}
for adminID, opts := range uc.QQ.Admins {
if !opts.EventStatusNotify {
continue
}
q.sendPrivateMessage(adminID, message)
}
}
return nil
}
// SendServerList sends the server list via QQ.
func (q *QQController) SendServerList(onlineServers, offlineServers string) error {
if !q.cfg.Enabled {
return nil
}
cfg := config.Current()
params := template.BuildParamsFromServerList()
message := template.Render(cfg.ControllerMessage.ServerList, params, q.cfg.Markdown)
for _, groupID := range q.trustedGroupIDs() {
q.sendGroupMessage(groupID, message)
}
return nil
}
// SendExecuteResult sends a command execution result via QQ.
func (q *QQController) SendExecuteResult(serverName, serverUUID, command, result string) error {
if !q.cfg.Enabled {
return nil
}
cfg := config.Current()
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, q.cfg.Markdown)
for _, groupID := range q.trustedGroupIDs() {
q.sendGroupMessage(groupID, message)
}
return nil
}
// SendAlert sends an alert submitted through the incoming webhook API to all QQ
// trusted groups and admins.
func (q *QQController) SendAlert(alert controller.Alert) error {
if !q.cfg.Enabled {
return nil
}
return q.SendMessage(controller.Message{
Source: q.Name(),
Content: alert.Render(q.cfg.Markdown),
Type: controller.MessageTypeAlert,
})
}
func (q *QQController) sendGroupMessage(groupID string, message string) {
if q.onebotClient == nil {
postLog.Warning("Cannot send QQ group message: OneBot client not initialized")
return
}
var groupIDInt int64
if _, err := fmt.Sscanf(groupID, "%d", &groupIDInt); err != nil || groupIDInt == 0 {
postLog.Warning(fmt.Sprintf("Invalid QQ group ID: %s", groupID))
return
}
if _, err := q.onebotClient.SendMsg("group", groupIDInt, message, false, 0); err != nil {
postLog.Warning(fmt.Sprintf("Failed to send QQ group message to %s: %v", groupID, err))
}
}
func (q *QQController) sendPrivateMessage(userID string, message string) {
if q.onebotClient == nil {
postLog.Warning("Cannot send QQ private message: OneBot client not initialized")
return
}
var userIDInt int64
if _, err := fmt.Sscanf(userID, "%d", &userIDInt); err != nil || userIDInt == 0 {
postLog.Warning(fmt.Sprintf("Invalid QQ user ID: %s", userID))
return
}
if _, err := q.onebotClient.SendMsg("private", userIDInt, message, false, 0); err != nil {
postLog.Warning(fmt.Sprintf("Failed to send QQ private message to %s: %v", userID, err))
}
}