diff --git a/api/api_bind.go b/api/api_bind.go index 2bbeeed6..09a5e7d0 100644 --- a/api/api_bind.go +++ b/api/api_bind.go @@ -166,7 +166,7 @@ func forceStop(c echo.Context) error { for _, i := range diceManager.Dice { if i.IsAlreadyLoadConfig { - i.BanList.SaveChanged(i) + i.Config.BanList.SaveChanged(i) i.AttrsManager.CheckForSave() i.Save(true) for _, j := range i.ExtList { diff --git a/api/ban.go b/api/ban.go index fc7b1855..62ac204a 100644 --- a/api/ban.go +++ b/api/ban.go @@ -20,7 +20,7 @@ func banConfigGet(c echo.Context) error { return c.JSON(http.StatusForbidden, nil) } - return c.JSON(http.StatusOK, myDice.BanList) + return c.JSON(http.StatusOK, myDice.Config.BanList) } func banConfigSet(c echo.Context) error { @@ -42,23 +42,23 @@ func banConfigSet(c echo.Context) error { v.ThresholdBan = 200 } - myDice.BanList.BanBehaviorRefuseReply = v.BanBehaviorRefuseReply - myDice.BanList.BanBehaviorRefuseInvite = v.BanBehaviorRefuseInvite - myDice.BanList.BanBehaviorQuitLastPlace = v.BanBehaviorQuitLastPlace - myDice.BanList.BanBehaviorQuitPlaceImmediately = v.BanBehaviorQuitPlaceImmediately - myDice.BanList.BanBehaviorQuitIfAdmin = v.BanBehaviorQuitIfAdmin - myDice.BanList.ScoreReducePerMinute = v.ScoreReducePerMinute - myDice.BanList.ThresholdWarn = v.ThresholdWarn - myDice.BanList.ThresholdBan = v.ThresholdBan - myDice.BanList.ScoreGroupMuted = v.ScoreGroupMuted - myDice.BanList.ScoreGroupKicked = v.ScoreGroupKicked - myDice.BanList.ScoreTooManyCommand = v.ScoreTooManyCommand - - myDice.BanList.JointScorePercentOfGroup = v.JointScorePercentOfGroup - myDice.BanList.JointScorePercentOfInviter = v.JointScorePercentOfInviter + myDice.Config.BanList.BanBehaviorRefuseReply = v.BanBehaviorRefuseReply + myDice.Config.BanList.BanBehaviorRefuseInvite = v.BanBehaviorRefuseInvite + myDice.Config.BanList.BanBehaviorQuitLastPlace = v.BanBehaviorQuitLastPlace + myDice.Config.BanList.BanBehaviorQuitPlaceImmediately = v.BanBehaviorQuitPlaceImmediately + myDice.Config.BanList.BanBehaviorQuitIfAdmin = v.BanBehaviorQuitIfAdmin + myDice.Config.BanList.ScoreReducePerMinute = v.ScoreReducePerMinute + myDice.Config.BanList.ThresholdWarn = v.ThresholdWarn + myDice.Config.BanList.ThresholdBan = v.ThresholdBan + myDice.Config.BanList.ScoreGroupMuted = v.ScoreGroupMuted + myDice.Config.BanList.ScoreGroupKicked = v.ScoreGroupKicked + myDice.Config.BanList.ScoreTooManyCommand = v.ScoreTooManyCommand + + myDice.Config.BanList.JointScorePercentOfGroup = v.JointScorePercentOfGroup + myDice.Config.BanList.JointScorePercentOfInviter = v.JointScorePercentOfInviter myDice.MarkModified() - return c.JSON(http.StatusOK, myDice.BanList) + return c.JSON(http.StatusOK, myDice.Config.BanList) } func banMapList(c echo.Context) error { @@ -75,7 +75,7 @@ func banMapDeleteOne(c echo.Context) error { if err != nil { return c.String(430, err.Error()) } - myDice.BanList.DeleteByID(myDice, v.ID) + myDice.Config.BanList.DeleteByID(myDice, v.ID) return c.JSON(http.StatusOK, nil) } @@ -92,7 +92,7 @@ func banMapAddOne(c echo.Context) error { return c.String(430, err.Error()) } if v.Rank == dice.BanRankBanned { - score := myDice.BanList.ThresholdBan + score := myDice.Config.BanList.ThresholdBan reason := "骰主后台设置" if len(v.Reasons) > 0 { reason = v.Reasons[0] @@ -102,7 +102,7 @@ func banMapAddOne(c echo.Context) error { platform := strings.Replace(prefix, "-Group", "", 1) for _, i := range myDice.ImSession.EndPoints { if i.Platform == platform && i.Enable { - v2 := myDice.BanList.AddScoreBase(v.ID, score, "海豹后台", reason, &dice.MsgContext{Dice: myDice, EndPoint: i}) + v2 := myDice.Config.BanList.AddScoreBase(v.ID, score, "海豹后台", reason, &dice.MsgContext{Dice: myDice, EndPoint: i}) if v2 != nil { if v.Name != "" { v2.Name = v.Name @@ -112,7 +112,7 @@ func banMapAddOne(c echo.Context) error { } } if v.Rank == dice.BanRankTrusted { - myDice.BanList.SetTrustByID(v.ID, "海豹后台", "骰主后台设置") + myDice.Config.BanList.SetTrustByID(v.ID, "海豹后台", "骰主后台设置") } return c.JSON(http.StatusOK, nil) @@ -132,7 +132,7 @@ func banMapAddOne(c echo.Context) error { // return c.String(430, err.Error()) // } // -// myDice.BanList.LoadMapFromJSON(v.data) +// myDice.Config.BanList.LoadMapFromJSON(v.data) // return c.JSON(http.StatusOK, nil) //} @@ -199,9 +199,9 @@ func banImport(c echo.Context) error { } } item.Reasons = newReasons - myDice.BanList.Map.Store(item.ID, item) + myDice.Config.BanList.Map.Store(item.ID, item) } - myDice.BanList.SaveChanged(myDice) + myDice.Config.BanList.SaveChanged(myDice) return Success(&c, Response{}) } diff --git a/api/censor.go b/api/censor.go index c3a10e67..c5211d1c 100644 --- a/api/censor.go +++ b/api/censor.go @@ -29,7 +29,7 @@ func check(c echo.Context) (bool, error) { if dm.JustForTest { return false, Error(&c, "展示模式不支持该操作", Response{"testMode": true}) } - if !myDice.EnableCensor { + if !myDice.Config.EnableCensor { return false, Error(&c, "未启用拦截引擎", Response{}) } if myDice.CensorManager.IsLoading { @@ -47,10 +47,10 @@ func censorRestart(c echo.Context) error { } myDice.NewCensorManager() - myDice.EnableCensor = true + myDice.Config.EnableCensor = true return Success(&c, Response{ - "enable": myDice.EnableCensor, + "enable": myDice.Config.EnableCensor, "isLoading": myDice.CensorManager.IsLoading, }) } @@ -61,7 +61,7 @@ func censorStop(c echo.Context) error { return err } - myDice.EnableCensor = false + myDice.Config.EnableCensor = false _ = myDice.CensorManager.DB.Close() myDice.CensorManager = nil @@ -74,23 +74,23 @@ func censorGetStatus(c echo.Context) error { isLoading = myDice.CensorManager.IsLoading } return Success(&c, Response{ - "enable": myDice.EnableCensor, + "enable": myDice.Config.EnableCensor, "isLoading": isLoading, }) } func censorGetConfig(c echo.Context) error { levelConfig := map[string]LevelConfig{ - "notice": getLevelConfig(censor.Notice, myDice.CensorThresholds, myDice.CensorHandlers, myDice.CensorScores), - "caution": getLevelConfig(censor.Caution, myDice.CensorThresholds, myDice.CensorHandlers, myDice.CensorScores), - "warning": getLevelConfig(censor.Warning, myDice.CensorThresholds, myDice.CensorHandlers, myDice.CensorScores), - "danger": getLevelConfig(censor.Danger, myDice.CensorThresholds, myDice.CensorHandlers, myDice.CensorScores), + "notice": getLevelConfig(censor.Notice, myDice.Config.CensorThresholds, myDice.Config.CensorHandlers, myDice.Config.CensorScores), + "caution": getLevelConfig(censor.Caution, myDice.Config.CensorThresholds, myDice.Config.CensorHandlers, myDice.Config.CensorScores), + "warning": getLevelConfig(censor.Warning, myDice.Config.CensorThresholds, myDice.Config.CensorHandlers, myDice.Config.CensorScores), + "danger": getLevelConfig(censor.Danger, myDice.Config.CensorThresholds, myDice.Config.CensorHandlers, myDice.Config.CensorScores), } return Success(&c, Response{ - "mode": myDice.CensorMode, - "caseSensitive": myDice.CensorCaseSensitive, - "matchPinyin": myDice.CensorMatchPinyin, - "filterRegex": myDice.CensorFilterRegexStr, + "mode": myDice.Config.CensorMode, + "caseSensitive": myDice.Config.CensorCaseSensitive, + "matchPinyin": myDice.Config.CensorMatchPinyin, + "filterRegex": myDice.Config.CensorFilterRegexStr, "levelConfig": levelConfig, }) } @@ -160,25 +160,25 @@ func censorSetConfig(c echo.Context) error { if err != nil { return Error(&c, "过滤字符正则不是合法的正则表达式", Response{}) } - myDice.CensorFilterRegexStr = filterRegex + myDice.Config.CensorFilterRegexStr = filterRegex } } if val, ok := jsonMap["mode"]; ok { mode, ok := val.(float64) if ok { - myDice.CensorMode = dice.CensorMode(mode) + myDice.Config.CensorMode = dice.CensorMode(mode) } } if val, ok := jsonMap["caseSensitive"]; ok { caseSensitive, ok := val.(bool) if ok { - myDice.CensorCaseSensitive = caseSensitive + myDice.Config.CensorCaseSensitive = caseSensitive } } if val, ok := jsonMap["matchPinyin"]; ok { matchPinyin, ok := val.(bool) if ok { - myDice.CensorMatchPinyin = matchPinyin + myDice.Config.CensorMatchPinyin = matchPinyin } } if val, ok := jsonMap["levelConfig"]; ok { //nolint:nestif @@ -212,7 +212,7 @@ func censorSetConfig(c echo.Context) error { if ok { if val, ok = confMap["threshold"]; ok { threshold := val.(float64) - myDice.CensorThresholds[level] = int(threshold) + myDice.Config.CensorThresholds[level] = int(threshold) } if val, ok = confMap["handlers"]; ok { handlers := stringConvert(val) @@ -220,7 +220,7 @@ func censorSetConfig(c echo.Context) error { } if val, ok = confMap["score"]; ok { score := val.(float64) - myDice.CensorScores[level] = int(score) + myDice.Config.CensorScores[level] = int(score) } } } @@ -259,7 +259,7 @@ func setLevelHandlers(level censor.Level, handlers []string) { handlerVal = newHandlerVal(handlerVal, dice.BanInviter, newHandlers) handlerVal = newHandlerVal(handlerVal, dice.AddScore, newHandlers) - myDice.CensorHandlers[level] = handlerVal + myDice.Config.CensorHandlers[level] = handlerVal } func newHandlerVal(val uint8, handle dice.CensorHandler, newHandlers map[dice.CensorHandler]bool) uint8 { diff --git a/api/deck.go b/api/deck.go index 9264b566..19a0af25 100644 --- a/api/deck.go +++ b/api/deck.go @@ -104,7 +104,7 @@ func deckEnable(c echo.Context) error { } } - return c.JSON(http.StatusOK, myDice.BanList) + return c.JSON(http.StatusOK, myDice.Config.BanList) } func deckDelete(c echo.Context) error { diff --git a/api/dice_config.go b/api/dice_config.go index 03928129..6004c39b 100644 --- a/api/dice_config.go +++ b/api/dice_config.go @@ -16,61 +16,17 @@ import ( ) type DiceConfigInfo struct { - // 注:form其实不需要 - CommandPrefix []string `json:"commandPrefix" form:"commandPrefix"` // 指令前缀 - DiceMasters []string `json:"diceMasters" form:"diceMasters"` // 骰主设置,需要格式: 平台:帐号 - NoticeIds []string `json:"noticeIds"` // 通知设置,需要格式: 平台:帐号 - OnlyLogCommandInGroup bool `json:"onlyLogCommandInGroup" form:"onlyLogCommandInGroup"` // 日志中仅记录命令 - OnlyLogCommandInPrivate bool `json:"onlyLogCommandInPrivate" form:"onlyLogCommandInPrivate"` // 日志中仅记录命令 - WorkInQQChannel bool `json:"workInQQChannel"` // 在QQ频道中开启 - MessageDelayRangeStart float64 `json:"messageDelayRangeStart" form:"messageDelayRangeStart"` // 指令延迟区间 - MessageDelayRangeEnd float64 `json:"messageDelayRangeEnd" form:"messageDelayRangeEnd"` - UIPassword string `json:"uiPassword" form:"uiPassword"` - HelpDocEngineType int `json:"helpDocEngineType"` - MasterUnlockCode string `json:"masterUnlockCode" form:"masterUnlockCode"` - ServeAddress string `json:"serveAddress" form:"serveAddress"` - MasterUnlockCodeTime int64 `json:"masterUnlockCodeTime"` - LogPageItemLimit int64 `json:"logPageItemLimit"` - FriendAddComment string `json:"friendAddComment"` - QQChannelAutoOn bool `json:"QQChannelAutoOn"` - QQChannelLogMessage bool `json:"QQChannelLogMessage"` - RefuseGroupInvite bool `json:"refuseGroupInvite"` // 拒绝群组邀请 - - QuitInactiveThreshold float64 `json:"quitInactiveThreshold"` // 退出不活跃群组阈值(天) - QuitInactiveBatchSize int64 `json:"quitInactiveBatchSize"` // 退出不活跃群组的批量大小 - QuitInactiveBatchWait int64 `json:"quitInactiveBatchWait"` // 退出不活跃群组的批量等待时间(分) - - DefaultCocRuleIndex string `json:"defaultCocRuleIndex"` // 默认coc index - MaxExecuteTime string `json:"maxExecuteTime"` // 最大骰点次数 - MaxCocCardGen string `json:"maxCocCardGen"` // 最大coc制卡数 - - ExtDefaultSettings []*dice.ExtDefaultSettingItem `yaml:"extDefaultSettings" json:"extDefaultSettings"` // 新群扩展按此顺序加载 - BotExtFreeSwitch bool `json:"botExtFreeSwitch"` - TrustOnlyMode bool `json:"trustOnlyMode"` - AliveNoticeEnable bool `json:"aliveNoticeEnable"` - AliveNoticeValue string `json:"aliveNoticeValue"` - ReplyDebugMode bool `json:"replyDebugMode"` - - CustomReplyConfigEnable bool `json:"customReplyConfigEnable"` // 是否开启reply - - LogSizeNoticeEnable bool `json:"logSizeNoticeEnable"` // 开启日志数量提示 - LogSizeNoticeCount int `json:"logSizeNoticeCount"` // 日志数量提示阈值,默认500 - - TextCmdTrustOnly bool `json:"textCmdTrustOnly"` // text命令只允许信任用户和master - IgnoreUnaddressedBotCmd bool `json:"ignoreUnaddressedBotCmd"` // 不响应群聊裸bot指令 - QQEnablePoke bool `json:"QQEnablePoke"` // QQ允许戳一戳 - PlayerNameWrapEnable bool `json:"playerNameWrapEnable"` // 玩家名外框 - - MailEnable bool `json:"mailEnable"` - MailFrom string `json:"mailFrom"` // 邮箱来源 - MailPassword string `json:"mailPassword"` // 邮箱密钥/密码 - MailSMTP string `json:"mailSmtp"` // 邮箱 smtp 地址 - - RateLimitEnabled bool `json:"rateLimitEnabled"` // 是否开启限速 - PersonalReplenishRate string `json:"personalReplenishRate"` // 个人自定义速率 - PersonalReplenishBurst int64 `json:"personalBurst"` // 个人自定义上限 - GroupReplenishRate string `json:"groupReplenishRate"` // 群组自定义速率 - GroupReplenishBurst int64 `json:"groupBurst"` // 群组自定义上限 + dice.Config + + CommandPrefix []string `json:"commandPrefix" form:"commandPrefix"` + DiceMasters []string `json:"diceMasters" form:"diceMasters"` + UIPassword string `json:"uiPassword" form:"uiPassword"` + LogPageItemLimit int64 `json:"logPageItemLimit"` + DefaultCocRuleIndex string `json:"defaultCocRuleIndex"` // 默认coc index + MaxExecuteTime string `json:"maxExecuteTime"` // 最大骰点次数 + MaxCocCardGen string `json:"maxCocCardGen"` // 最大coc制卡数 + ServerAddress string `json:"serveAddress" form:"serveAddress"` + HelpDocEngineType int `json:"helpDocEngineType"` } func DiceConfig(c echo.Context) error { @@ -83,93 +39,53 @@ func DiceConfig(c echo.Context) error { password = "------" } - limit := myDice.UILogLimit + limit := myDice.Config.UILogLimit if limit == 0 { limit = 100 } myDice.UnlockCodeUpdate(false) - cocRule := strconv.FormatInt(myDice.DefaultCocRuleIndex, 10) - if myDice.DefaultCocRuleIndex == 11 { + cocRule := strconv.FormatInt(myDice.Config.DefaultCocRuleIndex, 10) + if myDice.Config.DefaultCocRuleIndex == 11 { cocRule = "dg" } - maxExec := strconv.FormatInt(myDice.MaxExecuteTime, 10) + maxExec := strconv.FormatInt(myDice.Config.MaxExecuteTime, 10) - maxCard := strconv.FormatInt(myDice.MaxCocCardGen, 10) + maxCard := strconv.FormatInt(myDice.Config.MaxCocCardGen, 10) emailPasswordMasked := "" - if myDice.MailPassword != "" { + if myDice.Config.MailPassword != "" { emailPasswordMasked = "******" } // 过滤掉未加载的: 包括关闭的和已经删除的 // TODO(Xiangze Li): 如果前端能支持区分显示未加载插件的配置(.loaded字段), 这里就的过滤就可以去掉 - extDefaultSettings := make([]*dice.ExtDefaultSettingItem, 0, len(myDice.ExtDefaultSettings)) - for _, i := range myDice.ExtDefaultSettings { + extDefaultSettings := make([]*dice.ExtDefaultSettingItem, 0, len(myDice.Config.ExtDefaultSettings)) + for _, i := range myDice.Config.ExtDefaultSettings { if i.Loaded { extDefaultSettings = append(extDefaultSettings, i) } } info := DiceConfigInfo{ - CommandPrefix: myDice.CommandPrefix, - DiceMasters: myDice.DiceMasters, - NoticeIds: myDice.NoticeIDs, - OnlyLogCommandInPrivate: myDice.OnlyLogCommandInPrivate, - OnlyLogCommandInGroup: myDice.OnlyLogCommandInGroup, - MessageDelayRangeStart: myDice.MessageDelayRangeStart, - MessageDelayRangeEnd: myDice.MessageDelayRangeEnd, - UIPassword: password, - MasterUnlockCode: myDice.MasterUnlockCode, - MasterUnlockCodeTime: myDice.MasterUnlockCodeTime, - WorkInQQChannel: myDice.WorkInQQChannel, - LogPageItemLimit: limit, - FriendAddComment: myDice.FriendAddComment, - QQChannelAutoOn: myDice.QQChannelAutoOn, - QQChannelLogMessage: myDice.QQChannelLogMessage, - RefuseGroupInvite: myDice.RefuseGroupInvite, - RateLimitEnabled: myDice.RateLimitEnabled, - - ExtDefaultSettings: extDefaultSettings, - DefaultCocRuleIndex: cocRule, + Config: myDice.Config, - QuitInactiveThreshold: myDice.QuitInactiveThreshold.Hours() / 24, - QuitInactiveBatchSize: myDice.QuitInactiveBatchSize, - QuitInactiveBatchWait: myDice.QuitInactiveBatchWait, - - BotExtFreeSwitch: myDice.BotExtFreeSwitch, - TrustOnlyMode: myDice.TrustOnlyMode, - AliveNoticeEnable: myDice.AliveNoticeEnable, - AliveNoticeValue: myDice.AliveNoticeValue, - ReplyDebugMode: myDice.ReplyDebugMode, - - ServeAddress: myDice.Parent.ServeAddress, - HelpDocEngineType: myDice.Parent.HelpDocEngineType, - - // 1.0 正式 - LogSizeNoticeEnable: myDice.LogSizeNoticeEnable, - LogSizeNoticeCount: myDice.LogSizeNoticeCount, - CustomReplyConfigEnable: myDice.CustomReplyConfigEnable, - - // 1.2 - TextCmdTrustOnly: myDice.TextCmdTrustOnly, - QQEnablePoke: myDice.QQEnablePoke, - PlayerNameWrapEnable: myDice.PlayerNameWrapEnable, - - // 1.3? - MailEnable: myDice.MailEnable, - MailFrom: myDice.MailFrom, - MailPassword: emailPasswordMasked, - MailSMTP: myDice.MailSMTP, - MaxExecuteTime: maxExec, - MaxCocCardGen: maxCard, - PersonalReplenishRate: myDice.PersonalReplenishRateStr, - PersonalReplenishBurst: myDice.PersonalBurst, - GroupReplenishRate: myDice.GroupReplenishRateStr, - GroupReplenishBurst: myDice.GroupBurst, - IgnoreUnaddressedBotCmd: myDice.IgnoreUnaddressedBotCmd, + CommandPrefix: myDice.CommandPrefix, + DiceMasters: myDice.DiceMasters, + UIPassword: password, + LogPageItemLimit: limit, + DefaultCocRuleIndex: cocRule, + ServerAddress: myDice.Parent.ServeAddress, + HelpDocEngineType: myDice.Parent.HelpDocEngineType, + MaxExecuteTime: maxExec, + MaxCocCardGen: maxCard, } + info.ExtDefaultSettings = extDefaultSettings + info.DefaultCocRuleIndex = cocRule + info.MailPassword = emailPasswordMasked + info.Config.QuitInactiveThresholdDays = info.QuitInactiveThreshold.Hours() / 24 + return c.JSON(http.StatusOK, info) } @@ -218,7 +134,7 @@ func DiceConfigSet(c echo.Context) error { } if val, ok := jsonMap["noticeIds"]; ok { - myDice.NoticeIDs = stringConvert(val) + myDice.Config.NoticeIDs = stringConvert(val) } if val, ok := jsonMap["defaultCocRuleIndex"]; ok { //nolint:nestif @@ -226,12 +142,12 @@ func DiceConfigSet(c echo.Context) error { if ok { valStr = strings.TrimSpace(valStr) if strings.EqualFold(valStr, "dg") { - myDice.DefaultCocRuleIndex = 11 + myDice.Config.DefaultCocRuleIndex = 11 } else { - myDice.DefaultCocRuleIndex, err = strconv.ParseInt(valStr, 10, 64) + myDice.Config.DefaultCocRuleIndex, err = strconv.ParseInt(valStr, 10, 64) if err == nil { - if myDice.DefaultCocRuleIndex > 5 || myDice.DefaultCocRuleIndex < 0 { - myDice.DefaultCocRuleIndex = 0 + if myDice.Config.DefaultCocRuleIndex > 5 || myDice.Config.DefaultCocRuleIndex < 0 { + myDice.Config.DefaultCocRuleIndex = dice.DefaultConfig.DefaultCocRuleIndex } } } @@ -245,7 +161,7 @@ func DiceConfigSet(c echo.Context) error { var valInt int64 valInt, err = strconv.ParseInt(valStr, 10, 64) if err == nil && valInt > 0 { - myDice.MaxExecuteTime = valInt + myDice.Config.MaxExecuteTime = valInt } /* else { Should return some error? } */ @@ -259,7 +175,7 @@ func DiceConfigSet(c echo.Context) error { var valInt int64 valInt, err = strconv.ParseInt(valStr, 10, 64) if err == nil && valInt > 0 { - myDice.MaxCocCardGen = valInt + myDice.Config.MaxCocCardGen = valInt } /* else { Should return some error? } */ @@ -271,7 +187,7 @@ func DiceConfigSet(c echo.Context) error { if ok { customBurst := int64(valStr) if customBurst >= 1 { - myDice.PersonalBurst = customBurst + myDice.Config.PersonalBurst = customBurst } } } @@ -282,8 +198,8 @@ func DiceConfigSet(c echo.Context) error { valStr = strings.TrimSpace(valStr) newRate, errParse := utils.ParseRate(valStr) if errParse == nil && newRate != rate.Limit(0) { - myDice.PersonalReplenishRate = newRate - myDice.PersonalReplenishRateStr = valStr + myDice.Config.PersonalReplenishRate = newRate + myDice.Config.PersonalReplenishRateStr = valStr } } } @@ -293,7 +209,7 @@ func DiceConfigSet(c echo.Context) error { if ok { customBurst := int64(valStr) if customBurst >= 1 { - myDice.GroupBurst = customBurst + myDice.Config.GroupBurst = customBurst } } } @@ -304,54 +220,54 @@ func DiceConfigSet(c echo.Context) error { valStr = strings.TrimSpace(valStr) newRate, errParse := utils.ParseRate(valStr) if errParse == nil && newRate != rate.Limit(0) { - myDice.GroupReplenishRate = newRate - myDice.GroupReplenishRateStr = valStr + myDice.Config.GroupReplenishRate = newRate + myDice.Config.GroupReplenishRateStr = valStr } } } if val, ok := jsonMap["onlyLogCommandInGroup"]; ok { - myDice.OnlyLogCommandInGroup = val.(bool) + myDice.Config.OnlyLogCommandInGroup = val.(bool) } if val, ok := jsonMap["onlyLogCommandInPrivate"]; ok { - myDice.OnlyLogCommandInPrivate = val.(bool) + myDice.Config.OnlyLogCommandInPrivate = val.(bool) } if val, ok := jsonMap["refuseGroupInvite"]; ok { - myDice.RefuseGroupInvite = val.(bool) + myDice.Config.RefuseGroupInvite = val.(bool) } if val, ok := jsonMap["workInQQChannel"]; ok { - myDice.WorkInQQChannel = val.(bool) + myDice.Config.WorkInQQChannel = val.(bool) } if val, ok := jsonMap["QQChannelLogMessage"]; ok { - myDice.QQChannelLogMessage = val.(bool) + myDice.Config.QQChannelLogMessage = val.(bool) } if val, ok := jsonMap["QQChannelAutoOn"]; ok { - myDice.QQChannelAutoOn = val.(bool) + myDice.Config.QQChannelAutoOn = val.(bool) } if val, ok := jsonMap["botExtFreeSwitch"]; ok { - myDice.BotExtFreeSwitch = val.(bool) + myDice.Config.BotExtFreeSwitch = val.(bool) } if val, ok := jsonMap["rateLimitEnabled"]; ok { - myDice.RateLimitEnabled = val.(bool) + myDice.Config.RateLimitEnabled = val.(bool) } if val, ok := jsonMap["trustOnlyMode"]; ok { - myDice.TrustOnlyMode = val.(bool) + myDice.Config.TrustOnlyMode = val.(bool) } aliveNoticeMod := false if val, ok := jsonMap["aliveNoticeEnable"]; ok { - myDice.AliveNoticeEnable = val.(bool) + myDice.Config.AliveNoticeEnable = val.(bool) aliveNoticeMod = true } if val, ok := jsonMap["aliveNoticeValue"]; ok { - myDice.AliveNoticeValue = val.(string) + myDice.Config.AliveNoticeValue = val.(string) aliveNoticeMod = true } if aliveNoticeMod { @@ -373,10 +289,10 @@ func DiceConfigSet(c echo.Context) error { if f < 0 { f = 0 } - if myDice.MessageDelayRangeEnd < f { - myDice.MessageDelayRangeEnd = f + if myDice.Config.MessageDelayRangeEnd < f { + myDice.Config.MessageDelayRangeEnd = f } - myDice.MessageDelayRangeStart = f + myDice.Config.MessageDelayRangeStart = f } } @@ -387,14 +303,14 @@ func DiceConfigSet(c echo.Context) error { f = 0 } - if f >= myDice.MessageDelayRangeStart { - myDice.MessageDelayRangeEnd = f + if f >= myDice.Config.MessageDelayRangeStart { + myDice.Config.MessageDelayRangeEnd = f } } } if val, ok := jsonMap["friendAddComment"]; ok { - myDice.FriendAddComment = strings.TrimSpace(val.(string)) + myDice.Config.FriendAddComment = strings.TrimSpace(val.(string)) } if val, ok := jsonMap["uiPassword"]; ok { @@ -409,7 +325,7 @@ func DiceConfigSet(c echo.Context) error { var items []*dice.ExtDefaultSettingItem err := json.Unmarshal(data, &items) if err == nil { - myDice.ExtDefaultSettings = items + myDice.Config.ExtDefaultSettings = items myDice.ApplyExtDefaultSettings() } } @@ -434,57 +350,57 @@ func DiceConfigSet(c echo.Context) error { // } if val, ok := jsonMap["logSizeNoticeEnable"]; ok { - myDice.LogSizeNoticeEnable = val.(bool) + myDice.Config.LogSizeNoticeEnable = val.(bool) } if val, ok := jsonMap["logSizeNoticeCount"]; ok { count, ok := val.(float64) if ok { - myDice.LogSizeNoticeCount = int(count) + myDice.Config.LogSizeNoticeCount = int(count) } if !ok { if v, ok := val.(string); ok { v2, _ := strconv.ParseInt(v, 10, 64) - myDice.LogSizeNoticeCount = int(v2) + myDice.Config.LogSizeNoticeCount = int(v2) } } - if myDice.LogSizeNoticeCount == 0 { + if myDice.Config.LogSizeNoticeCount == 0 { // 不能为零 - myDice.LogSizeNoticeCount = 500 + myDice.Config.LogSizeNoticeCount = dice.DefaultConfig.LogSizeNoticeCount } } if val, ok := jsonMap["customReplyConfigEnable"]; ok { - myDice.CustomReplyConfigEnable = val.(bool) + myDice.Config.CustomReplyConfigEnable = val.(bool) } if val, ok := jsonMap["textCmdTrustOnly"]; ok { - myDice.TextCmdTrustOnly = val.(bool) + myDice.Config.TextCmdTrustOnly = val.(bool) } if val, ok := jsonMap["ignoreUnaddressedBotCmd"]; ok { - myDice.IgnoreUnaddressedBotCmd = val.(bool) + myDice.Config.IgnoreUnaddressedBotCmd = val.(bool) } if val, ok := jsonMap["QQEnablePoke"]; ok { - myDice.QQEnablePoke = val.(bool) + myDice.Config.QQEnablePoke = val.(bool) } if val, ok := jsonMap["playerNameWrapEnable"]; ok { - myDice.PlayerNameWrapEnable = val.(bool) + myDice.Config.PlayerNameWrapEnable = val.(bool) } if val, ok := jsonMap["mailEnable"]; ok { - myDice.MailEnable = val.(bool) + myDice.Config.MailEnable = val.(bool) } if val, ok := jsonMap["mailFrom"]; ok { - myDice.MailFrom = val.(string) + myDice.Config.MailFrom = val.(string) } if val, ok := jsonMap["mailPassword"]; ok { - myDice.MailPassword = val.(string) + myDice.Config.MailPassword = val.(string) } if val, ok := jsonMap["mailSmtp"]; ok { - myDice.MailSMTP = val.(string) + myDice.Config.MailSMTP = val.(string) } if val, ok := jsonMap["quitInactiveThreshold"]; ok { @@ -492,14 +408,14 @@ func DiceConfigSet(c echo.Context) error { switch v := val.(type) { case string: if vv, err := strconv.ParseFloat(v, 64); err == nil { - myDice.QuitInactiveThreshold = time.Duration(float64(24*time.Hour) * vv) + myDice.Config.QuitInactiveThreshold = time.Duration(float64(24*time.Hour) * vv) set = true } case float64: - myDice.QuitInactiveThreshold = time.Duration(float64(24*time.Hour) * v) + myDice.Config.QuitInactiveThreshold = time.Duration(float64(24*time.Hour) * v) set = true case int64: - myDice.QuitInactiveThreshold = 24 * time.Hour * time.Duration(v) + myDice.Config.QuitInactiveThreshold = 24 * time.Hour * time.Duration(v) set = true default: // ignore @@ -512,7 +428,7 @@ func DiceConfigSet(c echo.Context) error { if val, ok := jsonMap["quitInactiveBatchSize"]; ok { if v, ok := val.(float64); ok { if vv := int64(v); vv > 0 { - myDice.QuitInactiveBatchSize = vv + myDice.Config.QuitInactiveBatchSize = vv } } } @@ -520,7 +436,7 @@ func DiceConfigSet(c echo.Context) error { if val, ok := jsonMap["quitInactiveBatchWait"]; ok { if v, ok := val.(float64); ok { if vv := int64(v); vv > 0 { - myDice.QuitInactiveBatchWait = vv + myDice.Config.QuitInactiveBatchWait = vv } } } @@ -571,12 +487,12 @@ func vmVersionForExtSetBase(c echo.Context, callback func(val string)) error { func vmVersionForReplySet(c echo.Context) error { return vmVersionForExtSetBase(c, func(val string) { - myDice.VMVersionForReply = val + myDice.Config.VMVersionForReply = val }) } func vmVersionForDeckSet(c echo.Context) error { return vmVersionForExtSetBase(c, func(val string) { - myDice.VMVersionForDeck = val + myDice.Config.VMVersionForDeck = val }) } diff --git a/api/js.go b/api/js.go index 231e8269..d7773d0b 100644 --- a/api/js.go +++ b/api/js.go @@ -26,7 +26,7 @@ func jsExec(c echo.Context) error { "testMode": true, }) } - if !myDice.JsEnable { + if !myDice.Config.JsEnable { resp := c.JSON(200, map[string]interface{}{ "result": false, "err": "js扩展支持已关闭", @@ -86,7 +86,7 @@ func jsGetRecord(c echo.Context) error { if !doAuth(c) { return c.JSON(http.StatusForbidden, nil) } - if !myDice.JsEnable { + if !myDice.Config.JsEnable { resp := c.JSON(200, map[string]interface{}{ "outputs": []string{}, }) @@ -109,7 +109,7 @@ func jsDelete(c echo.Context) error { "testMode": true, }) } - if !myDice.JsEnable { + if !myDice.Config.JsEnable { resp := c.JSON(200, map[string]interface{}{ "result": false, "err": "js扩展支持已关闭", @@ -200,7 +200,7 @@ func jsList(c echo.Context) error { if !doAuth(c) { return c.JSON(http.StatusForbidden, nil) } - if !myDice.JsEnable { + if !myDice.Config.JsEnable { resp := c.JSON(200, []*dice.JsScriptInfo{}) return resp } @@ -231,7 +231,7 @@ func jsShutdown(c echo.Context) error { }) } - if myDice.JsEnable { + if myDice.Config.JsEnable { myDice.JsShutdown() } @@ -243,7 +243,7 @@ func jsShutdown(c echo.Context) error { func jsStatus(c echo.Context) error { return c.JSON(http.StatusOK, map[string]interface{}{ "result": true, - "status": myDice.JsEnable, + "status": myDice.Config.JsEnable, }) } @@ -333,7 +333,7 @@ func jsUpdate(c echo.Context) error { if dm.JustForTest { return Error(&c, "展示模式不支持该操作", Response{"testMode": true}) } - if !myDice.JsEnable { + if !myDice.Config.JsEnable { return Error(&c, "js扩展支持已关闭", Response{}) } diff --git a/api/news.go b/api/news.go index 2a405472..7ee7c9cc 100644 --- a/api/news.go +++ b/api/news.go @@ -29,7 +29,7 @@ func getNews(c echo.Context) error { } return c.JSON(http.StatusOK, map[string]interface{}{ "result": true, - "checked": mark == myDice.NewsMark, + "checked": mark == myDice.Config.NewsMark, "news": news, "newsMark": mark, }) @@ -55,7 +55,7 @@ func checkNews(c echo.Context) error { err := c.Bind(&v) if err == nil { - myDice.NewsMark = v.NewsMark + myDice.Config.NewsMark = v.NewsMark myDice.MarkModified() return c.JSON(http.StatusOK, map[string]interface{}{ "result": true, diff --git a/api/reply.go b/api/reply.go index fdc4bb1d..3f71cc93 100644 --- a/api/reply.go +++ b/api/reply.go @@ -202,7 +202,7 @@ func customReplyDebugModeGet(c echo.Context) error { } return c.JSON(http.StatusOK, map[string]interface{}{ - "value": myDice.ReplyDebugMode, + "value": myDice.Config.ReplyDebugMode, }) } @@ -219,9 +219,9 @@ func customReplyDebugModeSet(c echo.Context) error { return c.String(430, err.Error()) } - myDice.ReplyDebugMode = v.Value + myDice.Config.ReplyDebugMode = v.Value myDice.MarkModified() return c.JSON(http.StatusOK, map[string]interface{}{ - "value": myDice.ReplyDebugMode, + "value": myDice.Config.ReplyDebugMode, }) } diff --git a/dice/builtin_commands.go b/dice/builtin_commands.go index fb2f3f19..5f16f4af 100644 --- a/dice/builtin_commands.go +++ b/dice/builtin_commands.go @@ -75,7 +75,7 @@ func (d *Dice) registerCoreCommands() { if reason == "" { reason = "骰主指令" } - d.BanList.AddScoreBase(uid, d.BanList.ThresholdBan, "骰主指令", reason, ctx) + d.Config.BanList.AddScoreBase(uid, d.Config.BanList.ThresholdBan, "骰主指令", reason, ctx) ReplyToSender(ctx, msg, fmt.Sprintf("已将用户/群组 %s 加入黑名单,原因: %s", uid, reason)) case "rm", "del": uid = getID() @@ -83,7 +83,7 @@ func (d *Dice) registerCoreCommands() { return CmdExecuteResult{Matched: true, Solved: true, ShowHelp: true} } - item, ok := d.BanList.GetByID(uid) + item, ok := d.Config.BanList.GetByID(uid) if !ok || (item.Rank != BanRankBanned && item.Rank != BanRankTrusted && item.Rank != BanRankWarn) { ReplyToSender(ctx, msg, "找不到用户/群组") break @@ -99,14 +99,14 @@ func (d *Dice) registerCoreCommands() { return CmdExecuteResult{Matched: true, Solved: true, ShowHelp: true} } - d.BanList.SetTrustByID(uid, "骰主指令", "骰主指令") + d.Config.BanList.SetTrustByID(uid, "骰主指令", "骰主指令") ReplyToSender(ctx, msg, fmt.Sprintf("已将用户/群组 %s 加入信任列表", uid)) case "list", "show": // ban/warn/trust var extra, text string extra = cmdArgs.GetArgN(2) - d.BanList.Map.Range(func(k string, v *BanListInfoItem) bool { + d.Config.BanList.Map.Range(func(k string, v *BanListInfoItem) bool { if v.Rank == BanRankNormal { return true } @@ -133,7 +133,7 @@ func (d *Dice) registerCoreCommands() { break } - v, exists := d.BanList.Map.Load(targetID) + v, exists := d.Config.BanList.Map.Load(targetID) if !exists { ReplyToSender(ctx, msg, fmt.Sprintf("所查询的<%s>情况:正常(0)", targetID)) break @@ -495,7 +495,7 @@ func (d *Dice) registerCoreCommands() { if inGroup { // 不响应裸指令选项 - if len(cmdArgs.At) < 1 && ctx.Dice.IgnoreUnaddressedBotCmd { + if len(cmdArgs.At) < 1 && ctx.Dice.Config.IgnoreUnaddressedBotCmd { return CmdExecuteResult{Matched: true, Solved: false} } // 不响应at其他人 @@ -527,7 +527,7 @@ func (d *Dice) registerCoreCommands() { } if cmdArgs.IsArgEqual(1, "on") { - if !(msg.Platform == "QQ-CH" || ctx.Dice.BotExtFreeSwitch || ctx.PrivilegeLevel >= 40) { + if !(msg.Platform == "QQ-CH" || ctx.Dice.Config.BotExtFreeSwitch || ctx.PrivilegeLevel >= 40) { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:提示_无权限_非master/管理/邀请者")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -550,7 +550,7 @@ func (d *Dice) registerCoreCommands() { return CmdExecuteResult{Matched: true, Solved: true} } else if cmdArgs.IsArgEqual(1, "off") { - if !(msg.Platform == "QQ-CH" || ctx.Dice.BotExtFreeSwitch || ctx.PrivilegeLevel >= 40) { + if !(msg.Platform == "QQ-CH" || ctx.Dice.Config.BotExtFreeSwitch || ctx.PrivilegeLevel >= 40) { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:提示_无权限_非master/管理/邀请者")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -1036,11 +1036,11 @@ func (d *Dice) registerCoreCommands() { ret := <-dm.UpdateDownloadedChan if ctx.IsPrivate { - ctx.Dice.UpgradeWindowID = msg.Sender.UserID + ctx.Dice.Config.UpgradeWindowID = msg.Sender.UserID } else { - ctx.Dice.UpgradeWindowID = ctx.Group.GroupID + ctx.Dice.Config.UpgradeWindowID = ctx.Group.GroupID } - ctx.Dice.UpgradeEndpointID = ctx.EndPoint.ID + ctx.Dice.Config.UpgradeEndpointID = ctx.EndPoint.ID ctx.Dice.Save(true) bakFn, _ := ctx.Dice.Parent.Backup(BackupSelectionAll, false) @@ -1207,7 +1207,7 @@ func (d *Dice) registerCoreCommands() { } ctx.SystemTemplate = ctx.Group.GetCharTemplate(ctx.Dice) - if ctx.Dice.CommandCompatibleMode { + if ctx.Dice.Config.CommandCompatibleMode { if (cmdArgs.Command == "rd" || cmdArgs.Command == "rhd" || cmdArgs.Command == "rdh") && len(cmdArgs.Args) >= 1 { if m, _ := regexp.MatchString(`^\d|优势|劣势|\+|-`, cmdArgs.CleanArgs); m { if cmdArgs.IsSpaceBeforeArgs { @@ -1348,7 +1348,7 @@ func (d *Dice) registerCoreCommands() { if cmdArgs.SpecialExecuteTimes > 1 { VarSetValueInt64(ctx, "$t次数", int64(cmdArgs.SpecialExecuteTimes)) - if cmdArgs.SpecialExecuteTimes > int(ctx.Dice.MaxExecuteTime) { + if cmdArgs.SpecialExecuteTimes > int(ctx.Dice.Config.MaxExecuteTime) { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:骰点_轮数过多警告")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -1501,7 +1501,7 @@ func (d *Dice) registerCoreCommands() { if cmdArgs.IsArgEqual(1, "list") { showList() } else if cmdArgs.IsArgEqual(last, "on") { - if !ctx.Dice.BotExtFreeSwitch && ctx.PrivilegeLevel < 40 { + if !ctx.Dice.Config.BotExtFreeSwitch && ctx.PrivilegeLevel < 40 { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:提示_无权限_非master/管理/邀请者")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -1544,7 +1544,7 @@ func (d *Dice) registerCoreCommands() { ReplyToSender(ctx, msg, text) } } else if cmdArgs.IsArgEqual(last, "off") { - if !ctx.Dice.BotExtFreeSwitch && ctx.PrivilegeLevel < 40 { + if !ctx.Dice.Config.BotExtFreeSwitch && ctx.PrivilegeLevel < 40 { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:提示_无权限_非master/管理/邀请者")) return CmdExecuteResult{Matched: true, Solved: true} } diff --git a/dice/config.go b/dice/config.go index d3f2ef40..a9a27fed 100644 --- a/dice/config.go +++ b/dice/config.go @@ -14,11 +14,9 @@ import ( "time" wr "github.com/mroth/weightedrand" - "golang.org/x/time/rate" "gopkg.in/yaml.v3" "sealdice-core/dice/model" - "sealdice-core/utils" ) // type TextTemplateWithWeight = map[string]map[string]uint @@ -2057,153 +2055,24 @@ func getNumVal(i interface{}) uint { } func (d *Dice) loads() { + config := NewConfig(d) data, err := os.ReadFile(filepath.Join(d.BaseConfig.DataDir, "serve.yaml")) - - // 配置这块弄得比较屎,有机会换个方案。。。 - // TODO(Xiangze Li): 不管谁都好 赶紧重写吧, 谁能想起来加了配置还要在这里添一行才能Load出来哇 if err == nil { //nolint:nestif + err3 := config.LoadYamlConfig(data) + if err3 != nil { + d.Logger.Error("serve.yaml parse failed") + panic(err3) + } + + // 有一些配置项被用 jsbind 导出了,只能先留在 Dice 不迁移了 dNew := Dice{} err2 := yaml.Unmarshal(data, &dNew) if err2 != nil { d.Logger.Error("serve.yaml parse failed") panic(err2) } - d.CommandCompatibleMode = true // 一直为true即可 d.ImSession.EndPoints = dNew.ImSession.EndPoints - d.CommandPrefix = dNew.CommandPrefix d.DiceMasters = dNew.DiceMasters - d.VersionCode = dNew.VersionCode - d.MessageDelayRangeStart = dNew.MessageDelayRangeStart - d.MessageDelayRangeEnd = dNew.MessageDelayRangeEnd - d.WorkInQQChannel = dNew.WorkInQQChannel - d.QQChannelLogMessage = dNew.QQChannelLogMessage - d.QQChannelAutoOn = dNew.QQChannelAutoOn - d.QQEnablePoke = dNew.QQEnablePoke - d.TextCmdTrustOnly = dNew.TextCmdTrustOnly - d.IgnoreUnaddressedBotCmd = dNew.IgnoreUnaddressedBotCmd - d.UILogLimit = dNew.UILogLimit - d.FriendAddComment = dNew.FriendAddComment - d.NoticeIDs = dNew.NoticeIDs - d.ExtDefaultSettings = dNew.ExtDefaultSettings - d.CustomReplyConfigEnable = dNew.CustomReplyConfigEnable - d.RefuseGroupInvite = dNew.RefuseGroupInvite - d.DefaultCocRuleIndex = dNew.DefaultCocRuleIndex - d.UpgradeWindowID = dNew.UpgradeWindowID - d.UpgradeEndpointID = dNew.UpgradeEndpointID - d.BotExtFreeSwitch = dNew.BotExtFreeSwitch - d.RateLimitEnabled = dNew.RateLimitEnabled - d.TrustOnlyMode = dNew.TrustOnlyMode - d.AliveNoticeEnable = dNew.AliveNoticeEnable - d.AliveNoticeValue = dNew.AliveNoticeValue - d.ReplyDebugMode = dNew.ReplyDebugMode - d.LogSizeNoticeCount = dNew.LogSizeNoticeCount - d.LogSizeNoticeEnable = dNew.LogSizeNoticeEnable - d.PlayerNameWrapEnable = dNew.PlayerNameWrapEnable - d.MailEnable = dNew.MailEnable - d.MailFrom = dNew.MailFrom - d.MailPassword = dNew.MailPassword - d.MailSMTP = dNew.MailSMTP - d.JsEnable = dNew.JsEnable - d.DisabledJsScripts = dNew.DisabledJsScripts - d.NewsMark = dNew.NewsMark - - d.QuitInactiveThreshold = dNew.QuitInactiveThreshold - d.QuitInactiveBatchSize = dNew.QuitInactiveBatchSize - if d.QuitInactiveBatchSize == 0 { - d.QuitInactiveBatchSize = 10 - } - d.QuitInactiveBatchWait = dNew.QuitInactiveBatchWait - if d.QuitInactiveBatchWait == 0 { - d.QuitInactiveBatchWait = 30 - } - - d.EnableCensor = dNew.EnableCensor - d.CensorMode = dNew.CensorMode - d.CensorThresholds = dNew.CensorThresholds - d.CensorHandlers = dNew.CensorHandlers - d.CensorScores = dNew.CensorScores - d.CensorCaseSensitive = dNew.CensorCaseSensitive - d.CensorMatchPinyin = dNew.CensorMatchPinyin - d.CensorFilterRegexStr = dNew.CensorFilterRegexStr - - d.VMVersionForDeck = dNew.VMVersionForDeck - d.VMVersionForReply = dNew.VMVersionForReply - - if d.VMVersionForDeck == "" { - d.VMVersionForDeck = "v2" - } - - if d.VMVersionForReply == "" { - d.VMVersionForReply = "v1" - } - - if dNew.BanList != nil { - d.BanList.BanBehaviorRefuseReply = dNew.BanList.BanBehaviorRefuseReply - d.BanList.BanBehaviorRefuseInvite = dNew.BanList.BanBehaviorRefuseInvite - d.BanList.BanBehaviorQuitLastPlace = dNew.BanList.BanBehaviorQuitLastPlace - d.BanList.BanBehaviorQuitPlaceImmediately = dNew.BanList.BanBehaviorQuitPlaceImmediately - d.BanList.BanBehaviorQuitIfAdmin = dNew.BanList.BanBehaviorQuitIfAdmin - - d.BanList.ScoreReducePerMinute = dNew.BanList.ScoreReducePerMinute - - d.BanList.ThresholdWarn = dNew.BanList.ThresholdWarn - d.BanList.ThresholdBan = dNew.BanList.ThresholdBan - d.BanList.ScoreGroupMuted = dNew.BanList.ScoreGroupMuted - d.BanList.ScoreGroupKicked = dNew.BanList.ScoreGroupKicked - d.BanList.ScoreTooManyCommand = dNew.BanList.ScoreTooManyCommand - - d.BanList.JointScorePercentOfGroup = dNew.BanList.JointScorePercentOfGroup - d.BanList.JointScorePercentOfInviter = dNew.BanList.JointScorePercentOfInviter - } - - d.MaxExecuteTime = dNew.MaxExecuteTime - if d.MaxExecuteTime == 0 { - d.MaxExecuteTime = 12 - } - - d.MaxCocCardGen = dNew.MaxCocCardGen - if d.MaxCocCardGen == 0 { - d.MaxCocCardGen = 5 - } - - d.PersonalReplenishRateStr = dNew.PersonalReplenishRateStr - if d.PersonalReplenishRateStr == "" { - d.PersonalReplenishRateStr = "@every 3s" - d.PersonalReplenishRate = rate.Every(time.Second * 3) - } else { - if parsed, errParse := utils.ParseRate(d.PersonalReplenishRateStr); errParse == nil { - d.PersonalReplenishRate = parsed - } else { - d.Logger.Errorf("解析PersonalReplenishRate失败: %v", errParse) - d.PersonalReplenishRateStr = "@every 3s" - d.PersonalReplenishRate = rate.Every(time.Second * 3) - } - } - - d.PersonalBurst = dNew.PersonalBurst - if d.PersonalBurst == 0 { - d.PersonalBurst = 3 - } - - d.GroupReplenishRateStr = dNew.GroupReplenishRateStr - if d.GroupReplenishRateStr == "" { - d.GroupReplenishRateStr = "@every 3s" - d.GroupReplenishRate = rate.Every(time.Second * 3) - } else { - if parsed, errParse := utils.ParseRate(d.GroupReplenishRateStr); errParse == nil { - d.GroupReplenishRate = parsed - } else { - d.Logger.Errorf("解析GroupReplenishRate失败: %v", errParse) - d.GroupReplenishRateStr = "@every 3s" - d.GroupReplenishRate = rate.Every(time.Second * 3) - } - } - - d.GroupBurst = dNew.GroupBurst - if d.GroupBurst == 0 { - d.GroupBurst = 3 - } - if len(d.DiceMasters) == 0 { d.DiceMasters = []string{"UI:1001"} } @@ -2277,22 +2146,7 @@ func (d *Dice) loads() { return true }) - if d.VersionCode != 0 && d.VersionCode < 10000 { - d.CustomReplyConfigEnable = false - } - - if d.VersionCode != 0 && d.VersionCode < 10001 { - d.AliveNoticeValue = "@every 3h" - } - - if d.VersionCode != 0 && d.VersionCode < 10003 { - d.Logger.Infof("进行配置文件版本升级: %d -> %d", d.VersionCode, 10003) - d.LogSizeNoticeCount = 500 - d.LogSizeNoticeEnable = true - d.CustomReplyConfigEnable = true - } - - if d.VersionCode != 0 && d.VersionCode < 10005 { + if config.VersionCode != 0 && config.VersionCode < 10005 { d.RunAfterLoaded = append(d.RunAfterLoaded, func() { d.Logger.Info("正在自动升级自定义文案文件") for index, text := range d.TextMapRaw["核心"]["昵称_重置"] { @@ -2315,10 +2169,10 @@ func (d *Dice) loads() { } // 1.2 版本 - if d.VersionCode != 0 && d.VersionCode < 10200 { - d.TextCmdTrustOnly = true - d.QQEnablePoke = true - d.PlayerNameWrapEnable = true + if config.VersionCode != 0 && config.VersionCode < 10200 { + config.TextCmdTrustOnly = DefaultConfig.TextCmdTrustOnly + config.QQEnablePoke = DefaultConfig.QQEnablePoke + config.PlayerNameWrapEnable = DefaultConfig.PlayerNameWrapEnable isUI1001Master := false for _, i := range d.DiceMasters { @@ -2346,7 +2200,7 @@ func (d *Dice) loads() { } // 1.2 版本 - if d.VersionCode != 0 && d.VersionCode < 10203 { + if config.VersionCode != 0 && config.VersionCode < 10203 { d.RunAfterLoaded = append(d.RunAfterLoaded, func() { // 更正写反的部分 d.Logger.Info("正在自动升级自定义文案文件") @@ -2362,8 +2216,8 @@ func (d *Dice) loads() { } // 1.3 版本 - if d.VersionCode != 0 && d.VersionCode < 10300 { - d.JsEnable = true + if config.VersionCode != 0 && config.VersionCode < 10300 { + config.JsEnable = DefaultConfig.JsEnable d.RunAfterLoaded = append(d.RunAfterLoaded, func() { // 更正写反的部分 @@ -2394,6 +2248,8 @@ func (d *Dice) loads() { d.SaveText() }) + d.Config = config + // 1.4.5 版本 - 覆写lagrange配置 for _, i := range d.ImSession.EndPoints { if i.ProtocolType == "onebot" { @@ -2422,34 +2278,9 @@ func (d *Dice) loads() { }) d.Logger.Info("serve.yaml loaded") } else { - // 这里是没有加载到配置文件,所以写默认设置项 - d.WorkInQQChannel = true - d.CustomReplyConfigEnable = false - d.AliveNoticeValue = "@every 3h" d.Logger.Info("serve.yaml not found") - - d.LogSizeNoticeCount = 500 - d.LogSizeNoticeEnable = true - - // 1.2 - d.QQEnablePoke = true - d.TextCmdTrustOnly = true - d.PlayerNameWrapEnable = true + // 这里是没有加载到配置文件,所以写默认设置项 d.DiceMasters = []string{"UI:1001"} - - // 1.3 - d.JsEnable = true - - // 1.4 - d.MaxExecuteTime = 12 - d.MaxCocCardGen = 5 - - d.QuitInactiveBatchSize = 10 - d.QuitInactiveBatchWait = 30 - - // 1.5 - d.VMVersionForDeck = "v2" - d.VMVersionForReply = "v1" } _ = model.BanItemList(d.DBData, func(id string, banUpdatedAt int64, data []byte) { @@ -2457,7 +2288,7 @@ func (d *Dice) loads() { err := json.Unmarshal(data, &v) if err == nil { v.BanUpdatedAt = banUpdatedAt - d.BanList.Map.Store(id, &v) + d.Config.BanList.Map.Store(id, &v) } }) @@ -2466,10 +2297,6 @@ func (d *Dice) loads() { i.AdapterSetup() } - if d.NoticeIDs == nil { - d.NoticeIDs = []string{} - } - if len(d.CommandPrefix) == 0 { d.CommandPrefix = []string{ "!", @@ -2479,8 +2306,7 @@ func (d *Dice) loads() { } } - d.VersionCode = 10300 // TODO: 记得修改!!! - d.LogWriter.LogLimit = d.UILogLimit + d.LogWriter.LogLimit = d.Config.UILogLimit // 设置扩展选项 d.ApplyExtDefaultSettings() @@ -2536,7 +2362,7 @@ func (d *Dice) SaveText() { func (d *Dice) ApplyExtDefaultSettings() { // 遍历两个列表 exts1 := map[string]*ExtDefaultSettingItem{} - for _, i := range d.ExtDefaultSettings { + for _, i := range d.Config.ExtDefaultSettings { exts1[i.Name] = i } @@ -2549,7 +2375,7 @@ func (d *Dice) ApplyExtDefaultSettings() { for k, v := range exts2 { if _, exists := exts1[k]; !exists { item := &ExtDefaultSettingItem{Name: k, AutoActive: v.AutoActive, DisabledCommand: map[string]bool{}} - d.ExtDefaultSettings = append(d.ExtDefaultSettings, item) + d.Config.ExtDefaultSettings = append(d.Config.ExtDefaultSettings, item) exts1[k] = item } } @@ -2597,7 +2423,24 @@ func (d *Dice) ApplyExtDefaultSettings() { func (d *Dice) Save(isAuto bool) { if d.LastUpdatedTime != 0 { - a, err1 := yaml.Marshal(d) + totalConf := &struct { + // copy from Dice + ImSession *IMSession `yaml:"imSession" jsbind:"imSession" json:"-"` + DeckList []*DeckInfo `yaml:"deckList" jsbind:"deckList"` // 牌堆信息 + CommandPrefix []string `yaml:"commandPrefix" jsbind:"commandPrefix"` // 指令前导 + DiceMasters []string `yaml:"diceMasters" jsbind:"diceMasters"` // 骰主设置,需要格式: 平台:帐号 + + Config `yaml:",inline"` + }{ + // 这些都是由于导出到 goja 无法拆分的字段 + d.ImSession, + d.DeckList, + d.CommandPrefix, + d.DiceMasters, + + d.Config, + } + a, err1 := yaml.Marshal(totalConf) advancedData, err2 := yaml.Marshal(d.AdvancedConfig) if err1 == nil && err2 == nil { @@ -2605,7 +2448,7 @@ func (d *Dice) Save(isAuto bool) { err2 := os.WriteFile(filepath.Join(d.BaseConfig.DataDir, "advanced.yaml"), advancedData, 0o644) if err1 == nil && err2 == nil { now := time.Now() - d.LastSavedTime = &now + d.Config.LastSavedTime = &now if isAuto { d.Logger.Info("自动保存") } else { @@ -2654,7 +2497,7 @@ func (d *Dice) Save(isAuto bool) { // 保存黑名单数据 // TODO: 增加更新时间检测 - // model.BanMapSet(d.DBData, d.BanList.MapToJSON()) + // model.BanMapSet(d.DBData, d.Config.BanList.MapToJSON()) // endpoint数据额外更新到数据库 for _, ep := range d.ImSession.EndPoints { diff --git a/dice/dice.go b/dice/dice.go index 82b91a1d..a39588f9 100644 --- a/dice/dice.go +++ b/dice/dice.go @@ -21,9 +21,7 @@ import ( "github.com/tidwall/buntdb" rand2 "golang.org/x/exp/rand" "golang.org/x/exp/slices" - "golang.org/x/time/rate" - "sealdice-core/dice/censor" "sealdice-core/dice/logger" "sealdice-core/dice/model" log "sealdice-core/utils/kratos" @@ -103,8 +101,8 @@ type ExtInfo struct { OnLoad func() `yaml:"-" json:"-" jsbind:"onLoad"` } -// DiceConfig TODO:历史遗留问题,由于不输出DICE日志效果过差,已经抹除日志输出选项,剩余两个选项,私以为可以想办法也抹除掉。 -type DiceConfig struct { //nolint:revive +// RootConfig TODO:历史遗留问题,由于不输出DICE日志效果过差,已经抹除日志输出选项,剩余两个选项,私以为可以想办法也抹除掉。 +type RootConfig struct { //nolint:revive Name string `yaml:"name"` // 名称,默认为default DataDir string `yaml:"dataDir"` // 数据路径,为./data/{name},例如data/default } @@ -126,71 +124,29 @@ func (x ExtDefaultSettingItemSlice) Less(i, _ int) bool { return x[i].Name == "c func (x ExtDefaultSettingItemSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] } type Dice struct { - ImSession *IMSession `yaml:"imSession" jsbind:"imSession"` - CmdMap CmdMapCls `yaml:"-" json:"-"` - ExtList []*ExtInfo `yaml:"-"` - RollParser *DiceRollParser `yaml:"-"` - CommandCompatibleMode bool `yaml:"commandCompatibleMode"` - LastSavedTime *time.Time `yaml:"lastSavedTime"` - LastUpdatedTime int64 `yaml:"-"` - TextMap map[string]*wr.Chooser `yaml:"-"` - BaseConfig DiceConfig `yaml:"-"` - DBData *sqlx.DB `yaml:"-"` // 数据库对象 - DBLogs *sqlx.DB `yaml:"-"` // 数据库对象 - Logger *log.Helper `yaml:"-"` // 日志 - LogWriter *log.WriterX `yaml:"-"` // 用于api的log对象 - IsDeckLoading bool `yaml:"-"` // 正在加载中 - DeckList []*DeckInfo `yaml:"deckList" jsbind:"deckList"` // 牌堆信息 - CommandPrefix []string `yaml:"commandPrefix" jsbind:"commandPrefix"` // 指令前导 - DiceMasters []string `yaml:"diceMasters" jsbind:"diceMasters"` // 骰主设置,需要格式: 平台:帐号 - NoticeIDs []string `yaml:"noticeIds"` // 通知ID - OnlyLogCommandInGroup bool `yaml:"onlyLogCommandInGroup"` // 日志中仅记录命令 - OnlyLogCommandInPrivate bool `yaml:"onlyLogCommandInPrivate"` // 日志中仅记录命令 - VersionCode int `json:"versionCode"` // 版本ID(配置文件) - MessageDelayRangeStart float64 `yaml:"messageDelayRangeStart"` // 指令延迟区间 - MessageDelayRangeEnd float64 `yaml:"messageDelayRangeEnd"` - WorkInQQChannel bool `yaml:"workInQQChannel"` - QQChannelAutoOn bool `yaml:"QQChannelAutoOn"` // QQ频道中自动开启(默认不开) - QQChannelLogMessage bool `yaml:"QQChannelLogMessage"` // QQ频道中记录消息(默认不开) - QQEnablePoke bool `yaml:"QQEnablePoke"` // 启用戳一戳 - TextCmdTrustOnly bool `yaml:"textCmdTrustOnly"` // 只允许信任用户或master使用text指令 - IgnoreUnaddressedBotCmd bool `yaml:"ignoreUnaddressedBotCmd"` // 不响应群聊裸bot指令 - UILogLimit int64 `yaml:"UILogLimit"` - FriendAddComment string `yaml:"friendAddComment"` // 加好友验证信息 - MasterUnlockCode string `yaml:"-"` // 解锁码,每20分钟变化一次,使用后立即变化 - MasterUnlockCodeTime int64 `yaml:"-"` - CustomReplyConfigEnable bool `yaml:"customReplyConfigEnable"` - CustomReplyConfig []*ReplyConfig `yaml:"-"` - RefuseGroupInvite bool `yaml:"refuseGroupInvite"` // 拒绝加入新群 - UpgradeWindowID string `yaml:"upgradeWindowId"` // 执行升级指令的窗口 - UpgradeEndpointID string `yaml:"upgradeEndpointId"` // 执行升级指令的端点 - BotExtFreeSwitch bool `yaml:"botExtFreeSwitch"` // 允许任意人员开关: 否则邀请者、群主、管理员、master有权限 - TrustOnlyMode bool `yaml:"trustOnlyMode"` // 只有信任的用户/master可以拉群和使用 - AliveNoticeEnable bool `yaml:"aliveNoticeEnable"` // 定时通知 - AliveNoticeValue string `yaml:"aliveNoticeValue"` // 定时通知间隔 - ReplyDebugMode bool `yaml:"replyDebugMode"` // 回复调试 - PlayerNameWrapEnable bool `yaml:"playerNameWrapEnable"` // 启用玩家名称外框 - - RateLimitEnabled bool `yaml:"rateLimitEnabled"` // 启用频率限制 (刷屏限制) - PersonalReplenishRateStr string `yaml:"personalReplenishRate"` // 个人刷屏警告速率,字符串格式 - PersonalReplenishRate rate.Limit `yaml:"-"` // 个人刷屏警告速率 - GroupReplenishRateStr string `yaml:"groupReplenishRate"` // 群组刷屏警告速率,字符串格式 - GroupReplenishRate rate.Limit `yaml:"-"` // 群组刷屏警告速率 - PersonalBurst int64 `yaml:"personalBurst"` // 个人自定义上限 - GroupBurst int64 `yaml:"groupBurst"` // 群组自定义上限 - - QuitInactiveThreshold time.Duration `yaml:"quitInactiveThreshold"` // 退出不活跃群组的时间阈值 - quitInactiveCronEntry cron.EntryID - QuitInactiveBatchSize int64 `yaml:"quitInactiveBatchSize"` // 退出不活跃群组的批量大小 - QuitInactiveBatchWait int64 `yaml:"quitInactiveBatchWait"` // 退出不活跃群组的批量等待时间(分) - - DefaultCocRuleIndex int64 `yaml:"defaultCocRuleIndex" jsbind:"defaultCocRuleIndex"` // 默认coc index - MaxExecuteTime int64 `yaml:"maxExecuteTime" jsbind:"maxExecuteTime"` // 最大骰点次数 - MaxCocCardGen int64 `yaml:"maxCocCardGen" jsbind:"maxCocCardGen"` // 最大coc制卡数 - - ExtDefaultSettings []*ExtDefaultSettingItem `yaml:"extDefaultSettings"` // 新群扩展按此顺序加载 - - BanList *BanListInfo `yaml:"banList"` // + // 由于被导出的原因,暂时不迁移至 config + ImSession *IMSession `yaml:"imSession" jsbind:"imSession" json:"-"` + + CmdMap CmdMapCls `yaml:"-" json:"-"` + ExtList []*ExtInfo `yaml:"-"` + RollParser *DiceRollParser `yaml:"-"` + LastUpdatedTime int64 `yaml:"-"` + TextMap map[string]*wr.Chooser `yaml:"-"` + BaseConfig BaseConfig `yaml:"-"` + DBData *sqlx.DB `yaml:"-"` // 数据库对象 + DBLogs *sqlx.DB `yaml:"-"` // 数据库对象 + Logger *log.Helper `yaml:"-"` // 日志 + LogWriter *log.WriterX `yaml:"-"` // 用于api的log对象 + IsDeckLoading bool `yaml:"-"` // 正在加载中 + + // 由于被导出的原因,暂时不迁移至 config + DeckList []*DeckInfo `yaml:"deckList" jsbind:"deckList"` // 牌堆信息 + CommandPrefix []string `yaml:"commandPrefix" jsbind:"commandPrefix"` // 指令前导 + DiceMasters []string `yaml:"diceMasters" jsbind:"diceMasters"` // 骰主设置,需要格式: 平台:帐号 + + MasterUnlockCode string `yaml:"-" json:"masterUnlockCode"` // 解锁码,每20分钟变化一次,使用后立即变化 + MasterUnlockCodeTime int64 `yaml:"-" json:"masterUnlockCodeTime"` + CustomReplyConfig []*ReplyConfig `yaml:"-" json:"-"` TextMapRaw TextTemplateWithWeightDict `yaml:"-"` TextMapHelpInfo TextTemplateWithHelpDict `yaml:"-"` @@ -199,20 +155,17 @@ type Dice struct { ConfigManager *ConfigManager `yaml:"-"` Parent *DiceManager `yaml:"-"` - CocExtraRules map[int]*CocRuleInfo `yaml:"-" json:"cocExtraRules"` - Cron *cron.Cron `yaml:"-" json:"-"` - AliveNoticeEntry cron.EntryID `yaml:"-" json:"-"` - JsEnable bool `yaml:"jsEnable" json:"jsEnable"` - DisabledJsScripts map[string]bool `yaml:"disabledJsScripts" json:"disabledJsScripts"` // 作为set - JsPrinter *PrinterFunc `yaml:"-" json:"-"` - JsRequire *require.RequireModule `yaml:"-" json:"-"` - JsLoop *eventloop.EventLoop `yaml:"-" json:"-"` - JsScriptList []*JsScriptInfo `yaml:"-" json:"-"` - JsScriptCron *cron.Cron `yaml:"-" json:"-"` - JsScriptCronLock *sync.Mutex `yaml:"-" json:"-"` + CocExtraRules map[int]*CocRuleInfo `yaml:"-" json:"cocExtraRules"` + Cron *cron.Cron `yaml:"-" json:"-"` + AliveNoticeEntry cron.EntryID `yaml:"-" json:"-"` + JsPrinter *PrinterFunc `yaml:"-" json:"-"` + JsRequire *require.RequireModule `yaml:"-" json:"-"` + JsLoop *eventloop.EventLoop `yaml:"-" json:"-"` + JsScriptList []*JsScriptInfo `yaml:"-" json:"-"` + JsScriptCron *cron.Cron `yaml:"-" json:"-"` + JsScriptCronLock *sync.Mutex `yaml:"-" json:"-"` // 重载使用的互斥锁 JsReloadLock sync.Mutex `yaml:"-" json:"-"` - // 内置脚本摘要表,用于判断内置脚本是否有更新 JsBuiltinDigestSet map[string]bool `yaml:"-" json:"-"` // 当前在加载的脚本路径,用于关联 jsScriptInfo 和 ExtInfo @@ -223,75 +176,23 @@ type Dice struct { RunAfterLoaded []func() `yaml:"-" json:"-"` - LogSizeNoticeEnable bool `yaml:"logSizeNoticeEnable"` // 开启日志数量提示 - LogSizeNoticeCount int `yaml:"LogSizeNoticeCount"` // 日志数量提示阈值,默认500 - - IsAlreadyLoadConfig bool `yaml:"-"` // 如果在loads前崩溃,那么不写入配置,防止覆盖为空的 deckCommandItemsList DeckCommandListItems // 牌堆key信息,辅助作为模糊搜索使用 UIEndpoint *EndPointInfo `yaml:"-" json:"-"` // UI Endpoint - MailEnable bool `json:"mailEnable" yaml:"mailEnable"` // 是否启用 - MailFrom string `json:"mailFrom" yaml:"mailFrom"` // 邮箱来源 - MailPassword string `json:"mailPassword" yaml:"mailPassword"` // 邮箱密钥/密码 - MailSMTP string `json:"mailSmtp" yaml:"mailSmtp"` // 邮箱 smtp 地址 - - NewsMark string `json:"newsMark" yaml:"newsMark"` // 已读新闻的md5 + CensorManager *CensorManager `json:"-" yaml:"-"` - EnableCensor bool `json:"enableCensor" yaml:"enableCensor"` // 启用敏感词审查 - CensorManager *CensorManager `json:"-" yaml:"-"` - CensorMode CensorMode `json:"censorMode" yaml:"censorMode"` - CensorThresholds map[censor.Level]int `json:"censorThresholds" yaml:"censorThresholds"` // 敏感词阈值 - CensorHandlers map[censor.Level]uint8 `json:"censorHandlers" yaml:"censorHandlers"` - CensorScores map[censor.Level]int `json:"censorScores" yaml:"censorScores"` // 敏感词怒气值 - CensorCaseSensitive bool `json:"censorCaseSensitive" yaml:"censorCaseSensitive"` // 敏感词大小写敏感 - CensorMatchPinyin bool `json:"censorMatchPinyin" yaml:"censorMatchPinyin"` // 敏感词匹配拼音 - CensorFilterRegexStr string `json:"censorFilterRegexStr" yaml:"censorFilterRegexStr"` // 敏感词过滤字符正则 - - VMVersionForReply string `json:"VMVersionForReply" yaml:"VMVersionForReply"` // 自定义回复使用的vm版本 - VMVersionForDeck string `json:"VMVersionForDeck" yaml:"VMVersionForDeck"` // 牌堆使用的vm版本 + Config Config `json:"-" yaml:"-"` AttrsManager *AttrsManager `json:"-" yaml:"-"` AdvancedConfig AdvancedConfig `json:"-" yaml:"-"` ContainerMode bool `yaml:"-" json:"-"` // 容器模式:禁用内置适配器,不允许使用内置Lagrange和旧的内置Gocq -} - -type CensorMode int -const ( - OnlyOutputReply CensorMode = iota - OnlyInputCommand - AllInput -) - -const ( - // SendWarning 发送警告 - SendWarning CensorHandler = iota - // SendNotice 向通知列表/邮件发送通知 - SendNotice - // BanUser 拉黑用户 - BanUser - // BanGroup 拉黑群 - BanGroup - // BanInviter 拉黑邀请人 - BanInviter - // AddScore 增加怒气值 - AddScore -) - -var CensorHandlerText = map[CensorHandler]string{ - SendWarning: "SendWarning", - SendNotice: "SendNotice", - BanUser: "BanUser", - BanGroup: "BanGroup", - BanInviter: "BanInviter", - AddScore: "AddScore", + IsAlreadyLoadConfig bool `yaml:"-"` // 如果在loads前崩溃,那么不写入配置,防止覆盖为空的 } -type CensorHandler int - func (d *Dice) MarkModified() { d.LastUpdatedTime = time.Now().Unix() } @@ -332,12 +233,12 @@ func (d *Dice) Init() { d.AttrsManager = &AttrsManager{} d.AttrsManager.Init(d) - d.BanList = &BanListInfo{Parent: d} - d.BanList.Init() + d.Config.BanList = &BanListInfo{Parent: d} + d.Config.BanList.Init() initVerify() - d.CommandCompatibleMode = true + d.BaseConfig.CommandCompatibleMode = true // Pinenutn: 预先初始化对应的SyncMap d.ImSession = &IMSession{} d.ImSession.Parent = d @@ -354,16 +255,16 @@ func (d *Dice) Init() { d.RegisterBuiltinExt() d.loads() d.loadAdvanced() - d.BanList.Loads() - d.BanList.AfterLoads() + d.Config.BanList.Loads() + d.Config.BanList.AfterLoads() d.IsAlreadyLoadConfig = true - if d.EnableCensor { + if d.Config.EnableCensor { d.NewCensorManager() } // 创建js运行时 - if d.JsEnable { + if d.Config.JsEnable { d.Logger.Info("js扩展支持:开启") d.JsInit() } else { @@ -455,20 +356,20 @@ func (d *Dice) Init() { go refreshGroupInfo() d.ApplyAliveNotice() - if d.JsEnable { + if d.Config.JsEnable { d.JsBuiltinDigestSet = make(map[string]bool) d.JsLoadScripts() } else { d.Logger.Info("js扩展支持已关闭,跳过js脚本的加载") } - if d.UpgradeWindowID != "" { + if d.Config.UpgradeWindowID != "" { go func() { defer ErrorLogAndContinue(d) var ep *EndPointInfo for _, _ep := range d.ImSession.EndPoints { - if _ep.ID == d.UpgradeEndpointID { + if _ep.ID == d.Config.UpgradeEndpointID { ep = _ep break } @@ -490,16 +391,16 @@ func (d *Dice) Init() { // 可以了,发送消息 ctx := &MsgContext{Dice: d, EndPoint: ep, Session: d.ImSession} - isGroup := strings.Contains(d.UpgradeWindowID, "-Group:") + isGroup := strings.Contains(d.Config.UpgradeWindowID, "-Group:") if isGroup { - ReplyGroup(ctx, &Message{GroupID: d.UpgradeWindowID}, text) + ReplyGroup(ctx, &Message{GroupID: d.Config.UpgradeWindowID}, text) } else { - ReplyPerson(ctx, &Message{Sender: SenderBase{UserID: d.UpgradeWindowID}}, text) + ReplyPerson(ctx, &Message{Sender: SenderBase{UserID: d.Config.UpgradeWindowID}}, text) } d.Logger.Infof("升级完成,当前版本: %s", VERSION.String()) - d.UpgradeWindowID = "" - d.UpgradeEndpointID = "" + d.Config.UpgradeWindowID = "" + d.Config.UpgradeEndpointID = "" d.MarkModified() d.Save(false) break @@ -709,8 +610,8 @@ func (d *Dice) ApplyAliveNotice() { if d.Cron != nil && d.AliveNoticeEntry != 0 { d.Cron.Remove(d.AliveNoticeEntry) } - if d.AliveNoticeEnable { - entry, err := d.Cron.AddFunc(d.AliveNoticeValue, func() { + if d.Config.AliveNoticeEnable { + entry, err := d.Cron.AddFunc(d.Config.AliveNoticeValue, func() { d.NoticeForEveryEndpoint(fmt.Sprintf("存活, D100=%d", DiceRoll64(100)), false) }) if err == nil { @@ -786,19 +687,19 @@ var chsS2T = sat.DefaultDict() func (d *Dice) ResetQuitInactiveCron() { dm := d.Parent - if d.quitInactiveCronEntry > 0 { - dm.Cron.Remove(d.quitInactiveCronEntry) - d.quitInactiveCronEntry = 0 + if d.Config.quitInactiveCronEntry > 0 { + dm.Cron.Remove(d.Config.quitInactiveCronEntry) + d.Config.quitInactiveCronEntry = DefaultConfig.quitInactiveCronEntry } - if d.QuitInactiveThreshold > 0 { + if d.Config.QuitInactiveThreshold > 0 { var err error - d.quitInactiveCronEntry, err = dm.Cron.AddFunc("0 4 * * *", func() { - thr := time.Now().Add(-d.QuitInactiveThreshold) - hint := thr.Add(d.QuitInactiveThreshold / 10) // 进入退出判定线的9/10开始提醒 + d.Config.quitInactiveCronEntry, err = dm.Cron.AddFunc("0 4 * * *", func() { + thr := time.Now().Add(-d.Config.QuitInactiveThreshold) + hint := thr.Add(d.Config.QuitInactiveThreshold / 10) // 进入退出判定线的9/10开始提醒 d.ImSession.LongTimeQuitInactiveGroup(thr, hint, - int(d.QuitInactiveBatchWait), - int(d.QuitInactiveBatchSize)) + int(d.Config.QuitInactiveBatchWait), + int(d.Config.QuitInactiveBatchSize)) }) if err != nil { d.Logger.Errorf("创建自动清理群聊cron任务失败: %v", err) diff --git a/dice/dice_ban.go b/dice/dice_ban.go index aeb0095e..b8c839c0 100644 --- a/dice/dice_ban.go +++ b/dice/dice_ban.go @@ -105,7 +105,7 @@ func (i *BanListInfo) AfterLoads() { return } var toDelete []string - d.BanList.Map.Range(func(k string, v *BanListInfoItem) bool { + d.Config.BanList.Map.Range(func(k string, v *BanListInfoItem) bool { if v.Rank == BanRankNormal || v.Rank == BanRankWarn { v.Score -= i.ScoreReducePerMinute if v.Score <= 0 { @@ -121,7 +121,7 @@ func (i *BanListInfo) AfterLoads() { _ = model.BanItemDel(d.DBData, j) } - d.BanList.SaveChanged(d) + d.Config.BanList.SaveChanged(d) }) } @@ -281,7 +281,7 @@ func (i *BanListInfo) NoticeCheck(uid string, place string, oldRank BanRankType, if ctx != nil { var isWhiteGroup bool d := ctx.Dice - value, exists := d.BanList.Map.Load(place) + value, exists := d.Config.BanList.Map.Load(place) if exists { if value.Rank == BanRankTrusted { isWhiteGroup = true @@ -403,7 +403,7 @@ func (d *Dice) GetBanList() []*BanListInfoItem { } func (i *BanListInfo) SaveChanged(d *Dice) { - d.BanList.Map.Range(func(k string, v *BanListInfoItem) bool { + d.Config.BanList.Map.Range(func(k string, v *BanListInfoItem) bool { if v.UpdatedAt != 0 { data, err := json.Marshal(v) if err == nil { diff --git a/dice/dice_censor.go b/dice/dice_censor.go index 63fb0fbc..86bebd63 100644 --- a/dice/dice_censor.go +++ b/dice/dice_censor.go @@ -15,6 +15,40 @@ import ( "sealdice-core/dice/model" ) +type CensorMode int + +const ( + OnlyOutputReply CensorMode = iota + OnlyInputCommand + AllInput +) + +const ( + // SendWarning 发送警告 + SendWarning CensorHandler = iota + // SendNotice 向通知列表/邮件发送通知 + SendNotice + // BanUser 拉黑用户 + BanUser + // BanGroup 拉黑群 + BanGroup + // BanInviter 拉黑邀请人 + BanInviter + // AddScore 增加怒气值 + AddScore +) + +var CensorHandlerText = map[CensorHandler]string{ + SendWarning: "SendWarning", + SendNotice: "SendNotice", + BanUser: "BanUser", + BanGroup: "BanGroup", + BanInviter: "BanInviter", + AddScore: "AddScore", +} + +type CensorHandler int + type CensorManager struct { IsLoading bool Parent *Dice @@ -30,22 +64,22 @@ func (d *Dice) NewCensorManager() { } cm := CensorManager{ Censor: &censor.Censor{ - CaseSensitive: d.CensorCaseSensitive, - MatchPinyin: d.CensorMatchPinyin, - FilterRegexStr: d.CensorFilterRegexStr, + CaseSensitive: d.Config.CensorCaseSensitive, + MatchPinyin: d.Config.CensorMatchPinyin, + FilterRegexStr: d.Config.CensorFilterRegexStr, }, DB: db, } cm.Parent = d d.CensorManager = &cm - if d.CensorThresholds == nil { - d.CensorThresholds = make(map[censor.Level]int) + if d.Config.CensorThresholds == nil { + d.Config.CensorThresholds = make(map[censor.Level]int) } - if d.CensorHandlers == nil { - d.CensorHandlers = make(map[censor.Level]uint8) + if d.Config.CensorHandlers == nil { + d.Config.CensorHandlers = make(map[censor.Level]uint8) } - if d.CensorScores == nil { - d.CensorScores = make(map[censor.Level]int) + if d.Config.CensorScores == nil { + d.Config.CensorScores = make(map[censor.Level]int) } cm.Load(d) } @@ -138,7 +172,7 @@ func (d *Dice) CensorMsg(mctx *MsgContext, msg *Message, checkContent string, se if !ok { d.Logger.Warn("Dice CenSor获取GroupInfo失败") } - thresholds := d.CensorThresholds + thresholds := d.Config.CensorThresholds // 保证按程度依次降低来处理 var tempLevels censor.Levels @@ -156,7 +190,7 @@ func (d *Dice) CensorMsg(mctx *MsgContext, msg *Message, checkContent string, se // 清空此用户该等级计数 model.CensorClearLevelCount(d.CensorManager.DB, msg.Sender.UserID, level) // 该等级敏感词超过阈值,执行操作 - handler := d.CensorHandlers[level] + handler := d.Config.CensorHandlers[level] levelText := censor.LevelText[level] if handler&(1<敏感词", mctx, @@ -196,9 +230,9 @@ func (d *Dice) CensorMsg(mctx *MsgContext, msg *Message, checkContent string, se if handler&(1<敏感词", mctx, @@ -208,9 +242,9 @@ func (d *Dice) CensorMsg(mctx *MsgContext, msg *Message, checkContent string, se if handler&(1<敏感词", mctx, @@ -218,13 +252,13 @@ func (d *Dice) CensorMsg(mctx *MsgContext, msg *Message, checkContent string, se } } if handler&(1<= 0; i-- { idx := idxToDel[i] - d.ExtDefaultSettings = append(d.ExtDefaultSettings[:idx], d.ExtDefaultSettings[idx+1:]...) + d.Config.ExtDefaultSettings = append(d.Config.ExtDefaultSettings[:idx], d.Config.ExtDefaultSettings[idx+1:]...) } panic("DONT USE ME") @@ -1004,7 +1004,7 @@ func (d *Dice) JsParseMeta(s string, installTime time.Time, rawData []byte, buil jsInfo.ErrText = strings.Join(errMsg, "\n") return nil, errors.New(strings.Join(errMsg, "|")) } - jsInfo.Enable = !d.DisabledJsScripts[jsInfo.Name] + jsInfo.Enable = !d.Config.DisabledJsScripts[jsInfo.Name] return jsInfo, nil } @@ -1109,7 +1109,7 @@ func JsDelete(_ *Dice, jsInfo *JsScriptInfo) { } func JsEnable(d *Dice, jsInfoName string) { - delete(d.DisabledJsScripts, jsInfoName) + delete(d.Config.DisabledJsScripts, jsInfoName) for _, jsInfo := range d.JsScriptList { if jsInfo.Name == jsInfoName { jsInfo.Enable = true @@ -1118,7 +1118,7 @@ func JsEnable(d *Dice, jsInfoName string) { } func JsDisable(d *Dice, jsInfoName string) { - d.DisabledJsScripts[jsInfoName] = true + d.Config.DisabledJsScripts[jsInfoName] = true for _, jsInfo := range d.JsScriptList { if jsInfo.Name == jsInfoName { jsInfo.Enable = false diff --git a/dice/dice_manager.go b/dice/dice_manager.go index 2d0a9ad4..6e9cee06 100644 --- a/dice/dice_manager.go +++ b/dice/dice_manager.go @@ -82,8 +82,8 @@ type DiceManager struct { //nolint:revive CleanupFlag atomic.Uint32 // 1 为正在清理,0为普通状态 } -type DiceConfigs struct { //nolint:revive - DiceConfigs []DiceConfig `yaml:"diceConfigs"` +type Configs struct { //nolint:revive + DiceConfigs []BaseConfig `yaml:"diceConfigs"` ServeAddress string `yaml:"serveAddress"` WebUIAddress string `yaml:"webUIAddress"` HelpDocEngineType int `yaml:"helpDocEngineType"` @@ -150,7 +150,7 @@ func (dm *DiceManager) LoadDice() { return } - var dc DiceConfigs + var dc Configs err = yaml.Unmarshal(data, &dc) if err != nil { fmt.Println("读取 data/dice.yaml 发生错误: 配置文件格式不正确") @@ -196,7 +196,7 @@ func (dm *DiceManager) LoadDice() { } func (dm *DiceManager) Save() { - var dc DiceConfigs + var dc Configs dc.ServeAddress = dm.ServeAddress dc.HelpDocEngineType = dm.HelpDocEngineType dc.UIPasswordSalt = dm.UIPasswordSalt @@ -326,8 +326,8 @@ func (dm *DiceManager) TryCreateDefault() { if len(dm.Dice) == 0 { defaultDice := new(Dice) defaultDice.BaseConfig.Name = "default" - defaultDice.MessageDelayRangeStart = 0.4 - defaultDice.MessageDelayRangeEnd = 0.9 + defaultDice.Config.MessageDelayRangeStart = DefaultConfig.MessageDelayRangeStart + defaultDice.Config.MessageDelayRangeEnd = DefaultConfig.MessageDelayRangeEnd defaultDice.MarkModified() defaultDice.ContainerMode = dm.ContainerMode dm.Dice = append(dm.Dice, defaultDice) diff --git a/dice/ext.go b/dice/ext.go index 3aba0a0f..88b45dca 100644 --- a/dice/ext.go +++ b/dice/ext.go @@ -110,7 +110,7 @@ func GetExtensionDesc(ei *ExtInfo) string { func (i *ExtInfo) callWithJsCheck(d *Dice, f func()) { if i.IsJsExt { - if d.JsEnable { + if d.Config.JsEnable { waitRun := make(chan int, 1) d.JsLoop.RunOnLoop(func(vm *goja.Runtime) { defer func() { diff --git a/dice/ext_coc7.go b/dice/ext_coc7.go index 1b833dfe..f96f5b7f 100644 --- a/dice/ext_coc7.go +++ b/dice/ext_coc7.go @@ -471,7 +471,7 @@ func RegisterBuiltinExtCoc7(self *Dice) { var text string if cmdArgs.SpecialExecuteTimes > 1 { VarSetValueInt64(mctx, "$t次数", int64(cmdArgs.SpecialExecuteTimes)) - if cmdArgs.SpecialExecuteTimes > int(ctx.Dice.MaxExecuteTime) { + if cmdArgs.SpecialExecuteTimes > int(ctx.Dice.Config.MaxExecuteTime) { ReplyToSender(mctx, msg, DiceFormatTmpl(mctx, "COC:检定_轮数过多警告")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -1519,8 +1519,8 @@ func RegisterBuiltinExtCoc7(self *Dice) { return CmdExecuteResult{Matched: true, Solved: true, ShowHelp: true} } } - if val > ctx.Dice.MaxCocCardGen { - val = ctx.Dice.MaxCocCardGen + if val > ctx.Dice.Config.MaxCocCardGen { + val = ctx.Dice.Config.MaxCocCardGen } var ss []string diff --git a/dice/ext_deck.go b/dice/ext_deck.go index 7cf8b681..08df60cc 100644 --- a/dice/ext_deck.go +++ b/dice/ext_deck.go @@ -754,7 +754,7 @@ func RegisterBuiltinExtDeck(d *Dice) { // if times > 5 { // times = 5 // } - if times > int(ctx.Dice.MaxExecuteTime) { + if times > int(ctx.Dice.Config.MaxExecuteTime) { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:骰点_轮数过多警告")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -948,7 +948,7 @@ func deckStringFormat(ctx *MsgContext, deckInfo *DeckInfo, s string) (string, er s = ImageRewrite(s, imgSolve) s = strings.ReplaceAll(s, "\n", `\n`) - if ctx.Dice.VMVersionForDeck == "v1" { + if ctx.Dice.Config.VMVersionForDeck == "v1" { return DiceFormatV1(ctx, s) } else { return DiceFormatV2(ctx, s) diff --git a/dice/ext_dnd5e.go b/dice/ext_dnd5e.go index 4dfcb28d..320c63c7 100644 --- a/dice/ext_dnd5e.go +++ b/dice/ext_dnd5e.go @@ -72,7 +72,7 @@ func setupConfigDND(_ *Dice) AttributeConfigs { } func getPlayerNameTempFunc(mctx *MsgContext) string { - if mctx.Dice.PlayerNameWrapEnable { + if mctx.Dice.Config.PlayerNameWrapEnable { return fmt.Sprintf("<%s>", mctx.Player.Name) } return mctx.Player.Name diff --git a/dice/ext_fun.go b/dice/ext_fun.go index f9f14e07..a3566212 100644 --- a/dice/ext_fun.go +++ b/dice/ext_fun.go @@ -436,7 +436,7 @@ func RegisterBuiltinExtFun(self *Dice) { } else if val == "help" || val == "" { return CmdExecuteResult{Matched: true, Solved: true, ShowHelp: true} } else { - if self.MailEnable { + if self.Config.MailEnable { _ = ctx.Dice.SendMail(cmdArgs.CleanArgs, MailTypeSendNote) ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:留言_已记录")) return CmdExecuteResult{Matched: true, Solved: true} @@ -1031,7 +1031,7 @@ func RegisterBuiltinExtFun(self *Dice) { ShortHelp: textHelp, Help: "文本模板指令:\n" + textHelp, Solve: func(ctx *MsgContext, msg *Message, cmdArgs *CmdArgs) CmdExecuteResult { - if ctx.Dice.TextCmdTrustOnly { + if ctx.Dice.Config.TextCmdTrustOnly { // 检查master和信任权限 // 拒绝无权限访问 if ctx.PrivilegeLevel < 70 { @@ -1118,7 +1118,7 @@ func RegisterBuiltinExtFun(self *Dice) { if m == 0 { m = int(getDefaultDicePoints(ctx)) } - if t > int(ctx.Dice.MaxExecuteTime) { + if t > int(ctx.Dice.Config.MaxExecuteTime) { ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:骰点_轮数过多警告")) return CmdExecuteResult{Matched: true, Solved: true} } @@ -1208,7 +1208,7 @@ func RegisterBuiltinExtFun(self *Dice) { } // NOTE(Xiangze Li): 允许创建更多轮数。使用洗牌算法后并不会很重复计算 - // if roulette.Time > int(ctx.Dice.MaxExecuteTime) { + // if roulette.Time > int(ctx.Dice.Config.MaxExecuteTime) { // ReplyToSender(ctx, msg, DiceFormatTmpl(ctx, "核心:骰点_轮数过多警告")) // return CmdExecuteResult{Matched: true, Solved: true} // } diff --git a/dice/ext_log.go b/dice/ext_log.go index 87507393..7dd8faf6 100644 --- a/dice/ext_log.go +++ b/dice/ext_log.go @@ -881,11 +881,11 @@ func LogAppend(ctx *MsgContext, groupID string, logName string, logItem *model.L if ok { if size, okCount := model.LogLinesCountGet(ctx.Dice.DBLogs, groupID, logName); okCount { // 默认每记录500条发出提示 - if ctx.Dice.LogSizeNoticeEnable { - if ctx.Dice.LogSizeNoticeCount == 0 { - ctx.Dice.LogSizeNoticeCount = 500 + if ctx.Dice.Config.LogSizeNoticeEnable { + if ctx.Dice.Config.LogSizeNoticeCount == 0 { + ctx.Dice.Config.LogSizeNoticeCount = DefaultConfig.LogSizeNoticeCount } - if size > 0 && int(size)%ctx.Dice.LogSizeNoticeCount == 0 { + if size > 0 && int(size)%ctx.Dice.Config.LogSizeNoticeCount == 0 { VarSetValueInt64(ctx, "$t条数", size) text := DiceFormatTmpl(ctx, "日志:记录_条数提醒") // text := fmt.Sprintf("提示: 当前故事的文本已经记录了 %d 条", size) diff --git a/dice/ext_reply.go b/dice/ext_reply.go index 816057fb..0fb2ed0e 100644 --- a/dice/ext_reply.go +++ b/dice/ext_reply.go @@ -143,7 +143,7 @@ func RegisterBuiltinExtReply(dice *Dice) { OnNotCommandReceived: func(ctx *MsgContext, msg *Message) { // 当前,只有非指令才会匹配 rcs := ctx.Dice.CustomReplyConfig - if !ctx.Dice.CustomReplyConfigEnable { + if !ctx.Dice.Config.CustomReplyConfigEnable { return } executed := false @@ -153,7 +153,7 @@ func RegisterBuiltinExtReply(dice *Dice) { cleanText = strings.TrimSpace(cleanText) VarSetValueInt64(ctx, "$t文本长度", int64(len(cleanText))) - if dice.ReplyDebugMode { + if dice.Config.ReplyDebugMode { log.Infof("[回复调试]当前文本:“%s” hex: %x 字节形式: %v", cleanText, cleanText, []byte(cleanText)) } diff --git a/dice/ext_reply_logic.go b/dice/ext_reply_logic.go index 3ba4903a..001240e8 100644 --- a/dice/ext_reply_logic.go +++ b/dice/ext_reply_logic.go @@ -148,7 +148,7 @@ func (m *ReplyConditionExprTrue) Check(ctx *MsgContext, _ *Message, _ *CmdArgs, // r := ctx.Eval(m.Value, ds.RollConfig{}) flags := RollExtraFlags{ V2Only: true, - V1Only: ctx.Dice.VMVersionForReply == "v1", + V1Only: ctx.Dice.Config.VMVersionForReply == "v1", } r, _, err := DiceExprEvalBase(ctx, m.Value, flags) @@ -182,7 +182,7 @@ func formatExprForReply(ctx *MsgContext, expr string) string { var text string var err error - if ctx.Dice.VMVersionForReply == "v1" { + if ctx.Dice.Config.VMVersionForReply == "v1" { text, err = DiceFormatV1(ctx, expr) if err != nil { // text = fmt.Sprintf("执行出错V1: %s", err.Error()) @@ -260,7 +260,7 @@ func (m *ReplyResultRunText) Execute(ctx *MsgContext, _ *Message, _ *CmdArgs) { time.Sleep(time.Duration(m.Delay * float64(time.Second))) flags := RollExtraFlags{ V2Only: true, - V1Only: ctx.Dice.VMVersionForReply == "v1", + V1Only: ctx.Dice.Config.VMVersionForReply == "v1", } _, _, _ = DiceExprTextBase(ctx, m.Message, flags) } diff --git a/dice/im_helpers.go b/dice/im_helpers.go index 0c5bf9c2..8fa6e85f 100644 --- a/dice/im_helpers.go +++ b/dice/im_helpers.go @@ -64,9 +64,9 @@ func SetBotOnAtGroup(ctx *MsgContext, groupID string) *GroupInfo { group.Active = true } else { // 设定扩展情况 - sort.Sort(ExtDefaultSettingItemSlice(session.Parent.ExtDefaultSettings)) + sort.Sort(ExtDefaultSettingItemSlice(session.Parent.Config.ExtDefaultSettings)) var extLst []*ExtInfo - for _, i := range session.Parent.ExtDefaultSettings { + for _, i := range session.Parent.Config.ExtDefaultSettings { if i.ExtItem != nil { if i.AutoActive { extLst = append(extLst, i.ExtItem) @@ -81,7 +81,7 @@ func SetBotOnAtGroup(ctx *MsgContext, groupID string) *GroupInfo { GroupID: groupID, DiceIDActiveMap: new(SyncMap[string, bool]), DiceIDExistsMap: new(SyncMap[string, bool]), - CocRuleIndex: int(session.Parent.DefaultCocRuleIndex), + CocRuleIndex: int(session.Parent.Config.DefaultCocRuleIndex), UpdatedAtTime: time.Now().Unix(), }) // TODO: Pinenutn:总觉得这里不太对,但是又觉得合理,GPT也没说怎么改更好一些,求教 @@ -181,7 +181,7 @@ func ReplyGroupRaw(ctx *MsgContext, msg *Message, text string, flag string) { ctx.DelegateText = "" } - if ctx.Dice.RateLimitEnabled && msg.Platform == "QQ" { + if ctx.Dice.Config.RateLimitEnabled && msg.Platform == "QQ" { if !spamCheckPerson(ctx, msg) { spamCheckGroup(ctx, msg) } @@ -191,7 +191,7 @@ func ReplyGroupRaw(ctx *MsgContext, msg *Message, text string, flag string) { if d != nil { d.Logger.Infof("发给(群%s): %s", msg.GroupID, text) // 敏感词拦截:回复(群) - if d.EnableCensor && d.CensorMode == OnlyOutputReply { + if d.Config.EnableCensor && d.Config.CensorMode == OnlyOutputReply { // 先拿掉海豹码和CQ码再检查敏感词 checkText := sealCodeRe.ReplaceAllString(text, "") checkText = cqCodeRe.ReplaceAllString(checkText, "") @@ -256,7 +256,7 @@ func ReplyPersonRaw(ctx *MsgContext, msg *Message, text string, flag string) { ctx.DelegateText = "" } - if ctx.Dice.RateLimitEnabled && msg.Platform == "QQ" { + if ctx.Dice.Config.RateLimitEnabled && msg.Platform == "QQ" { spamCheckPerson(ctx, msg) } @@ -264,7 +264,7 @@ func ReplyPersonRaw(ctx *MsgContext, msg *Message, text string, flag string) { if d != nil { d.Logger.Infof("发给(帐号%s): %s", msg.Sender.UserID, text) // 敏感词拦截:回复(个人) - if d.EnableCensor && d.CensorMode == OnlyOutputReply { + if d.Config.EnableCensor && d.Config.CensorMode == OnlyOutputReply { // 先拿掉海豹码和CQ码再检查敏感词 checkText := sealCodeRe.ReplaceAllString(text, "") checkText = cqCodeRe.ReplaceAllString(checkText, "") @@ -449,16 +449,16 @@ func spamCheckPerson(ctx *MsgContext, msg *Message) bool { if ctx.Player.RateLimiter == nil { ctx.Player.RateLimitWarned = false - if ctx.Dice.PersonalReplenishRateStr == "" { - ctx.Dice.PersonalReplenishRateStr = "@every 3s" - ctx.Dice.PersonalReplenishRate = rate.Every(time.Second * 3) + if ctx.Dice.Config.PersonalReplenishRateStr == "" { + ctx.Dice.Config.PersonalReplenishRateStr = DefaultConfig.PersonalReplenishRateStr + ctx.Dice.Config.PersonalReplenishRate = DefaultConfig.PersonalReplenishRate } - if ctx.Dice.PersonalBurst == 0 { - ctx.Dice.PersonalBurst = 3 + if ctx.Dice.Config.PersonalBurst == 0 { + ctx.Dice.Config.PersonalBurst = DefaultConfig.PersonalBurst } ctx.Player.RateLimiter = rate.NewLimiter( - ctx.Dice.PersonalReplenishRate, - int(ctx.Dice.PersonalBurst), + ctx.Dice.Config.PersonalReplenishRate, + int(ctx.Dice.Config.PersonalBurst), ) } @@ -468,7 +468,7 @@ func spamCheckPerson(ctx *MsgContext, msg *Message) bool { } if ctx.Player.RateLimitWarned { - ctx.Dice.BanList.AddScoreByCommandSpam(ctx.Player.UserID, msg.GroupID, ctx) + ctx.Dice.Config.BanList.AddScoreByCommandSpam(ctx.Player.UserID, msg.GroupID, ctx) } else { ctx.Player.RateLimitWarned = true replyToSenderRawNoCheck( @@ -500,16 +500,16 @@ func spamCheckGroup(ctx *MsgContext, msg *Message) bool { if ctx.Group.RateLimiter == nil { ctx.Group.RateLimitWarned = false - if ctx.Dice.GroupReplenishRateStr == "" { - ctx.Dice.GroupReplenishRateStr = "@every 3s" - ctx.Dice.GroupReplenishRate = rate.Every(time.Second * 3) + if ctx.Dice.Config.GroupReplenishRateStr == "" { + ctx.Dice.Config.GroupReplenishRateStr = DefaultConfig.GroupReplenishRateStr + ctx.Dice.Config.GroupReplenishRate = DefaultConfig.GroupReplenishRate } - if ctx.Dice.GroupBurst == 0 { - ctx.Dice.GroupBurst = 3 + if ctx.Dice.Config.GroupBurst == 0 { + ctx.Dice.Config.GroupBurst = DefaultConfig.GroupBurst } ctx.Group.RateLimiter = rate.NewLimiter( - ctx.Dice.GroupReplenishRate, - int(ctx.Dice.GroupBurst), + ctx.Dice.Config.GroupReplenishRate, + int(ctx.Dice.Config.GroupBurst), ) } @@ -520,7 +520,7 @@ func spamCheckGroup(ctx *MsgContext, msg *Message) bool { // If not allow if ctx.Group.RateLimitWarned { - ctx.Dice.BanList.AddScoreByCommandSpam(ctx.Group.GroupID, msg.GroupID, ctx) + ctx.Dice.Config.BanList.AddScoreByCommandSpam(ctx.Group.GroupID, msg.GroupID, ctx) } else { ctx.Group.RateLimitWarned = true replyToSenderRawNoCheck( diff --git a/dice/im_session.go b/dice/im_session.go index 14197174..8285245b 100644 --- a/dice/im_session.go +++ b/dice/im_session.go @@ -521,7 +521,7 @@ func (ctx *MsgContext) fillPrivilege(msg *Message) int { } // 加入黑名单相关权限 - if val, exists := ctx.Dice.BanList.GetByID(ctx.Player.UserID); exists { + if val, exists := ctx.Dice.Config.BanList.GetByID(ctx.Player.UserID); exists { switch val.Rank { case BanRankBanned: ctx.PrivilegeLevel = -30 @@ -562,7 +562,7 @@ func (s *IMSession) Execute(ep *EndPointInfo, msg *Message, runInSync bool) { // 注意: 此处必须开启,不然下面mctx.player取不到 autoOn := true if msg.Platform == "QQ-CH" { - autoOn = d.QQChannelAutoOn + autoOn = d.Config.QQChannelAutoOn } groupInfo = SetBotOnAtGroup(mctx, msg.GroupID) groupInfo.Active = autoOn @@ -710,13 +710,13 @@ func (s *IMSession) Execute(ep *EndPointInfo, msg *Message, runInSync bool) { log.Infof("收到群(%s)内<%s>(%s)的指令: %s", msg.GroupID, msg.Sender.Nickname, msg.Sender.UserID, msg.Message) } else { doLog := true - if d.OnlyLogCommandInGroup { + if d.Config.OnlyLogCommandInGroup { // 检查上级选项 doLog = false } if doLog { // 检查QQ频道的独立选项 - if msg.Platform == "QQ-CH" && (!d.QQChannelLogMessage) { + if msg.Platform == "QQ-CH" && (!d.Config.QQChannelLogMessage) { doLog = false } } @@ -728,7 +728,7 @@ func (s *IMSession) Execute(ep *EndPointInfo, msg *Message, runInSync bool) { } // 敏感词拦截:全部输入 - if mctx.IsCurGroupBotOn && d.EnableCensor && d.CensorMode == AllInput { + if mctx.IsCurGroupBotOn && d.Config.EnableCensor && d.Config.CensorMode == AllInput { hit, words, needToTerminate, _ := d.CensorMsg(mctx, msg, msg.Message, "") if needToTerminate { return @@ -760,7 +760,7 @@ func (s *IMSession) Execute(ep *EndPointInfo, msg *Message, runInSync bool) { if msg.MessageType == "private" { if mctx.CommandID != 0 { log.Infof("收到<%s>(%s)的私聊指令: %s", msg.Sender.Nickname, msg.Sender.UserID, msg.Message) - } else if !d.OnlyLogCommandInPrivate { + } else if !d.Config.OnlyLogCommandInPrivate { log.Infof("收到<%s>(%s)的私聊消息: %s", msg.Sender.Nickname, msg.Sender.UserID, msg.Message) } } @@ -778,7 +778,7 @@ func (s *IMSession) Execute(ep *EndPointInfo, msg *Message, runInSync bool) { }() // 敏感词拦截:命令输入 - if (msg.MessageType == "private" || mctx.IsCurGroupBotOn) && d.EnableCensor && d.CensorMode == OnlyInputCommand { + if (msg.MessageType == "private" || mctx.IsCurGroupBotOn) && d.Config.EnableCensor && d.Config.CensorMode == OnlyInputCommand { hit, words, needToTerminate, _ := d.CensorMsg(mctx, msg, msg.Message, "") if needToTerminate { return @@ -925,7 +925,7 @@ func (s *IMSession) ExecuteNew(ep *EndPointInfo, msg *Message) { // 注意: 此处必须开启,不然下面mctx.player取不到 autoOn := true if msg.Platform == "QQ-CH" { - autoOn = d.QQChannelAutoOn + autoOn = d.Config.QQChannelAutoOn } groupInfo = SetBotOnAtGroup(mctx, msg.GroupID) groupInfo.Active = autoOn @@ -1047,13 +1047,13 @@ func (s *IMSession) ExecuteNew(ep *EndPointInfo, msg *Message) { log.Infof("收到群(%s)内<%s>(%s)的指令: %s", msg.GroupID, msg.Sender.Nickname, msg.Sender.UserID, msg.Message) } else { doLog := true - if d.OnlyLogCommandInGroup { + if d.Config.OnlyLogCommandInGroup { // 检查上级选项 doLog = false } if doLog { // 检查QQ频道的独立选项 - if msg.Platform == "QQ-CH" && (!d.QQChannelLogMessage) { + if msg.Platform == "QQ-CH" && (!d.Config.QQChannelLogMessage) { doLog = false } } @@ -1069,13 +1069,13 @@ func (s *IMSession) ExecuteNew(ep *EndPointInfo, msg *Message) { // TODO(Szzrain): 需要优化的写法,不应根据 CommandID 来判断是否是指令,而应该根据 cmdArgs 是否 match 到指令来判断,同上 if mctx.CommandID != 0 { log.Infof("收到<%s>(%s)的私聊指令: %s", msg.Sender.Nickname, msg.Sender.UserID, msg.Message) - } else if !d.OnlyLogCommandInPrivate { + } else if !d.Config.OnlyLogCommandInPrivate { log.Infof("收到<%s>(%s)的私聊消息: %s", msg.Sender.Nickname, msg.Sender.UserID, msg.Message) } } // 敏感词拦截:全部输入 - if mctx.IsCurGroupBotOn && d.EnableCensor && d.CensorMode == AllInput { + if mctx.IsCurGroupBotOn && d.Config.EnableCensor && d.Config.CensorMode == AllInput { hit, words, needToTerminate, _ := d.CensorMsg(mctx, msg, msg.Message, "") if needToTerminate { return @@ -1167,7 +1167,7 @@ func (s *IMSession) PreTriggerCommand(mctx *MsgContext, msg *Message, cmdArgs *C }() // 敏感词拦截:命令输入 - if (msg.MessageType == "private" || mctx.IsCurGroupBotOn) && d.EnableCensor && d.CensorMode == OnlyInputCommand { + if (msg.MessageType == "private" || mctx.IsCurGroupBotOn) && d.Config.EnableCensor && d.Config.CensorMode == OnlyInputCommand { hit, words, needToTerminate, _ := d.CensorMsg(mctx, msg, msg.Message, "") if needToTerminate { return @@ -1398,8 +1398,8 @@ func (s *IMSession) LongTimeQuitInactiveGroup(threshold, hint time.Time, roundIn if strings.HasPrefix(grp.GroupID, "PG-") { return true } - if s.Parent.BanList != nil { - info, ok := s.Parent.BanList.GetByID(grp.GroupID) + if s.Parent.Config.BanList != nil { + info, ok := s.Parent.Config.BanList.GetByID(grp.GroupID) if ok && info.Rank > BanRankNormal { return true // 信任等级高于普通的不清理 } @@ -1494,7 +1494,7 @@ func checkBan(ctx *MsgContext, msg *Message) (notReply bool) { var isBanGroup, isWhiteGroup bool // log.Info("check ban ", msg.MessageType, " ", msg.GroupID, " ", ctx.PrivilegeLevel) if msg.MessageType == "group" { - value, exists := d.BanList.GetByID(msg.GroupID) + value, exists := d.Config.BanList.GetByID(msg.GroupID) if exists { if value.Rank == BanRankBanned { isBanGroup = true @@ -1506,7 +1506,7 @@ func checkBan(ctx *MsgContext, msg *Message) (notReply bool) { } banQuitGroup := func() { - banListInfoItem, _ := ctx.Dice.BanList.Map.Load(msg.Sender.UserID) + banListInfoItem, _ := ctx.Dice.Config.BanList.Map.Load(msg.Sender.UserID) reasontext := FormatBlacklistReasons(banListInfoItem) groupID := msg.GroupID noticeMsg := fmt.Sprintf("检测到群(%s)内黑名单用户<%s>(%s),自动退群\n%s", groupID, msg.Sender.Nickname, msg.Sender.UserID, reasontext) @@ -1523,9 +1523,9 @@ func checkBan(ctx *MsgContext, msg *Message) (notReply bool) { if ctx.PrivilegeLevel == -30 { groupLevel := ctx.GroupRoleLevel - if d.BanList.BanBehaviorQuitIfAdmin && msg.MessageType == "group" { + if d.Config.BanList.BanBehaviorQuitIfAdmin && msg.MessageType == "group" { // 黑名单用户 - 立即退出所在群 - banListInfoItem, _ := ctx.Dice.BanList.Map.Load(msg.Sender.UserID) + banListInfoItem, _ := ctx.Dice.Config.BanList.Map.Load(msg.Sender.UserID) reasontext := FormatBlacklistReasons(banListInfoItem) groupID := msg.GroupID notReply = true @@ -1555,7 +1555,7 @@ func checkBan(ctx *MsgContext, msg *Message) (notReply bool) { ctx.Notice(noticeMsg) } } - } else if d.BanList.BanBehaviorQuitPlaceImmediately && msg.MessageType == "group" { + } else if d.Config.BanList.BanBehaviorQuitPlaceImmediately && msg.MessageType == "group" { notReply = true // 黑名单用户 - 立即退出所在群 groupID := msg.GroupID @@ -1564,16 +1564,16 @@ func checkBan(ctx *MsgContext, msg *Message) (notReply bool) { } else { banQuitGroup() } - } else if d.BanList.BanBehaviorRefuseReply { + } else if d.Config.BanList.BanBehaviorRefuseReply { notReply = true // 黑名单用户 - 拒绝回复 log.Infof("忽略黑名单用户信息: 来自群(%s)内<%s>(%s): %s", msg.GroupID, msg.Sender.Nickname, msg.Sender.UserID, msg.Message) } } else if isBanGroup { - if d.BanList.BanBehaviorQuitPlaceImmediately && !isWhiteGroup { + if d.Config.BanList.BanBehaviorQuitPlaceImmediately && !isWhiteGroup { notReply = true // 黑名单群 - 立即退出 - banListInfoItem, _ := ctx.Dice.BanList.Map.Load(msg.Sender.UserID) + banListInfoItem, _ := ctx.Dice.Config.BanList.Map.Load(msg.Sender.UserID) reasontext := FormatBlacklistReasons(banListInfoItem) groupID := msg.GroupID if isWhiteGroup { @@ -1589,7 +1589,7 @@ func checkBan(ctx *MsgContext, msg *Message) (notReply bool) { time.Sleep(1 * time.Second) ctx.EndPoint.Adapter.QuitGroup(ctx, groupID) } - } else if d.BanList.BanBehaviorRefuseReply { + } else if d.Config.BanList.BanBehaviorRefuseReply { notReply = true // 黑名单群 - 拒绝回复 log.Infof("忽略黑名单群消息: 来自群(%s)内<%s>(%s): %s", msg.GroupID, msg.Sender.Nickname, msg.Sender.UserID, msg.Message) @@ -1668,7 +1668,7 @@ func (s *IMSession) commandSolve(ctx *MsgContext, msg *Message, cmdArgs *CmdArgs } if cur != -1 { - if ctx.Dice.PlayerNameWrapEnable { + if ctx.Dice.Config.PlayerNameWrapEnable { ctx.DelegateText = fmt.Sprintf("由<%s>代骰:\n", ctx.Player.Name) } else { ctx.DelegateText = fmt.Sprintf("由%s代骰:\n", ctx.Player.Name) @@ -1958,13 +1958,13 @@ func (d *Dice) NoticeForEveryEndpoint(txt string, allowCrossPlatform bool) { } }() - if d.MailEnable { + if d.Config.MailEnable { _ = d.SendMail(txt, MailTypeNotice) return } for _, ep := range d.ImSession.EndPoints { - for _, i := range d.NoticeIDs { + for _, i := range d.Config.NoticeIDs { n := strings.Split(i, ":") // 如果文本中没有-,则会取到整个字符串 // 但好像不严谨,比如QQ-CH-Group @@ -2001,14 +2001,14 @@ func (ctx *MsgContext) NoticeCrossPlatform(txt string) { } }() - if ctx.Dice.MailEnable { + if ctx.Dice.Config.MailEnable { _ = ctx.Dice.SendMail(txt, MailTypeNotice) return } sent := false - for _, i := range ctx.Dice.NoticeIDs { + for _, i := range ctx.Dice.Config.NoticeIDs { n := strings.Split(i, ":") if len(n) < 2 { continue @@ -2059,14 +2059,14 @@ func (ctx *MsgContext) Notice(txt string) { } }() - if ctx.Dice.MailEnable { + if ctx.Dice.Config.MailEnable { _ = ctx.Dice.SendMail(txt, MailTypeNotice) return } sent := false if ctx.EndPoint.Enable { - for _, i := range ctx.Dice.NoticeIDs { + for _, i := range ctx.Dice.Config.NoticeIDs { n := strings.Split(i, ":") if len(n) >= 2 { if strings.HasSuffix(n[0], "-Group") { diff --git a/dice/im_vars.go b/dice/im_vars.go index 23cc6087..6403b9a9 100644 --- a/dice/im_vars.go +++ b/dice/im_vars.go @@ -222,7 +222,7 @@ func SetTempVars(ctx *MsgContext, qqNickname string) { pcName = strings.ReplaceAll(pcName, `\f`, "") VarSetValueStr(ctx, "$t玩家", fmt.Sprintf("<%s>", pcName)) - if ctx.Dice != nil && !ctx.Dice.PlayerNameWrapEnable { + if ctx.Dice != nil && !ctx.Dice.Config.PlayerNameWrapEnable { VarSetValueStr(ctx, "$t玩家", pcName) } VarSetValueStr(ctx, "$t玩家_RAW", pcName) diff --git a/dice/platform_adapter_gocq.go b/dice/platform_adapter_gocq.go index b7ac4664..0176740f 100644 --- a/dice/platform_adapter_gocq.go +++ b/dice/platform_adapter_gocq.go @@ -15,10 +15,7 @@ import ( "syscall" "time" - "github.com/gorilla/websocket" "github.com/labstack/echo/v4" - "github.com/sacOO7/gowebsocket" - "github.com/samber/lo" "github.com/tidwall/gjson" "github.com/tidwall/sjson" "gopkg.in/yaml.v3" @@ -26,6 +23,10 @@ import ( "sealdice-core/message" log "sealdice-core/utils/kratos" "sealdice-core/utils/procs" + + "github.com/gorilla/websocket" + "github.com/sacOO7/gowebsocket" + "github.com/samber/lo" ) // 0 默认 1登录中 2登录中-二维码 3登录中-滑条 4登录中-手机验证码 10登录成功 11登录失败 @@ -461,9 +462,9 @@ func (pa *PlatformAdapterGocq) Serve() int { // log.Info("...", message) // } if strings.Contains(message, `"guild_id"`) { - // log.Info("!!!", message, s.Parent.WorkInQQChannel) + // log.Info("!!!", message, s.Parent.Config.WorkInQQChannel) // 暂时忽略频道消息 - if s.Parent.WorkInQQChannel { + if s.Parent.Config.WorkInQQChannel { pa.QQChannelTrySolve(message) } return @@ -561,9 +562,9 @@ func (pa *PlatformAdapterGocq) Serve() int { // 处理被强制拉群的情况 uid := groupInfo.InviteUserID - banInfo, ok := ctx.Dice.BanList.GetByID(uid) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && ctx.Dice.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && ctx.Dice.Config.BanList.BanBehaviorRefuseInvite { // 如果是被ban之后拉群,判定为强制拉群 if groupInfo.EnteredTime > 0 && groupInfo.EnteredTime > banInfo.BanTime { text := fmt.Sprintf("本次入群为遭遇强制邀请,即将主动退群,因为邀请人%s正处于黑名单上。打扰各位还请见谅。感谢使用海豹核心。", groupInfo.InviteUserID) @@ -576,7 +577,7 @@ func (pa *PlatformAdapterGocq) Serve() int { } // 强制拉群情况2 - 群在黑名单 - banInfo, ok = ctx.Dice.BanList.GetByID(groupID) + banInfo, ok = ctx.Dice.Config.BanList.GetByID(groupID) if ok { if banInfo.Rank == BanRankBanned { // 如果是被ban之后拉群,判定为强制拉群 @@ -625,9 +626,9 @@ func (pa *PlatformAdapterGocq) Serve() int { tempInviteMap2[msg.GroupID] = uid // 邀请人在黑名单上 - banInfo, ok := ctx.Dice.BanList.GetByID(uid) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && ctx.Dice.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && ctx.Dice.Config.BanList.BanBehaviorRefuseInvite { pa.SetGroupAddRequest(msgQQ.Flag, msgQQ.SubType, false, "黑名单") return } @@ -635,13 +636,13 @@ func (pa *PlatformAdapterGocq) Serve() int { // 信任模式,如果不是信任,又不是master则拒绝拉群邀请 isMaster := ctx.Dice.IsMaster(uid) - if ctx.Dice.TrustOnlyMode && ((banInfo != nil && banInfo.Rank != BanRankTrusted) && !isMaster) { + if ctx.Dice.Config.TrustOnlyMode && ((banInfo != nil && banInfo.Rank != BanRankTrusted) && !isMaster) { pa.SetGroupAddRequest(msgQQ.Flag, msgQQ.SubType, false, "只允许骰主设置信任的人拉群") return } // 群在黑名单上 - banInfo, ok = ctx.Dice.BanList.GetByID(msg.GroupID) + banInfo, ok = ctx.Dice.Config.BanList.GetByID(msg.GroupID) if ok { if banInfo.Rank == BanRankBanned { pa.SetGroupAddRequest(msgQQ.Flag, msgQQ.SubType, false, "群黑名单") @@ -649,7 +650,7 @@ func (pa *PlatformAdapterGocq) Serve() int { } } - if ctx.Dice.RefuseGroupInvite { + if ctx.Dice.Config.RefuseGroupInvite { pa.SetGroupAddRequest(msgQQ.Flag, msgQQ.SubType, false, "设置拒绝加群") return } @@ -677,7 +678,7 @@ func (pa *PlatformAdapterGocq) Serve() int { comment = strings.ReplaceAll(comment, "\u00a0", "") } - toMatch := strings.TrimSpace(session.Parent.FriendAddComment) + toMatch := strings.TrimSpace(session.Parent.Config.FriendAddComment) willAccept := comment == DiceFormat(ctx, toMatch) if toMatch == "" { willAccept = true @@ -717,9 +718,9 @@ func (pa *PlatformAdapterGocq) Serve() int { // 检查黑名单 extra := "" uid := FormatDiceIDQQ(string(msgQQ.UserID)) - banInfo, ok := ctx.Dice.BanList.GetByID(uid) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && ctx.Dice.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && ctx.Dice.Config.BanList.BanBehaviorRefuseInvite { if willAccept { extra = "。回答正确,但为被禁止用户,准备自动拒绝" } else { @@ -956,7 +957,7 @@ func (pa *PlatformAdapterGocq) Serve() int { skip := false skipReason := "" - banInfo, ok := ctx.Dice.BanList.GetByID(opUID) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(opUID) if ok { if banInfo.Rank == 30 { skip = true @@ -972,7 +973,7 @@ func (pa *PlatformAdapterGocq) Serve() int { if skip { extra = fmt.Sprintf("\n取消处罚,原因为%s", skipReason) } else { - ctx.Dice.BanList.AddScoreByGroupKicked(opUID, msg.GroupID, ctx) + ctx.Dice.Config.BanList.AddScoreByGroupKicked(opUID, msg.GroupID, ctx) } txt := fmt.Sprintf("被踢出群: 在QQ群组<%s>(%s)中被踢出,操作者:<%s>(%s)%s", groupName, msgQQ.GroupID, userName, msgQQ.OperatorID, extra) @@ -1003,7 +1004,7 @@ func (pa *PlatformAdapterGocq) Serve() int { groupName := dm.TryGetGroupName(msg.GroupID) userName := dm.TryGetUserName(opUID) - ctx.Dice.BanList.AddScoreByGroupMuted(opUID, msg.GroupID, ctx) + ctx.Dice.Config.BanList.AddScoreByGroupMuted(opUID, msg.GroupID, ctx) txt := fmt.Sprintf("被禁言: 在群组<%s>(%s)中被禁言,时长%d秒,操作者:<%s>(%s)", groupName, msgQQ.GroupID, msgQQ.Duration, userName, msgQQ.OperatorID) log.Info(txt) ctx.Notice(txt) @@ -1034,7 +1035,7 @@ func (pa *PlatformAdapterGocq) Serve() int { // {"post_type":"notice","notice_type":"notify","time":1672489767,"self_id":2589922907,"sub_type":"poke","group_id":131687852,"user_id":303451945,"sender_id":303451945,"target_id":2589922907} // 检查设置中是否开启 - if !ctx.Dice.QQEnablePoke { + if !ctx.Dice.Config.QQEnablePoke { return } diff --git a/dice/platform_adapter_gocq_actions.go b/dice/platform_adapter_gocq_actions.go index 0963a629..78d6b819 100644 --- a/dice/platform_adapter_gocq_actions.go +++ b/dice/platform_adapter_gocq_actions.go @@ -159,8 +159,8 @@ func socketSendBinary(socket *gowebsocket.Socket, data []byte) { //nolint func doSleepQQ(ctx *MsgContext) { if ctx.Dice != nil { d := ctx.Dice - offset := d.MessageDelayRangeEnd - d.MessageDelayRangeStart - time.Sleep(time.Duration((d.MessageDelayRangeStart + rand.Float64()*offset) * float64(time.Second))) + offset := d.Config.MessageDelayRangeEnd - d.Config.MessageDelayRangeStart + time.Sleep(time.Duration((d.Config.MessageDelayRangeStart + rand.Float64()*offset) * float64(time.Second))) } else { time.Sleep(time.Duration((0.4 + rand.Float64()/2) * float64(time.Second))) } diff --git a/dice/platform_adapter_satori.go b/dice/platform_adapter_satori.go index f88fce91..770d8e52 100644 --- a/dice/platform_adapter_satori.go +++ b/dice/platform_adapter_satori.go @@ -810,21 +810,21 @@ func (pa *PlatformAdapterSatori) guildRequestHandle(e *SatoriEvent) { eid := e.ID.String() // 邀请人在黑名单上 - banInfo, ok := d.BanList.GetByID(uid) + banInfo, ok := d.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && d.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && d.Config.BanList.BanBehaviorRefuseInvite { pa.sendGuildRequestResult(eid, false, "黑名单") return } } // 信任模式,如果不是信任,又不是 master 则拒绝拉群邀请 isMaster := d.IsMaster(uid) - if d.TrustOnlyMode && ((banInfo != nil && banInfo.Rank != BanRankTrusted) && !isMaster) { + if d.Config.TrustOnlyMode && ((banInfo != nil && banInfo.Rank != BanRankTrusted) && !isMaster) { pa.sendGuildRequestResult(eid, false, "只允许骰主设置信任的人拉群") return } // 群在黑名单上 - banInfo, ok = d.BanList.GetByID(guildID) + banInfo, ok = d.Config.BanList.GetByID(guildID) if ok { if banInfo.Rank == BanRankBanned { pa.sendGuildRequestResult(eid, false, "群黑名单") @@ -832,7 +832,7 @@ func (pa *PlatformAdapterSatori) guildRequestHandle(e *SatoriEvent) { } } // 拒绝加群 - if d.RefuseGroupInvite { + if d.Config.RefuseGroupInvite { pa.sendGuildRequestResult(eid, false, "设置拒绝加群") return } @@ -871,15 +871,15 @@ func (pa *PlatformAdapterSatori) friendRequestHandle(e *SatoriEvent) { eid := e.ID.String() // 申请人在黑名单上 - banInfo, ok := d.BanList.GetByID(uid) + banInfo, ok := d.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && d.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && d.Config.BanList.BanBehaviorRefuseInvite { pa.sendGuildRequestResult(eid, false, "为被禁止用户,准备自动拒绝") return } } - if strings.TrimSpace(d.FriendAddComment) == "" { + if strings.TrimSpace(d.Config.FriendAddComment) == "" { pa.sendFriendRequestResult(eid, true, "") } else { pa.sendFriendRequestResult(eid, false, "存在好友问题校验,准备自动拒绝,请联系骰主") diff --git a/dice/platform_adapter_walleq.go b/dice/platform_adapter_walleq.go index 47d0a126..1cf7c5aa 100644 --- a/dice/platform_adapter_walleq.go +++ b/dice/platform_adapter_walleq.go @@ -404,7 +404,7 @@ func (pa *PlatformAdapterWalleQ) Serve() int { if event.UserID == event.Self.UserID { skip := false skipReason := "" - banInfo, ok := ctx.Dice.BanList.GetByID(opUID) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(opUID) if ok { if banInfo.Rank == 30 { skip = true @@ -420,7 +420,7 @@ func (pa *PlatformAdapterWalleQ) Serve() int { if skip { extra = fmt.Sprintf("\n取消处罚,原因为%s", skipReason) } else { - ctx.Dice.BanList.AddScoreByGroupKicked(opUID, msg.GroupID, ctx) + ctx.Dice.Config.BanList.AddScoreByGroupKicked(opUID, msg.GroupID, ctx) } txt := fmt.Sprintf("被踢出群: 在QQ群组<%s>(%s)中被踢出,操作者:<%s>(%s)%s", groupName, event.GroupID, userName, n.OperatorID, extra) @@ -429,7 +429,7 @@ func (pa *PlatformAdapterWalleQ) Serve() int { } case "group_member_ban": // 被禁言 if event.UserID == event.Self.UserID { - ctx.Dice.BanList.AddScoreByGroupMuted(opUID, msg.GroupID, ctx) + ctx.Dice.Config.BanList.AddScoreByGroupMuted(opUID, msg.GroupID, ctx) txt := fmt.Sprintf("被禁言: 在群组<%s>(%s)中被禁言,时长%d秒,操作者:<%s>(%s)", groupName, msg.GroupID, n.Duration, userName, n.OperatorID) log.Info(txt) ctx.Notice(txt) @@ -470,7 +470,7 @@ func (pa *PlatformAdapterWalleQ) Serve() int { comment = strings.ReplaceAll(comment, "\u00a0", "") } - toMatch := strings.TrimSpace(s.Parent.FriendAddComment) + toMatch := strings.TrimSpace(s.Parent.Config.FriendAddComment) willAccept := comment == DiceFormat(ctx, toMatch) if toMatch == "" { willAccept = true @@ -510,9 +510,9 @@ func (pa *PlatformAdapterWalleQ) Serve() int { // 检查黑名单 extra := "" uid := msg.Sender.UserID - banInfo, ok := ctx.Dice.BanList.GetByID(uid) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && ctx.Dice.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && ctx.Dice.Config.BanList.BanBehaviorRefuseInvite { if willAccept { extra = "。回答正确,但为被禁止用户,准备自动拒绝" } else { @@ -564,21 +564,21 @@ func (pa *PlatformAdapterWalleQ) Serve() int { // tempInviteMap2[msg.GroupId] = uid // 邀请人在黑名单上 - banInfo, ok := ctx.Dice.BanList.GetByID(uid) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && ctx.Dice.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && ctx.Dice.Config.BanList.BanBehaviorRefuseInvite { pa.SetGroupAddRequest(req.RequestID, event.GroupID, false) return } } // 信任模式,如果不是信任,又不是master则拒绝拉群邀请 isMaster := ctx.Dice.IsMaster(uid) - if ctx.Dice.TrustOnlyMode && ((banInfo != nil && banInfo.Rank != BanRankTrusted) && !isMaster) { + if ctx.Dice.Config.TrustOnlyMode && ((banInfo != nil && banInfo.Rank != BanRankTrusted) && !isMaster) { pa.SetGroupAddRequest(req.RequestID, event.GroupID, false) return } // 群在黑名单上 - banInfo, ok = ctx.Dice.BanList.GetByID(gid) + banInfo, ok = ctx.Dice.Config.BanList.GetByID(gid) if ok { if banInfo.Rank == BanRankBanned { pa.SetGroupAddRequest(req.RequestID, event.GroupID, false) @@ -586,7 +586,7 @@ func (pa *PlatformAdapterWalleQ) Serve() int { } } // 拒绝加入新群 - if ctx.Dice.RefuseGroupInvite { + if ctx.Dice.Config.RefuseGroupInvite { pa.SetGroupAddRequest(req.RequestID, event.GroupID, false) return } @@ -643,9 +643,9 @@ func (pa *PlatformAdapterWalleQ) Serve() int { // 处理被强制拉群的情况 uid := groupInfo.InviteUserID - banInfo, ok := ctx.Dice.BanList.GetByID(uid) + banInfo, ok := ctx.Dice.Config.BanList.GetByID(uid) if ok { - if banInfo.Rank == BanRankBanned && ctx.Dice.BanList.BanBehaviorRefuseInvite { + if banInfo.Rank == BanRankBanned && ctx.Dice.Config.BanList.BanBehaviorRefuseInvite { // 如果是被ban之后拉群,判定为强制拉群 if groupInfo.EnteredTime > 0 && groupInfo.EnteredTime > banInfo.BanTime { text := fmt.Sprintf("本次入群为遭遇强制邀请,即将主动退群,因为邀请人%s正处于黑名单上。打扰各位还请见谅。感谢使用海豹核心。", groupInfo.InviteUserID) @@ -658,7 +658,7 @@ func (pa *PlatformAdapterWalleQ) Serve() int { } // 强制拉群情况2 - 群在黑名单 - banInfo, ok = ctx.Dice.BanList.GetByID(groupID) + banInfo, ok = ctx.Dice.Config.BanList.GetByID(groupID) if ok { if banInfo.Rank == BanRankBanned { // 如果是被ban之后拉群,判定为强制拉群 diff --git a/dice/utils_email.go b/dice/utils_email.go index de09340f..782e4f92 100644 --- a/dice/utils_email.go +++ b/dice/utils_email.go @@ -24,7 +24,7 @@ const ( ) func (d *Dice) CanSendMail() bool { - if d.MailFrom == "" || d.MailPassword == "" || d.MailSMTP == "" { + if d.Config.MailFrom == "" || d.Config.MailPassword == "" || d.Config.MailSMTP == "" { return false } return true @@ -48,7 +48,7 @@ func (d *Dice) SendMail(body string, m MailCode) error { sub += "Test 测试邮件" } var to []string - for _, id := range d.NoticeIDs { + for _, id := range d.Config.NoticeIDs { if strings.HasPrefix(id, "QQ:") { to = append(to, id[3:]+"@qq.com") } @@ -71,7 +71,7 @@ func (d *Dice) SendMailRow(subject string, to []string, content string, attachme } } m.SetHeader("Subject", fmt.Sprintf("[%s] %s", diceName, subject)) - m.SetHeader("From", d.MailFrom) + m.SetHeader("From", d.Config.MailFrom) m.SetHeader("To", to...) if content == "" { m.SetBody("text/plain", "***自动邮件,无需回复***") @@ -84,7 +84,7 @@ func (d *Dice) SendMailRow(subject string, to []string, content string, attachme } } - dialer := gomail.NewDialer(d.MailSMTP, 25, d.MailFrom, d.MailPassword) + dialer := gomail.NewDialer(d.Config.MailSMTP, 25, d.Config.MailFrom, d.Config.MailPassword) if err := dialer.DialAndSend(m); err != nil { d.Logger.Error(err) } else { diff --git a/go.sum b/go.sum index 20820e23..4699e97c 100644 --- a/go.sum +++ b/go.sum @@ -185,6 +185,7 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg= github.com/google/pprof v0.0.0-20230926050212-f7f687d19a98 h1:pUa4ghanp6q4IJHwE9RwLgmVFfReJN+KbQ8ExNEUUoQ= @@ -296,6 +297,7 @@ github.com/open-dingtalk/dingtalk-stream-sdk-go v0.9.0/go.mod h1:ln3IqPYYocZbYvl github.com/otiai10/copy v1.14.0 h1:dCI/t1iTdYGtkvCuBG2BgR6KZa83PTclw4U5n2wAllU= github.com/otiai10/copy v1.14.0/go.mod h1:ECfuL02W+/FkTWZWgQqXPWZgW9oeKCSQ5qVfSc4qc4w= github.com/otiai10/mint v1.5.1 h1:XaPLeE+9vGbuyEHem1JNk3bYc7KKqyI/na0/mLd/Kks= +github.com/otiai10/mint v1.5.1/go.mod h1:MJm72SBthJjz8qhefc4z1PYEieWmy8Bku7CjcAqyUSM= github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw= github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0= github.com/pdfcpu/pdfcpu v0.8.1 h1:AiWUb8uXlrXqJ73OmiYXBjDF0Qxt4OuM281eAfkAOMA= @@ -391,7 +393,9 @@ github.com/tdewolff/parse/v2 v2.7.15 h1:hysDXtdGZIRF5UZXwpfn3ZWRbm+ru4l53/ajBRGp github.com/tdewolff/parse/v2 v2.7.15/go.mod h1:3FbJWZp3XT9OWVN3Hmfp0p/a08v4h8J9W1aghka0soA= github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE= github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739 h1:IkjBCtQOOjIn03u/dMQK9g+Iw9ewps4mCl1nB8Sscbo= +github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= github.com/tidwall/assert v0.1.0 h1:aWcKyRBUAdLoVebxo95N7+YZVTFF/ASTr7BN4sLP6XI= +github.com/tidwall/assert v0.1.0/go.mod h1:QLYtGyeqse53vuELQheYl9dngGCJQ+mTtlxcktb+Kj8= github.com/tidwall/btree v1.7.0 h1:L1fkJH/AuEh5zBnnBbmTwQ5Lt+bRJ5A8EWecslvo9iI= github.com/tidwall/btree v1.7.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= github.com/tidwall/buntdb v1.3.2 h1:qd+IpdEGs0pZci37G4jF51+fSKlkuUTMXuHhXL1AkKg= @@ -404,6 +408,7 @@ github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vl github.com/tidwall/grect v0.1.4 h1:dA3oIgNgWdSspFzn1kS4S/RDpZFLrIxAZOdJKjYapOg= github.com/tidwall/grect v0.1.4/go.mod h1:9FBsaYRaR0Tcy4UwefBX/UDcDcDy9V5jUcxHzv2jd5Q= github.com/tidwall/lotsa v1.0.2 h1:dNVBH5MErdaQ/xd9s769R31/n2dXavsQ0Yf4TMEHHw8= +github.com/tidwall/lotsa v1.0.2/go.mod h1:X6NiU+4yHA3fE3Puvpnn1XMDrFZrE9JO2/w+UMuqgR8= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= @@ -440,6 +445,7 @@ go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.8.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= diff --git a/main.go b/main.go index 0b41c6a6..180e94a0 100644 --- a/main.go +++ b/main.go @@ -61,7 +61,7 @@ func cleanupCreate(diceManager *dice.DiceManager) func() { for _, i := range diceManager.Dice { if i.IsAlreadyLoadConfig { - i.BanList.SaveChanged(i) + i.Config.BanList.SaveChanged(i) i.Save(true) for _, j := range i.ExtList { if j.Storage != nil { diff --git a/tray_windows.go b/tray_windows.go index d234ea5a..df40c2c6 100644 --- a/tray_windows.go +++ b/tray_windows.go @@ -244,7 +244,7 @@ func httpServe(e *echo.Echo, dm *dice.DiceManager, hideUI bool) { os.Exit(0) } } else { - log.Info("如果浏览器没有自动打开,请手动访问:\nhttp://localhost:%s\n", portStr) + log.Infof("如果浏览器没有自动打开,请手动访问:\nhttp://localhost:%s\n", portStr) go showUI() break }