style(qq_onebot): rename all NapCat related to OneBot
Build / ubuntu-latest (push) Failing after 3m6s
Build / windows-latest (push) Failing after 11m26s

This commit is contained in:
NanamiAdmin committed 2026-10-10 11:34:22 +08:00
1 parent 72d0d587cb
commit 40e3663dc8
8 files changed
+100 -103

No files matched your search

@@ -1,4 +1,4 @@
package qq_napcat
package qq_onebot
import (
"bytes"
@@ -17,16 +17,16 @@ import (
"nukumizu-backend/postLog"
)
// actionLogEnabled reports whether the NapCat HTTP API methods echo each action
// they send, per the showNapcatAction toggle. Unlike the WebSocket message path
// 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.ShowNapcatAction
return cfg != nil && cfg.Debug.ShowOneBotAction
}
// APIResponse mirrors NapCat's HTTP API response envelope.
// APIResponse mirrors OneBot's HTTP API response envelope.
type APIResponse struct {
Status string `json:"status"`
RetCode int `json:"retcode"`
@@ -34,9 +34,9 @@ type APIResponse struct {
Data json.RawMessage `json:"data"`
}
// Client is the HTTP + WebSocket client for a single NapCat instance.
// Client is the HTTP + WebSocket client for a single OneBot instance.
// It both listens for incoming OneBot events over WebSocket and issues
// outbound NapCat API calls over HTTP.
// outbound OneBot API calls over HTTP.
type Client struct {
addr string
port string
@@ -50,7 +50,7 @@ type Client struct {
stopOnce sync.Once
}
// NewClient creates a NapCat client for the given host/port/token. When
// 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 {
@@ -68,9 +68,9 @@ func (c *Client) baseURL() string {
return fmt.Sprintf("http://%s:%s", c.addr, c.port)
}
// sendRequest performs an HTTP call to NapCat, injecting access_token into POST
// 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 NapCat Web UI).
// created in the OneBot Web UI).
func (c *Client) sendRequest(method, endpoint string, body []byte) ([]byte, error) {
url := c.baseURL() + endpoint
@@ -105,28 +105,28 @@ func (c *Client) sendRequest(method, endpoint string, body []byte) ([]byte, erro
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request to napcat: %w", err)
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 napcat response: %w", err)
return nil, fmt.Errorf("failed to read onebot response: %w", err)
}
return respBody, nil
}
// parseResponse unmarshals NapCat's raw response body into an APIResponse.
// parseResponse unmarshals OneBot's raw response body into an APIResponse.
func (c *Client) parseResponse(respBody []byte, caller string) (*APIResponse, error) {
var napcatResp APIResponse
if err := json.Unmarshal(respBody, &napcatResp); err != nil {
return nil, fmt.Errorf("failed to unmarshal napcat response (%s): %w\n%s", caller, err, string(respBody))
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 &napcatResp, nil
return &onebotResp, nil
}
// SendMsg sends a message via NapCat.
// SendMsg sends a message via OneBot.
// targetType: "group" or "private"
// targetID: QQ group ID or user ID
// msg: message content
@@ -140,18 +140,18 @@ func (c *Client) SendMsg(targetType string, targetID int64, msg string, hasAt bo
}
var endpoint string
var napcatReq map[string]interface{}
var onebotReq map[string]interface{}
switch targetType {
case "group":
endpoint = "/send_group_msg"
napcatReq = map[string]interface{}{
onebotReq = map[string]interface{}{
"group_id": targetID,
"message": message,
}
case "private":
endpoint = "/send_private_msg"
napcatReq = map[string]interface{}{
onebotReq = map[string]interface{}{
"user_id": targetID,
"message": message,
}
@@ -159,13 +159,13 @@ func (c *Client) SendMsg(targetType string, targetID int64, msg string, hasAt bo
return nil, fmt.Errorf("invalid targetType: %s, must be 'group' or 'private'", targetType)
}
reqBody, err := json.Marshal(napcatReq)
reqBody, err := json.Marshal(onebotReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[Napcat] SendMsg -> %s (%s): %s", endpoint, targetType, message))
postLog.Debug(fmt.Sprintf("[OneBot] SendMsg -> %s (%s): %s", endpoint, targetType, message))
}
respBody, err := c.sendRequest(http.MethodPost, endpoint, reqBody)
@@ -176,7 +176,7 @@ func (c *Client) SendMsg(targetType string, targetID int64, msg string, hasAt bo
return c.parseResponse(respBody, "SendMsg")
}
// RecallMsg recalls (deletes) a sent message via NapCat.
// 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,
@@ -186,7 +186,7 @@ func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
}
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[Napcat] RecallMsg -> /delete_msg: %d", msgID))
postLog.Debug(fmt.Sprintf("[OneBot] RecallMsg -> /delete_msg: %d", msgID))
}
respBody, err := c.sendRequest(http.MethodPost, "/delete_msg", reqBody)
@@ -197,10 +197,10 @@ func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
return c.parseResponse(respBody, "RecallMsg")
}
// GetGroupList retrieves the list of joined groups from NapCat.
// GetGroupList retrieves the list of joined groups from OneBot.
func (c *Client) GetGroupList() (*APIResponse, error) {
if actionLogEnabled() {
postLog.Debug("[Napcat] GetGroupList -> /get_group_list")
postLog.Debug("[OneBot] GetGroupList -> /get_group_list")
}
respBody, err := c.sendRequest(http.MethodGet, "/get_group_list", nil)
@@ -211,7 +211,7 @@ func (c *Client) GetGroupList() (*APIResponse, error) {
return c.parseResponse(respBody, "GetGroupList")
}
// GetGroupInfo retrieves detailed information about a specific group from NapCat.
// 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,
@@ -221,7 +221,7 @@ func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
}
if actionLogEnabled() {
postLog.Debug(fmt.Sprintf("[Napcat] GetGroupInfo -> /get_group_info: %d", groupID))
postLog.Debug(fmt.Sprintf("[OneBot] GetGroupInfo -> /get_group_info: %d", groupID))
}
respBody, err := c.sendRequest(http.MethodPost, "/get_group_info", reqBody)
@@ -232,10 +232,10 @@ func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
return c.parseResponse(respBody, "GetGroupInfo")
}
// GetFriendsList retrieves the friends list from NapCat.
// GetFriendsList retrieves the friends list from OneBot.
func (c *Client) GetFriendsList() (*APIResponse, error) {
if actionLogEnabled() {
postLog.Debug("[Napcat] GetFriendsList -> /get_friend_list")
postLog.Debug("[OneBot] GetFriendsList -> /get_friend_list")
}
respBody, err := c.sendRequest(http.MethodGet, "/get_friend_list", nil)
@@ -246,7 +246,7 @@ func (c *Client) GetFriendsList() (*APIResponse, error) {
return c.parseResponse(respBody, "GetFriendsList")
}
// Listen connects to the NapCat WebSocket server and calls onEvent for every raw
// 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)) {
@@ -259,7 +259,7 @@ func (c *Client) Listen(onEvent func(raw []byte)) {
c.listenOnce(onEvent)
postLog.Warning("[Napcat] WebSocket disconnected, reconnecting in 5s...")
postLog.Warning("[OneBot] WebSocket disconnected, reconnecting in 5s...")
select {
case <-c.stopCh:
return
@@ -268,7 +268,7 @@ func (c *Client) Listen(onEvent func(raw []byte)) {
}
}
// listenOnce connects to the NapCat WebSocket and reads events until the
// 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)
@@ -282,7 +282,7 @@ func (c *Client) listenOnce(onEvent func(raw []byte)) {
dialer.Proxy = netproxy.ProxyFunc(c.useProxy)
conn, _, err := dialer.Dial(wsURL, header)
if err != nil {
postLog.Error(fmt.Sprintf("[Napcat] Failed to connect to NapCat WebSocket: %v", err))
postLog.Error(fmt.Sprintf("[OneBot] Failed to connect to OneBot WebSocket: %v", err))
return
}
@@ -298,7 +298,7 @@ func (c *Client) listenOnce(onEvent func(raw []byte)) {
conn.Close()
}()
postLog.Info(fmt.Sprintf("[Napcat] Connected to NapCat WebSocket at %s", wsURL))
postLog.Info(fmt.Sprintf("[OneBot] Connected to OneBot WebSocket at %s", wsURL))
for {
select {
@@ -309,7 +309,7 @@ func (c *Client) listenOnce(onEvent func(raw []byte)) {
_, msgBytes, err := conn.ReadMessage()
if err != nil {
postLog.Error(fmt.Sprintf("[Napcat] WebSocket read error: %v", err))
postLog.Error(fmt.Sprintf("[OneBot] WebSocket read error: %v", err))
return
}
@@ -1,4 +1,4 @@
package qq_napcat
package qq_onebot
import (
"encoding/json"
@@ -12,7 +12,7 @@ import (
"nukumizu-backend/postLog"
)
// oneBotEvent mirrors a OneBot 11 event pushed over the NapCat WebSocket.
// 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"
@@ -29,24 +29,24 @@ type oneBotEvent struct {
SubType string `json:"sub_type"` // The subtype of the message, e.g., "normal", "anonymous", etc.
}
// QQController handles QQ Bot interactions by connecting directly to NapCat.
// QQController handles QQ Bot interactions by connecting directly to OneBot.
type QQController struct {
cfg config.QQConfig
napcatClient *Client
onebotClient *Client
}
// NewQQController creates a new QQ (Napcat) controller.
// NewQQController creates a new QQ (OneBot) controller.
func NewQQController(cfg config.QQConfig) *QQController {
q := &QQController{cfg: cfg}
if cfg.Enabled {
q.napcatClient = NewClient(cfg.NapcatAddr, cfg.NapcatPort, cfg.NapcatToken, cfg.NetworkUseProxy)
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(napcat)"
return "qq(onebot)"
}
// Start initializes the QQ controller and starts the NapCat WebSocket listener.
@@ -55,19 +55,19 @@ func (q *QQController) Start() error {
// postLog.Info("QQ (Napcat) controller is disabled")
return nil
}
if q.napcatClient == nil {
postLog.Warning("QQ (Napcat) controller enabled but NapCat client is nil")
if q.onebotClient == nil {
postLog.Warning("QQ (OneBot) controller enabled but OneBot client is nil")
return nil
}
postLog.Info("QQ (Napcat) controller started, connecting to NapCat WebSocket...")
postLog.Info("QQ (OneBot) controller started, connecting to OneBot WebSocket...")
go func() {
defer func() {
if r := recover(); r != nil {
postLog.Error(fmt.Sprintf("Napcat WS listener panic recovered: %v", r))
postLog.Error(fmt.Sprintf("OneBot WS listener panic recovered: %v", r))
}
}()
q.napcatClient.Listen(q.handleNapcatEvent)
q.onebotClient.Listen(q.handleOneBotEvent)
}()
return nil
@@ -75,10 +75,10 @@ func (q *QQController) Start() error {
// Stop shuts down the QQ controller and its WebSocket listener.
func (q *QQController) Stop() {
if q.napcatClient != nil {
q.napcatClient.Stop()
if q.onebotClient != nil {
q.onebotClient.Stop()
}
postLog.Info("QQ (Napcat) controller stopped")
postLog.Info("QQ (OneBot) controller stopped")
}
// IsEnabled returns whether the controller is enabled.
@@ -92,11 +92,11 @@ func (q *QQController) IsMarkdown() bool {
return q.cfg.Markdown
}
// handleNapcatEvent processes a raw OneBot event received from the NapCat WebSocket.
func (q *QQController) handleNapcatEvent(raw []byte) {
// 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 NapCat WS event: " + err.Error())
postLog.Debug("Failed to parse OneBot WS event: " + err.Error())
return
}
@@ -108,16 +108,16 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
return
}
debugMode := cfg.System.DebugMode
showAction := debugMode && cfg.Debug.ShowNapcatAction
showAction := debugMode && cfg.Debug.ShowOneBotAction
if debugMode && cfg.Debug.ShowNapcatMsg {
postLog.Debug("Napcat WS event received: " + string(raw))
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 Napcat WS event: " + string(raw))
postLog.Debug("Ignoring OneBot WS event: " + string(raw))
}
return
}
@@ -126,9 +126,9 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
if q.isSelfMessage(ev) && !debugMode {
return
}
if q.isSelfMessage(ev) && debugMode && cfg.Debug.NapcatIgnoreSelfMsg {
if q.isSelfMessage(ev) && debugMode && cfg.Debug.OneBotIgnoreSelfMsg {
if showAction {
postLog.Debug("Ignoring Napcat WS self message: " + string(raw))
postLog.Debug("Ignoring OneBot WS self message: " + string(raw))
}
return
}
@@ -149,19 +149,19 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
response := q.processCommand(cmd)
if response == "" {
if showAction {
postLog.Debug("Napcat WS command discarded: " + string(raw))
postLog.Debug("OneBot WS command discarded: " + string(raw))
}
return
}
// Reply in the same chat.
if ev.MessageType == "private" {
if _, err := q.napcatClient.SendMsg("private", ev.UserID, response, false, 0); err != nil {
postLog.Warning("Failed to send NapCat private reply: " + err.Error())
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.napcatClient.SendMsg("group", ev.GroupID, response, false, 0); err != nil {
postLog.Warning("Failed to send NapCat group reply: " + err.Error())
if _, err := q.onebotClient.SendMsg("group", ev.GroupID, response, false, 0); err != nil {
postLog.Warning("Failed to send OneBot group reply: " + err.Error())
}
}
}
@@ -179,8 +179,8 @@ func (q *QQController) processCommand(cmd controller.Command) string {
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.ShowNapcatAction {
postLog.Debug("Napcat WS message ignored (no @mention): " + text)
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowOneBotAction {
postLog.Debug("OneBot WS message ignored (no @mention): " + text)
}
return "" // Not mentioned, ignore.
}
@@ -202,10 +202,10 @@ func (q *QQController) processCommand(cmd controller.Command) string {
// 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_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_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("Napcat command processing failed: " + err.Error())
postLog.Error("OneBot command processing failed: " + err.Error())
return ""
}
return response
@@ -341,8 +341,8 @@ func (q *QQController) SendAlert(alert controller.Alert) error {
}
func (q *QQController) sendGroupMessage(groupID string, message string) {
if q.napcatClient == nil {
postLog.Warning("Cannot send QQ group message: NapCat client not initialized")
if q.onebotClient == nil {
postLog.Warning("Cannot send QQ group message: OneBot client not initialized")
return
}
@@ -352,14 +352,14 @@ func (q *QQController) sendGroupMessage(groupID string, message string) {
return
}
if _, err := q.napcatClient.SendMsg("group", groupIDInt, message, false, 0); err != nil {
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.napcatClient == nil {
postLog.Warning("Cannot send QQ private message: NapCat client not initialized")
if q.onebotClient == nil {
postLog.Warning("Cannot send QQ private message: OneBot client not initialized")
return
}
@@ -369,7 +369,7 @@ func (q *QQController) sendPrivateMessage(userID string, message string) {
return
}
if _, err := q.napcatClient.SendMsg("private", userIDInt, message, false, 0); err != nil {
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))
}
}