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
+118 -121

No files matched your search

+7 -7
View File
@@ -65,15 +65,15 @@ func LoadGlobalConfig(configPath string) (*Config, error) {
cfg.System.ListenPort = "8080" cfg.System.ListenPort = "8080"
} }
// Apply defaults for QQ controller. // Apply defaults for QQ_OneBot controller.
if cfg.ControllerMethod.QQ.ListenMethod == "" { if cfg.ControllerMethod.QQ_OneBot.ListenMethod == "" {
cfg.ControllerMethod.QQ.ListenMethod = "global" cfg.ControllerMethod.QQ_OneBot.ListenMethod = "global"
} }
if cfg.ControllerMethod.QQ.NapcatAddr == "" { if cfg.ControllerMethod.QQ_OneBot.OneBotAddr == "" {
cfg.ControllerMethod.QQ.NapcatAddr = "127.0.0.1" cfg.ControllerMethod.QQ_OneBot.OneBotAddr = "127.0.0.1"
} }
if cfg.ControllerMethod.QQ.NapcatPort == "" { if cfg.ControllerMethod.QQ_OneBot.OneBotPort == "" {
cfg.ControllerMethod.QQ.NapcatPort = "3000" cfg.ControllerMethod.QQ_OneBot.OneBotPort = "3000"
} }
// Apply defaults for Telegram controller. // Apply defaults for Telegram controller.
+12 -12
View File
@@ -15,12 +15,12 @@ type SystemConfig struct {
// DebugConfig holds debug-level configuration. // DebugConfig holds debug-level configuration.
type DebugConfig struct { type DebugConfig struct {
ShowNapcatMsg bool `json:"showNapcatMsg"` ShowOneBotMsg bool `json:"showOneBotMsg"`
ShowNapcatAction bool `json:"showNapcatAction"` ShowOneBotAction bool `json:"showOneBotAction"`
ShowTelegramMsg bool `json:"showTelegramMsg"` ShowTelegramMsg bool `json:"showTelegramMsg"`
ShowTriggerCmdEcho bool `json:"showTriggerCmdEcho"` ShowTriggerCmdEcho bool `json:"showTriggerCmdEcho"`
ShowKomariTaskEcho bool `json:"showKomariTaskEcho"` ShowKomariTaskEcho bool `json:"showKomariTaskEcho"`
NapcatIgnoreSelfMsg bool `json:"napcatIgnoreSelfMsg"` OneBotIgnoreSelfMsg bool `json:"oneBotIgnoreSelfMsg"`
} }
// KomariAccount holds Komari login credentials. // KomariAccount holds Komari login credentials.
@@ -35,14 +35,14 @@ type KomariConfig struct {
Account KomariAccount `json:"account"` Account KomariAccount `json:"account"`
} }
// QQConfig holds QQ (Napcat) Bot controller configuration. // QQConfig holds QQ (OneBot) Bot controller configuration.
type QQConfig struct { type OneBotConfig struct {
Markdown bool `json:"markdown"` Markdown bool `json:"markdown"`
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
NetworkUseProxy bool `json:"networkUseProxy"` NetworkUseProxy bool `json:"networkUseProxy"`
NapcatAddr string `json:"napcatAddr"` OneBotAddr string `json:"oneBotAddr"`
NapcatPort string `json:"napcatPort"` OneBotPort string `json:"oneBotPort"`
NapcatToken string `json:"napcatToken"` OneBotToken string `json:"oneBotToken"`
BotQQID int64 `json:"botQQID"` BotQQID int64 `json:"botQQID"`
ListenMethod string `json:"listenMethod"` ListenMethod string `json:"listenMethod"`
} }
@@ -96,7 +96,7 @@ type WebhookConfig struct {
// ControllerMethodConfig holds all controller method configurations. // ControllerMethodConfig holds all controller method configurations.
type ControllerMethodConfig struct { type ControllerMethodConfig struct {
QQ QQConfig `json:"qq(napcat)"` QQ_OneBot OneBotConfig `json:"qq_onebot"`
Telegram TelegramConfig `json:"telegram"` Telegram TelegramConfig `json:"telegram"`
Email EmailConfig `json:"email"` Email EmailConfig `json:"email"`
Ntfy NtfyConfig `json:"ntfy"` Ntfy NtfyConfig `json:"ntfy"`
@@ -119,7 +119,7 @@ type WebhookEndpointConfig struct {
Token string `json:"token"` Token string `json:"token"`
// NotifyPipes lists the notification channels the alert is delivered to, by // NotifyPipes lists the notification channels the alert is delivered to, by
// controller name (e.g. "qq(napcat)", "telegram", "email", "ntfy", // controller name (e.g. "qq(onebot)", "telegram", "email", "ntfy",
// "webhook"). // "webhook").
NotifyPipes []string `json:"notifyPipes"` NotifyPipes []string `json:"notifyPipes"`
} }
@@ -216,7 +216,7 @@ func (m BotUserMembers) IDs() []string {
return ids return ids
} }
// BotUser_QQConfig holds the admins and trusted groups for the QQ (Napcat) bot. // BotUser_QQConfig holds the admins and trusted groups for the QQ (OneBot) bot.
type BotUser_QQConfig struct { type BotUser_QQConfig struct {
Admins BotUserMembers `json:"admins"` Admins BotUserMembers `json:"admins"`
TrustedGroups BotUserMembers `json:"trustedGroups"` TrustedGroups BotUserMembers `json:"trustedGroups"`
@@ -232,7 +232,7 @@ type BotUser_TelegramConfig struct {
// and trusted groups (chat targets) for each bot channel separately from the // and trusted groups (chat targets) for each bot channel separately from the
// main config.json. // main config.json.
type BotUserConfig struct { type BotUserConfig struct {
QQ BotUser_QQConfig `json:"qq(napcat)"` QQ BotUser_QQConfig `json:"qq(onebot)"`
Telegram BotUser_TelegramConfig `json:"telegram"` Telegram BotUser_TelegramConfig `json:"telegram"`
} }
-3
View File
@@ -1473,7 +1473,6 @@
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -1596,7 +1595,6 @@
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.25.0", "esbuild": "^0.25.0",
"fdir": "^6.4.4", "fdir": "^6.4.4",
@@ -1671,7 +1669,6 @@
"resolved": "https://registry.npmjs.org/vue/-/vue-3.5.42.tgz", "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.42.tgz",
"integrity": "sha512-4RyHQTbQvOPs3MfvUO1Sg0YRrKNnA0mAVtvpd12Tg1fKDN7OHBUl1IqSn8zGJjK9nI3NkNp8cgTpVrSZC5TTcA==", "integrity": "sha512-4RyHQTbQvOPs3MfvUO1Sg0YRrKNnA0mAVtvpd12Tg1fKDN7OHBUl1IqSn8zGJjK9nI3NkNp8cgTpVrSZC5TTcA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@vue/compiler-dom": "3.5.42", "@vue/compiler-dom": "3.5.42",
"@vue/compiler-sfc": "3.5.42", "@vue/compiler-sfc": "3.5.42",
+9 -9
View File
@@ -26,12 +26,12 @@ const sections = [
hint: 'Per-module verbosity for the bot pipes.', hint: 'Per-module verbosity for the bot pipes.',
root: ['debug'], root: ['debug'],
fields: [ fields: [
{ key: 'showNapcatMsg', type: 'bool', label: 'NapCat messages' }, { key: 'showOneBotMsg', type: 'bool', label: 'OneBot messages' },
{ key: 'showNapcatAction', type: 'bool', label: 'NapCat actions' }, { key: 'showOneBotAction', type: 'bool', label: 'OneBot actions' },
{ key: 'showTelegramMsg', type: 'bool', label: 'Telegram messages' }, { key: 'showTelegramMsg', type: 'bool', label: 'Telegram messages' },
{ key: 'showTriggerCmdEcho', type: 'bool', label: 'Trigger command echo' }, { key: 'showTriggerCmdEcho', type: 'bool', label: 'Trigger command echo' },
{ key: 'showKomariTaskEcho', type: 'bool', label: 'Komari task echo' }, { key: 'showKomariTaskEcho', type: 'bool', label: 'Komari task echo' },
{ key: 'napcatIgnoreSelfMsg', type: 'bool', label: 'Ignore NapCat self messages' } { key: 'onebotIgnoreSelfMsg', type: 'bool', label: 'Ignore OneBot self messages' }
] ]
}, },
{ {
@@ -60,16 +60,16 @@ const sections = [
] ]
}, },
{ {
id: 'qq', id: 'qq_onebot',
title: 'QQ controller (NapCat)', title: 'QQ controller (OneBot)',
root: ['controllerMethod', 'qq(napcat)'], root: ['controllerMethod', 'qq_onebot'],
fields: [ fields: [
{ key: 'enabled', type: 'bool', label: 'Enabled' }, { key: 'enabled', type: 'bool', label: 'Enabled' },
{ key: 'markdown', type: 'bool', label: 'Markdown', help: 'Send the formatted variant of the templates (code blocks, inline code).' }, { key: 'markdown', type: 'bool', label: 'Markdown', help: 'Send the formatted variant of the templates (code blocks, inline code).' },
{ key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' }, { key: 'networkUseProxy', type: 'bool', label: 'Use network proxy' },
{ key: 'napcatAddr', type: 'text', label: 'NapCat address' }, { key: 'oneBotAddr', type: 'text', label: 'OneBot address' },
{ key: 'napcatPort', type: 'text', label: 'NapCat port' }, { key: 'oneBotPort', type: 'text', label: 'OneBot port' },
{ key: 'napcatToken', type: 'password', label: 'NapCat token' }, { key: 'oneBotToken', type: 'password', label: 'OneBot token' },
{ key: 'botQQID', type: 'number', label: 'Bot QQ ID' }, { key: 'botQQID', type: 'number', label: 'Bot QQ ID' },
{ key: 'listenMethod', type: 'select', label: 'Listen method', options: ['global', 'at'] } { key: 'listenMethod', type: 'select', label: 'Listen method', options: ['global', 'at'] }
] ]
+1 -1
View File
@@ -6,7 +6,7 @@ import Toggle from '../components/Toggle.vue';
import Modal from '../components/Modal.vue'; import Modal from '../components/Modal.vue';
const CHANNELS = [ const CHANNELS = [
{ key: 'qq(napcat)', label: 'QQ (NapCat)', hint: 'Members are identified by QQ number / group number' }, { key: 'qq_onebot', label: 'QQ (OneBot)', hint: 'Members are identified by QQ number / group number' },
{ key: 'telegram', label: 'Telegram', hint: 'Members are identified by @username or numeric ID / group ID' } { key: 'telegram', label: 'Telegram', hint: 'Members are identified by @username or numeric ID / group ID' }
]; ];
+1 -1
View File
@@ -10,7 +10,7 @@ import Modal from '../components/Modal.vue';
// controller names in config.json (controllerMethod.*), which is exactly what // controller names in config.json (controllerMethod.*), which is exactly what
// the backend matches notifyPipes against. // the backend matches notifyPipes against.
const CHANNELS = [ const CHANNELS = [
{ key: 'qq(napcat)', label: 'QQ' }, { key: 'qq_onebot', label: 'QQ_OneBot' },
{ key: 'telegram', label: 'Telegram' }, { key: 'telegram', label: 'Telegram' },
{ key: 'email', label: 'Email' }, { key: 'email', label: 'Email' },
{ key: 'ntfy', label: 'ntfy' }, { key: 'ntfy', label: 'ntfy' },
+5 -5
View File
@@ -27,7 +27,7 @@ type Command struct {
// Message represents a message to be sent by a controller. // Message represents a message to be sent by a controller.
type Message struct { type Message struct {
Source string // The source pipe (e.g., "telegram", "qq", "napcat") Source string // The source pipe (e.g., "telegram", "qq", "onebot")
Content string // The message content Content string // The message content
ChatID int64 // Chat/group ID where the message should be sent ChatID int64 // Chat/group ID where the message should be sent
Type string // Message type (see MessageType*), used for per-member opt-outs Type string // Message type (see MessageType*), used for per-member opt-outs
@@ -100,7 +100,7 @@ type Controller interface {
// BotController is implemented by controllers that act as chat bots and can // BotController is implemented by controllers that act as chat bots and can
// deliver arbitrary messages, such as the bot initialization message on startup. // deliver arbitrary messages, such as the bot initialization message on startup.
// Only bot-type pipes (QQ/NapCat, Telegram) implement it; notification-only // Only bot-type pipes (QQ_OneBot, Telegram) implement it; notification-only
// pipes (email, ntfy, webhook) do not. // pipes (email, ntfy, webhook) do not.
type BotController interface { type BotController interface {
Controller Controller
@@ -140,7 +140,7 @@ func GetManager() *Manager {
// //
// Controllers are rebuilt wholesale rather than reconfigured in place: each one // Controllers are rebuilt wholesale rather than reconfigured in place: each one
// reads its settings into fields at construction, and two of them own // reads its settings into fields at construction, and two of them own
// connections that cannot be re-pointed (the NapCat WebSocket listener is // connections that cannot be re-pointed (the OneBot WebSocket listener is
// stopped through a sync.Once, the Telegram polling context is created with the // stopped through a sync.Once, the Telegram polling context is created with the
// controller). Replacing the set keeps every channel on the same footing. // controller). Replacing the set keeps every channel on the same footing.
func (m *Manager) NeedsRebuild(next config.ControllerMethodConfig) bool { func (m *Manager) NeedsRebuild(next config.ControllerMethodConfig) bool {
@@ -183,7 +183,7 @@ func (m *Manager) ReplaceAll(next []Controller, method config.ControllerMethodCo
} }
// Start off the calling goroutine, the way startup does: Telegram's getMe // Start off the calling goroutine, the way startup does: Telegram's getMe
// and the NapCat WebSocket handshake would otherwise hold the settings // and the OneBot WebSocket handshake would otherwise hold the settings
// request open for as long as they take. The new controllers are already // request open for as long as they take. The new controllers are already
// routable, and each one can send before Start returns. // routable, and each one can send before Start returns.
for _, ctrl := range next { for _, ctrl := range next {
@@ -201,7 +201,7 @@ func (m *Manager) ReplaceAll(next []Controller, method config.ControllerMethodCo
} }
// ShowBotInitMessage sends the bot initialization message to all enabled // ShowBotInitMessage sends the bot initialization message to all enabled
// bot controllers (QQ/NapCat and Telegram). Notification-only pipes that do // bot controllers (QQ_OneBot and Telegram). Notification-only pipes that do
// not implement BotController are skipped. The message is typed // not implement BotController are skipped. The message is typed
// MessageTypeBotStarted so each controller can honor its members' per-recipient // MessageTypeBotStarted so each controller can honor its members' per-recipient
// EventBotStarted opt-out. It is rendered once per controller because the // EventBotStarted opt-out. It is rendered once per controller because the
+1 -1
View File
@@ -97,7 +97,7 @@ func TestReplaceAllInstallsAndStarts(t *testing.T) {
} }
// TestReplaceAllStopsTheOutgoingSet is the invariant the rebuild relies on: the // TestReplaceAllStopsTheOutgoingSet is the invariant the rebuild relies on: the
// old controllers must be shut down, or a rebuilt NapCat or Telegram controller // old controllers must be shut down, or a rebuilt onebot or Telegram controller
// would leave its previous connection running. // would leave its previous connection running.
func TestReplaceAllStopsTheOutgoingSet(t *testing.T) { func TestReplaceAllStopsTheOutgoingSet(t *testing.T) {
m := newTestManager() m := newTestManager()
@@ -1,4 +1,4 @@
package qq_napcat package qq_onebot
import ( import (
"bytes" "bytes"
@@ -17,16 +17,16 @@ import (
"nukumizu-backend/postLog" "nukumizu-backend/postLog"
) )
// actionLogEnabled reports whether the NapCat HTTP API methods echo each action // actionLogEnabled reports whether the OneBot HTTP API methods echo each action
// they send, per the showNapcatAction toggle. Unlike the WebSocket message path // they send, per the showOneBotAction toggle. Unlike the WebSocket message path
// in qq.go it deliberately does not also require debugMode: these methods have // in qq.go it deliberately does not also require debugMode: these methods have
// always logged on this toggle alone, and preserving that is intentional. // always logged on this toggle alone, and preserving that is intentional.
func actionLogEnabled() bool { func actionLogEnabled() bool {
cfg := config.Current() 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 { type APIResponse struct {
Status string `json:"status"` Status string `json:"status"`
RetCode int `json:"retcode"` RetCode int `json:"retcode"`
@@ -34,9 +34,9 @@ type APIResponse struct {
Data json.RawMessage `json:"data"` 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 // 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 { type Client struct {
addr string addr string
port string port string
@@ -50,7 +50,7 @@ type Client struct {
stopOnce sync.Once 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 // useProxy is set, HTTP API calls and the WebSocket connection are routed
// through the system-wide network proxy. // through the system-wide network proxy.
func NewClient(addr, port, token string, useProxy bool) *Client { 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) 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 // 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) { func (c *Client) sendRequest(method, endpoint string, body []byte) ([]byte, error) {
url := c.baseURL() + endpoint 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) resp, err := c.httpClient.Do(req)
if err != nil { 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() defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body) respBody, err := io.ReadAll(resp.Body)
if err != nil { 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 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) { func (c *Client) parseResponse(respBody []byte, caller string) (*APIResponse, error) {
var napcatResp APIResponse var onebotResp APIResponse
if err := json.Unmarshal(respBody, &napcatResp); err != nil { if err := json.Unmarshal(respBody, &onebotResp); err != nil {
return nil, fmt.Errorf("failed to unmarshal napcat response (%s): %w\n%s", caller, err, string(respBody)) 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" // targetType: "group" or "private"
// targetID: QQ group ID or user ID // targetID: QQ group ID or user ID
// msg: message content // msg: message content
@@ -140,18 +140,18 @@ func (c *Client) SendMsg(targetType string, targetID int64, msg string, hasAt bo
} }
var endpoint string var endpoint string
var napcatReq map[string]interface{} var onebotReq map[string]interface{}
switch targetType { switch targetType {
case "group": case "group":
endpoint = "/send_group_msg" endpoint = "/send_group_msg"
napcatReq = map[string]interface{}{ onebotReq = map[string]interface{}{
"group_id": targetID, "group_id": targetID,
"message": message, "message": message,
} }
case "private": case "private":
endpoint = "/send_private_msg" endpoint = "/send_private_msg"
napcatReq = map[string]interface{}{ onebotReq = map[string]interface{}{
"user_id": targetID, "user_id": targetID,
"message": message, "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) 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 { if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err) return nil, fmt.Errorf("failed to marshal request: %w", err)
} }
if actionLogEnabled() { 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) 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") 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) { func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
reqBody, err := json.Marshal(map[string]interface{}{ reqBody, err := json.Marshal(map[string]interface{}{
"message_id": msgID, "message_id": msgID,
@@ -186,7 +186,7 @@ func (c *Client) RecallMsg(msgID int64) (*APIResponse, error) {
} }
if actionLogEnabled() { 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) 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") 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) { func (c *Client) GetGroupList() (*APIResponse, error) {
if actionLogEnabled() { 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) 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") 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) { func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
reqBody, err := json.Marshal(map[string]interface{}{ reqBody, err := json.Marshal(map[string]interface{}{
"group_id": groupID, "group_id": groupID,
@@ -221,7 +221,7 @@ func (c *Client) GetGroupInfo(groupID int64) (*APIResponse, error) {
} }
if actionLogEnabled() { 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) 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") 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) { func (c *Client) GetFriendsList() (*APIResponse, error) {
if actionLogEnabled() { 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) 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") 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 // message. It blocks forever, reconnecting every 5s after a disconnect, until
// Stop is called. Run it in a goroutine. // Stop is called. Run it in a goroutine.
func (c *Client) Listen(onEvent func(raw []byte)) { func (c *Client) Listen(onEvent func(raw []byte)) {
@@ -259,7 +259,7 @@ func (c *Client) Listen(onEvent func(raw []byte)) {
c.listenOnce(onEvent) c.listenOnce(onEvent)
postLog.Warning("[Napcat] WebSocket disconnected, reconnecting in 5s...") postLog.Warning("[OneBot] WebSocket disconnected, reconnecting in 5s...")
select { select {
case <-c.stopCh: case <-c.stopCh:
return 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. // connection drops or Stop is called.
func (c *Client) listenOnce(onEvent func(raw []byte)) { func (c *Client) listenOnce(onEvent func(raw []byte)) {
wsURL := fmt.Sprintf("ws://%s:%s/", c.addr, c.port) 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) dialer.Proxy = netproxy.ProxyFunc(c.useProxy)
conn, _, err := dialer.Dial(wsURL, header) conn, _, err := dialer.Dial(wsURL, header)
if err != nil { 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 return
} }
@@ -298,7 +298,7 @@ func (c *Client) listenOnce(onEvent func(raw []byte)) {
conn.Close() 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 { for {
select { select {
@@ -309,7 +309,7 @@ func (c *Client) listenOnce(onEvent func(raw []byte)) {
_, msgBytes, err := conn.ReadMessage() _, msgBytes, err := conn.ReadMessage()
if err != nil { if err != nil {
postLog.Error(fmt.Sprintf("[Napcat] WebSocket read error: %v", err)) postLog.Error(fmt.Sprintf("[OneBot] WebSocket read error: %v", err))
return return
} }
@@ -1,4 +1,4 @@
package qq_napcat package qq_onebot
import ( import (
"encoding/json" "encoding/json"
@@ -12,7 +12,7 @@ import (
"nukumizu-backend/postLog" "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. // Only "message" events are handled; notice/request/meta_event are ignored.
type oneBotEvent struct { type oneBotEvent struct {
PostType string `json:"post_type"` // Identifies "message", "notice", "request", or "meta_event" 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. 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 { type QQController struct {
cfg config.QQConfig cfg config.OneBotConfig
napcatClient *Client onebotClient *Client
} }
// NewQQController creates a new QQ (Napcat) controller. // NewQQController creates a new QQ (OneBot) controller.
func NewQQController(cfg config.QQConfig) *QQController { func NewQQController(cfg config.OneBotConfig) *QQController {
q := &QQController{cfg: cfg} q := &QQController{cfg: cfg}
if cfg.Enabled { 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 return q
} }
// Name returns the controller name. // Name returns the controller name.
func (q *QQController) Name() string { func (q *QQController) Name() string {
return "qq(napcat)" return "qq_onebot"
} }
// Start initializes the QQ controller and starts the NapCat WebSocket listener. // 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") // postLog.Info("QQ (Napcat) controller is disabled")
return nil return nil
} }
if q.napcatClient == nil { if q.onebotClient == nil {
postLog.Warning("QQ (Napcat) controller enabled but NapCat client is nil") postLog.Warning("QQ (OneBot) controller enabled but OneBot client is nil")
return 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() { go func() {
defer func() { defer func() {
if r := recover(); r != nil { 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 return nil
@@ -75,10 +75,10 @@ func (q *QQController) Start() error {
// Stop shuts down the QQ controller and its WebSocket listener. // Stop shuts down the QQ controller and its WebSocket listener.
func (q *QQController) Stop() { func (q *QQController) Stop() {
if q.napcatClient != nil { if q.onebotClient != nil {
q.napcatClient.Stop() q.onebotClient.Stop()
} }
postLog.Info("QQ (Napcat) controller stopped") postLog.Info("QQ (OneBot) controller stopped")
} }
// IsEnabled returns whether the controller is enabled. // IsEnabled returns whether the controller is enabled.
@@ -92,11 +92,11 @@ func (q *QQController) IsMarkdown() bool {
return q.cfg.Markdown return q.cfg.Markdown
} }
// handleNapcatEvent processes a raw OneBot event received from the NapCat WebSocket. // handleOneBotEvent processes a raw OneBot event received from the OneBot WebSocket.
func (q *QQController) handleNapcatEvent(raw []byte) { func (q *QQController) handleOneBotEvent(raw []byte) {
var ev oneBotEvent var ev oneBotEvent
if err := json.Unmarshal(raw, &ev); err != nil { 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 return
} }
@@ -108,16 +108,16 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
return return
} }
debugMode := cfg.System.DebugMode debugMode := cfg.System.DebugMode
showAction := debugMode && cfg.Debug.ShowNapcatAction showAction := debugMode && cfg.Debug.ShowOneBotAction
if debugMode && cfg.Debug.ShowNapcatMsg { if debugMode && cfg.Debug.ShowOneBotMsg {
postLog.Debug("Napcat WS event received: " + string(raw)) postLog.Debug("OneBot WS event received: " + string(raw))
} }
// Only handle message events; ignore notice/request/meta_event. // Only handle message events; ignore notice/request/meta_event.
if ev.PostType != "message" { if ev.PostType != "message" {
if showAction { if showAction {
postLog.Debug("Ignoring Napcat WS event: " + string(raw)) postLog.Debug("Ignoring OneBot WS event: " + string(raw))
} }
return return
} }
@@ -126,9 +126,9 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
if q.isSelfMessage(ev) && !debugMode { if q.isSelfMessage(ev) && !debugMode {
return return
} }
if q.isSelfMessage(ev) && debugMode && cfg.Debug.NapcatIgnoreSelfMsg { if q.isSelfMessage(ev) && debugMode && cfg.Debug.OneBotIgnoreSelfMsg {
if showAction { if showAction {
postLog.Debug("Ignoring Napcat WS self message: " + string(raw)) postLog.Debug("Ignoring OneBot WS self message: " + string(raw))
} }
return return
} }
@@ -149,19 +149,19 @@ func (q *QQController) handleNapcatEvent(raw []byte) {
response := q.processCommand(cmd) response := q.processCommand(cmd)
if response == "" { if response == "" {
if showAction { if showAction {
postLog.Debug("Napcat WS command discarded: " + string(raw)) postLog.Debug("OneBot WS command discarded: " + string(raw))
} }
return return
} }
// Reply in the same chat. // Reply in the same chat.
if ev.MessageType == "private" { if ev.MessageType == "private" {
if _, err := q.napcatClient.SendMsg("private", ev.UserID, response, false, 0); err != nil { if _, err := q.onebotClient.SendMsg("private", ev.UserID, response, false, 0); err != nil {
postLog.Warning("Failed to send NapCat private reply: " + err.Error()) postLog.Warning("Failed to send OneBot private reply: " + err.Error())
} }
} else { } else {
if _, err := q.napcatClient.SendMsg("group", ev.GroupID, response, false, 0); err != nil { if _, err := q.onebotClient.SendMsg("group", ev.GroupID, response, false, 0); err != nil {
postLog.Warning("Failed to send NapCat group reply: " + err.Error()) 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" { if q.cfg.ListenMethod == "at" {
atMention := fmt.Sprintf("[CQ:at,qq=%d]", q.cfg.BotQQID) atMention := fmt.Sprintf("[CQ:at,qq=%d]", q.cfg.BotQQID)
if !strings.Contains(text, atMention) { if !strings.Contains(text, atMention) {
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowNapcatAction { if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowOneBotAction {
postLog.Debug("Napcat WS message ignored (no @mention): " + text) postLog.Debug("OneBot WS message ignored (no @mention): " + text)
} }
return "" // Not mentioned, ignore. 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. // vs private, trusted groups, admin permissions, and executes it.
response, err := controller.GetManager().Trigger(parsed, q.trustedGroupIDs(), q.adminIDs(), q.cfg.ListenMethod) response, err := controller.GetManager().Trigger(parsed, q.trustedGroupIDs(), q.adminIDs(), q.cfg.ListenMethod)
if cfg != nil && cfg.System.DebugMode && cfg.Debug.ShowTriggerCmdEcho { 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 { if err != nil {
postLog.Error("Napcat command processing failed: " + err.Error()) postLog.Error("OneBot command processing failed: " + err.Error())
return "" return ""
} }
return response return response
@@ -341,8 +341,8 @@ func (q *QQController) SendAlert(alert controller.Alert) error {
} }
func (q *QQController) sendGroupMessage(groupID string, message string) { func (q *QQController) sendGroupMessage(groupID string, message string) {
if q.napcatClient == nil { if q.onebotClient == nil {
postLog.Warning("Cannot send QQ group message: NapCat client not initialized") postLog.Warning("Cannot send QQ group message: OneBot client not initialized")
return return
} }
@@ -352,14 +352,14 @@ func (q *QQController) sendGroupMessage(groupID string, message string) {
return 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)) postLog.Warning(fmt.Sprintf("Failed to send QQ group message to %s: %v", groupID, err))
} }
} }
func (q *QQController) sendPrivateMessage(userID string, message string) { func (q *QQController) sendPrivateMessage(userID string, message string) {
if q.napcatClient == nil { if q.onebotClient == nil {
postLog.Warning("Cannot send QQ private message: NapCat client not initialized") postLog.Warning("Cannot send QQ private message: OneBot client not initialized")
return return
} }
@@ -369,7 +369,7 @@ func (q *QQController) sendPrivateMessage(userID string, message string) {
return 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)) postLog.Warning(fmt.Sprintf("Failed to send QQ private message to %s: %v", userID, err))
} }
} }
+4 -4
View File
@@ -14,7 +14,7 @@ import (
"nukumizu-backend/global" "nukumizu-backend/global"
"nukumizu-backend/internal/controller" "nukumizu-backend/internal/controller"
"nukumizu-backend/internal/controller/pipes" "nukumizu-backend/internal/controller/pipes"
"nukumizu-backend/internal/controller/pipes/qq_napcat" "nukumizu-backend/internal/controller/pipes/qq_onebot"
"nukumizu-backend/internal/controller/pipes/telegram" "nukumizu-backend/internal/controller/pipes/telegram"
"nukumizu-backend/internal/komari" "nukumizu-backend/internal/komari"
"nukumizu-backend/internal/node" "nukumizu-backend/internal/node"
@@ -72,7 +72,7 @@ func main() {
} }
// Controller settings changed. Each controller reads its settings into // Controller settings changed. Each controller reads its settings into
// fields when it is built, and the NapCat and Telegram ones own // fields when it is built, and the OneBot and Telegram ones own
// connections that cannot be re-pointed, so the change is applied by // connections that cannot be re-pointed, so the change is applied by
// replacing the whole set rather than reconfiguring it in place. // replacing the whole set rather than reconfiguring it in place.
postLog.Info("Controller settings changed; rebuilding every channel") postLog.Info("Controller settings changed; rebuilding every channel")
@@ -131,7 +131,7 @@ func main() {
initControllers() initControllers()
// Send the bot initialization message to all enabled bot controllers // Send the bot initialization message to all enabled bot controllers
// (QQ_NapCat, Telegram), then the server list right after it once the // (QQ_OneBot, Telegram), then the server list right after it once the
// initial status refresh has completed so the list reflects the real // initial status refresh has completed so the list reflects the real
// online/offline state. // online/offline state.
if mgr := controller.GetManager(); mgr != nil { if mgr := controller.GetManager(); mgr != nil {
@@ -226,7 +226,7 @@ func startWebhookServer(cfg *config.Config) {
// own connections that cannot be re-pointed. // own connections that cannot be re-pointed.
func buildControllers(cfg *config.Config) []controller.Controller { func buildControllers(cfg *config.Config) []controller.Controller {
return []controller.Controller{ return []controller.Controller{
qq_napcat.NewQQController(cfg.ControllerMethod.QQ), qq_onebot.NewQQController(cfg.ControllerMethod.QQ_OneBot),
telegram.NewTelegramController(cfg.ControllerMethod.Telegram), telegram.NewTelegramController(cfg.ControllerMethod.Telegram),
pipes.NewEmailController(cfg.ControllerMethod.Email), pipes.NewEmailController(cfg.ControllerMethod.Email),
pipes.NewNtfyController(cfg.ControllerMethod.Ntfy), pipes.NewNtfyController(cfg.ControllerMethod.Ntfy),