├── .gitignore
├── winres
├── icon.png
├── icon16.png
├── init.go
├── winres.json
└── gen
│ └── gen.go
├── bfhelper
├── pkg
│ ├── global
│ │ ├── dictionary.go
│ │ ├── db.go
│ │ ├── anticheat.go
│ │ ├── designation.go
│ │ ├── tracer.go
│ │ ├── setting.go
│ │ ├── engine.go
│ │ └── bf1.go
│ ├── uuid
│ │ └── uuid.go
│ ├── setting
│ │ ├── section.go
│ │ ├── struct.go
│ │ └── setting.go
│ ├── renderer
│ │ └── rendertext.go
│ ├── netreq
│ │ ├── netreq.go
│ │ └── bf1
│ │ │ └── body.go
│ ├── tracer
│ │ └── tracer.go
│ └── logger
│ │ └── logger.go
├── internal
│ ├── dao
│ │ ├── dao.go
│ │ ├── player.go
│ │ └── server.go
│ ├── model
│ │ ├── model.go
│ │ ├── init.go
│ │ ├── playerdb.go
│ │ └── serverdb.go
│ ├── anticheat
│ │ ├── bfban.go
│ │ ├── template.html
│ │ └── bfeac.go
│ ├── rule
│ │ ├── template.yml
│ │ └── rule.go
│ ├── service
│ │ ├── service.go
│ │ ├── player.go
│ │ └── server.go
│ ├── textutil
│ │ └── textutil.go
│ ├── bf1
│ │ ├── player
│ │ │ ├── record.go
│ │ │ ├── structs.go
│ │ │ └── player.go
│ │ ├── server
│ │ │ └── server.go
│ │ └── api
│ │ │ └── rpc.go
│ ├── errcode
│ │ ├── errcode.go
│ │ └── code.go
│ └── handler
│ │ ├── player.go
│ │ └── server.go
├── player_helper.go
└── server_helper.go
├── kanban
├── init.go
├── banner
│ └── banner.go
└── gen
│ └── banner.go
├── botsetting
├── default.yaml
└── config.go
├── console
├── console_ansi.go
└── console_windows.go
├── main.go
├── .github
├── workflows
│ ├── auto_merge.yml
│ ├── push.yml
│ ├── pull.yml
│ ├── release.yml
│ └── go.yml
└── dependabot.yml
├── .goreleaser.yml
├── .golangci.yml
├── go.mod
├── README.md
├── go.sum
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | *_test.go
2 | *.db
--------------------------------------------------------------------------------
/winres/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KomeiDiSanXian/BFHelper/HEAD/winres/icon.png
--------------------------------------------------------------------------------
/winres/icon16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KomeiDiSanXian/BFHelper/HEAD/winres/icon16.png
--------------------------------------------------------------------------------
/bfhelper/pkg/global/dictionary.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | // Dictionary 全局简转繁词典
4 | var Dictionary map[string]string
5 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/db.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import "github.com/jinzhu/gorm"
4 |
5 | // DB 全局数据库
6 | var DB *gorm.DB
7 |
--------------------------------------------------------------------------------
/kanban/init.go:
--------------------------------------------------------------------------------
1 | // Package kanban 打印版本信息
2 | package kanban
3 |
4 | //go:generate go run github.com/FloatTech/ZeroBot-Plugin/kanban/gen
5 |
--------------------------------------------------------------------------------
/winres/init.go:
--------------------------------------------------------------------------------
1 | // Package winres 生成windows资源
2 | package winres
3 |
4 | //go:generate go run github.com/KomeiDiSanXian/BFHelper/winres/gen
5 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/anticheat.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | const (
4 | BFBan = "https://api.gametools.network/bfban/" // BFBan gt联ban api
5 | BFEAC = "https://api.bfeac.com/" // BFEAC api
6 | )
7 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/designation.go:
--------------------------------------------------------------------------------
1 | // Package global 游戏代号
2 | package global
3 |
4 | // 游戏代号
5 | const (
6 | BF1 string = "tunguska"
7 | BFV string = "casablanca"
8 | BF4 string = "bf4"
9 | )
10 |
--------------------------------------------------------------------------------
/bfhelper/pkg/uuid/uuid.go:
--------------------------------------------------------------------------------
1 | // Package uuid uuid生成
2 | package uuid
3 |
4 | import "github.com/google/uuid"
5 |
6 | // NewUUID generates a new UUID v4
7 | func NewUUID() string {
8 | return uuid.New().String()
9 | }
10 |
--------------------------------------------------------------------------------
/botsetting/default.yaml:
--------------------------------------------------------------------------------
1 | Bot:
2 | BotNames:
3 | - "蕾米"
4 | - "蕾米莉亚"
5 | CommandPrefix: "."
6 | SuperUsers:
7 | - 123456
8 | - 654321
9 | RingLen: 40
10 | Latency: 233
11 | MarkMessage: true
12 | WSClient: "ws://127.0.0.1:6700"
13 | AccessToken: ""
--------------------------------------------------------------------------------
/bfhelper/internal/dao/dao.go:
--------------------------------------------------------------------------------
1 | // Package dao 数据访问对象
2 | package dao
3 |
4 | import "github.com/jinzhu/gorm"
5 |
6 | // Dao 含有数据库对象
7 | type Dao struct {
8 | engine *gorm.DB
9 | }
10 |
11 | // New 新建一个数据库对象
12 | func New(engine *gorm.DB) *Dao {
13 | return &Dao{engine: engine}
14 | }
15 |
--------------------------------------------------------------------------------
/bfhelper/internal/model/model.go:
--------------------------------------------------------------------------------
1 | // Package model 数据库操作
2 | package model
3 |
4 | import "github.com/jinzhu/gorm"
5 |
6 | // Open 打开数据库
7 | func Open(path string) (db *gorm.DB, err error) {
8 | db, err = gorm.Open("sqlite3", path)
9 | if err != nil {
10 | return nil, err
11 | }
12 | return db, err
13 | }
14 |
--------------------------------------------------------------------------------
/console/console_ansi.go:
--------------------------------------------------------------------------------
1 | //go:build !windows
2 |
3 | // Package console sets console's behavior on init
4 | package console
5 |
6 | import (
7 | "fmt"
8 |
9 | "github.com/KomeiDiSanXian/BFHelper/kanban/banner"
10 | )
11 |
12 | func init() {
13 | fmt.Print("\033]0;RemiliaBot " + banner.Version + " " + banner.Copyright + "\007")
14 | }
15 |
--------------------------------------------------------------------------------
/bfhelper/internal/anticheat/bfban.go:
--------------------------------------------------------------------------------
1 | // Package anticheat BFBan相关
2 | package anticheat
3 |
4 | // HackBFBanResp 返回案件信息
5 | type HackBFBanResp struct {
6 | IsCheater bool
7 | URL string
8 | Status string
9 | }
10 |
11 | // BFBanHackerStatus BFBan 举报状态
12 | var BFBanHackerStatus = map[int]string{
13 | 0: "正在处理",
14 | 1: "实锤",
15 | 2: "等待自证",
16 | 3: "MOSS自证",
17 | 4: "无效举报",
18 | 5: "讨论中",
19 | 6: "需要更多管理员投票",
20 | 8: "刷枪",
21 | }
22 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/tracer.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "github.com/KomeiDiSanXian/BFHelper/kanban/banner"
5 | "go.opentelemetry.io/otel"
6 | semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
7 | "go.opentelemetry.io/otel/trace"
8 | )
9 |
10 | // Tracer 全局追踪
11 | var Tracer = otel.GetTracerProvider().Tracer(
12 | "github.com/KomeiDiSanXian/BFHelper",
13 | trace.WithInstrumentationVersion(banner.Version),
14 | trace.WithSchemaURL(semconv.SchemaURL),
15 | )
16 |
--------------------------------------------------------------------------------
/kanban/banner/banner.go:
--------------------------------------------------------------------------------
1 | // Code generated by kanban/gen. DO NOT EDIT.
2 |
3 | package banner
4 |
5 | // Version ...
6 | var Version = "v1.0.0"
7 |
8 | // Copyright ...
9 | var Copyright = "© 2020 - 2023 FloatTech"
10 |
11 | // Banner ...
12 | var Banner = "* OneBot + ZeroBot + Golang\n" +
13 | "* Version " + Version + " - 2023-08-02 01:22:12 +0800 CST\n" +
14 | "* Copyright " + Copyright + ". All Rights Reserved.\n" +
15 | "* Project: https://github.com/KomeiDiSanXian/BFHelper\n" +
16 | "* Origin Project: https://github.com/FloatTech/ZeroBot-Plugin"
17 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/setting.go:
--------------------------------------------------------------------------------
1 | package global
2 |
3 | import (
4 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/logger"
5 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/setting"
6 | )
7 |
8 | var (
9 | AccountSetting *setting.AccountSettingS // AccountSetting 账号设置
10 | SessionAPISetting *setting.SessionAPISettingS // SessionAPISetting Session 获取
11 | BFEACSetting *setting.BFEACSettingS // BFEACSetting BFEAC 设置
12 | TraceSetting *setting.TraceSettingS // TraceSetting 追踪设置
13 |
14 | Logger *logger.Logger // Logger 日志
15 | )
16 |
--------------------------------------------------------------------------------
/bfhelper/internal/model/init.go:
--------------------------------------------------------------------------------
1 | // Package model 数据库操作
2 | package model
3 |
4 | import (
5 | "github.com/jinzhu/gorm"
6 | // _ "github.com/jinzhu/gorm/dialects/sqlite" // sqlite 启用dialect,集成测试及relase需要注释掉
7 | )
8 |
9 | // Init 数据库初始化
10 | func Init(path string) error {
11 | db, err := gorm.Open("sqlite3", path)
12 | if err != nil {
13 | return err
14 | }
15 |
16 | // Migrate the schema
17 | err = db.AutoMigrate(&Player{}, &Group{}, &Server{}, &Admin{}).Error
18 | if err != nil {
19 | return err
20 | }
21 | db.SingularTable(true)
22 | return db.Close()
23 | }
24 |
--------------------------------------------------------------------------------
/bfhelper/internal/rule/template.yml:
--------------------------------------------------------------------------------
1 | Account:
2 | UserName: your_ea_account@example.com
3 | Password: yourpassword
4 | # 以下信息你可以自己填写进去
5 | Session: "-"
6 | Token: "-"
7 | SID: "-"
8 | Remid: "-"
9 | # 这个API key 请去联系SakuraKooi 本人获取,或者等什么时候我自己写
10 | SakuraKooi:
11 | SakuraID: yourid
12 | SakuraToken: yourtoken
13 | MFASecret: "" # 开启了两步验证就要填这个, 类似于2GFS PQSN 7D25 6HRG, 用于计算MFA Code
14 | # 举报功能的使用需要填写该项
15 | BFEAC:
16 | ApiKey: "-"
17 | # 追踪相关
18 | Trace:
19 | Enabled: false # 是否开启追踪
20 | URL: "-" # 追踪日志上传到何处,不要填写http或者https等schema
21 | UseHTTPS: false # 是否使用ssl
22 |
--------------------------------------------------------------------------------
/bfhelper/pkg/setting/section.go:
--------------------------------------------------------------------------------
1 | package setting
2 |
3 | var sections = make(map[string]any)
4 |
5 | // ReadSection 根据给定的建造的写入map section
6 | func (s *Setting) ReadSection(k string, v any) error {
7 | if err := s.vp.UnmarshalKey(k, v); err != nil {
8 | return err
9 | }
10 | if _, ok := sections[k]; !ok {
11 | sections[k] = v
12 | }
13 | return nil
14 | }
15 |
16 | // ReloadAllSections 重载所有键值对
17 | func (s *Setting) ReloadAllSections() error {
18 | for k, v := range sections {
19 | err := s.ReadSection(k, v)
20 | if err != nil {
21 | return err
22 | }
23 | }
24 | return nil
25 | }
26 |
--------------------------------------------------------------------------------
/bfhelper/internal/service/service.go:
--------------------------------------------------------------------------------
1 | // Package service 业务逻辑代码
2 | package service
3 |
4 | import (
5 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/dao"
6 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
7 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/logger"
8 | zero "github.com/wdvxdr1123/ZeroBot"
9 | )
10 |
11 | // Service 业务
12 | type Service struct {
13 | zctx *zero.Ctx
14 | dao *dao.Dao
15 | }
16 |
17 | // New 新建业务
18 | func New(zctx *zero.Ctx) *Service {
19 | svc := Service{zctx: zctx}
20 | svc.dao = dao.New(global.DB)
21 | return &svc
22 | }
23 |
24 | // Log 日志记录
25 | //
26 | // 多业务使用同一个log
27 | func (s *Service) Log() *logger.Logger {
28 | return global.Logger
29 | }
30 |
--------------------------------------------------------------------------------
/bfhelper/pkg/setting/struct.go:
--------------------------------------------------------------------------------
1 | package setting
2 |
3 | // AccountSettingS 账号相关设置
4 | type AccountSettingS struct {
5 | Username string
6 | Password string
7 | Session string // Session is X-Gatewaysession
8 | Token string // Token is bearerAccessToken
9 | SID string // SID is cookie sid
10 | Remid string // Remid is cookie remid
11 | }
12 |
13 | // SessionAPISettingS 获取Session的API设置
14 | type SessionAPISettingS struct {
15 | SakuraID string
16 | SakuraToken string
17 | MFASecret string
18 | }
19 |
20 | // BFEACSettingS BFEAC 设置
21 | type BFEACSettingS struct {
22 | APIKey string
23 | }
24 |
25 | // TraceSettingS 追踪设置
26 | type TraceSettingS struct {
27 | Enabled bool
28 | UseHTTPS bool
29 | URL string
30 | }
31 |
--------------------------------------------------------------------------------
/bfhelper/pkg/renderer/rendertext.go:
--------------------------------------------------------------------------------
1 | // Package renderer 文字转图片并发送
2 | package renderer
3 |
4 | import (
5 | "github.com/FloatTech/zbputils/img/text"
6 | zero "github.com/wdvxdr1123/ZeroBot"
7 | "github.com/wdvxdr1123/ZeroBot/message"
8 | "github.com/wdvxdr1123/ZeroBot/utils/helper"
9 | )
10 |
11 | // Txt2Img 文字转图片并发送
12 | func Txt2Img(ctx *zero.Ctx, txt string) {
13 | data, err := text.RenderToBase64(txt, text.FontFile, 400, 20)
14 | if err != nil {
15 | ctx.Send(message.ReplyWithMessage(ctx.Event.MessageID, message.Text("将文字转换成图片时发生错误")))
16 | }
17 | if id := ctx.Send(message.ReplyWithMessage(ctx.Event.MessageID, message.Image("base64://"+helper.BytesToString(data)))); id.ID() == 0 {
18 | ctx.SendChain(message.At(ctx.Event.UserID), message.Text("ERROR:可能被风控了"))
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/bfhelper/internal/textutil/textutil.go:
--------------------------------------------------------------------------------
1 | // Package textutil 用于处理文字
2 | package textutil
3 |
4 | import (
5 | "strings"
6 |
7 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
8 | )
9 |
10 | // Traditionalize 简体转繁体
11 | func Traditionalize(text string) string {
12 | result := ""
13 | for _, v := range text {
14 | r, ok := global.Dictionary[string(v)]
15 | if ok {
16 | result += r
17 | continue
18 | }
19 | result += string(v)
20 | }
21 | return result
22 | }
23 |
24 | // CleanPersonalID 检查是否为pid (有 # 就判断为pid)
25 | //
26 | // 如果是就删去 # 并返回 pid
27 | //
28 | // 为否就返回输入
29 | func CleanPersonalID(input string) (cleaned string, hasHash bool) {
30 | if strings.Contains(input, "#") {
31 | cleaned = strings.Trim(input, "#")
32 | return cleaned, true
33 | }
34 | return input, false
35 | }
36 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | // Package main 主程序
2 | package main
3 |
4 | import (
5 | _ "github.com/KomeiDiSanXian/BFHelper/bfhelper"
6 | _ "github.com/KomeiDiSanXian/BFHelper/console"
7 |
8 | "github.com/KomeiDiSanXian/BFHelper/botsetting"
9 |
10 | "github.com/FloatTech/floatbox/process"
11 | zero "github.com/wdvxdr1123/ZeroBot"
12 | "github.com/wdvxdr1123/ZeroBot/driver"
13 | )
14 |
15 | var c zero.Config
16 |
17 | func init() {
18 | s := botsetting.Read()
19 | // 使用正向ws
20 | c.Driver = []zero.Driver{driver.NewWebSocketClient(s.WSClient, s.AccessToken)}
21 |
22 | c.NickName = s.BotNames
23 | c.CommandPrefix = s.CommandPrefix
24 | c.SuperUsers = s.SuperUsers
25 | c.RingLen = s.RingLen
26 | c.MarkMessage = s.MarkMessage
27 | }
28 |
29 | func main() {
30 | zero.RunAndBlock(&c, process.GlobalInitMutex.Unlock)
31 | }
32 |
--------------------------------------------------------------------------------
/bfhelper/pkg/setting/setting.go:
--------------------------------------------------------------------------------
1 | // Package setting 设置
2 | package setting
3 |
4 | import (
5 | "github.com/fsnotify/fsnotify"
6 | "github.com/spf13/viper"
7 | )
8 |
9 | // Setting 使用viper读取设置信息
10 | type Setting struct {
11 | vp *viper.Viper
12 | }
13 |
14 | // NewSetting 读取配置信息
15 | func NewSetting(name, path string) (*Setting, error) {
16 | vp := viper.New()
17 | vp.SetConfigName(name)
18 | vp.AddConfigPath(path)
19 | vp.SetConfigType("yaml")
20 | if err := vp.ReadInConfig(); err != nil {
21 | return nil, err
22 | }
23 | s := &Setting{vp}
24 | s.WatchSettingChange()
25 | return s, nil
26 | }
27 |
28 | // WatchSettingChange 配置热更新
29 | func (s *Setting) WatchSettingChange() {
30 | go func() {
31 | s.vp.WatchConfig()
32 | s.vp.OnConfigChange(func(_ fsnotify.Event) {
33 | _ = s.ReloadAllSections()
34 | })
35 | }()
36 | }
37 |
--------------------------------------------------------------------------------
/.github/workflows/auto_merge.yml:
--------------------------------------------------------------------------------
1 | name: Dependabot auto-merge
2 | on:
3 | pull_request:
4 | types: [opened, reopened, synchronize]
5 |
6 | permissions:
7 | contents: write
8 | pull-requests: write
9 |
10 | jobs:
11 | dependabot:
12 | runs-on: ubuntu-latest
13 | if: github.actor == 'dependabot[bot]' || github.actor == 'github-actions[bot]'
14 | steps:
15 | - name: Checkout Repository
16 | uses: actions/checkout@v4
17 |
18 | - name: Dependabot metadata
19 | id: metadata
20 | uses: dependabot/fetch-metadata@v2
21 | with:
22 | github-token: "${{ secrets.GITHUB_TOKEN }}"
23 |
24 | - name: Merge a PR
25 | run: gh pr merge --auto --merge "$PR_URL"
26 | env:
27 | PR_URL: ${{github.event.pull_request.html_url}}
28 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
29 |
--------------------------------------------------------------------------------
/.github/workflows/push.yml:
--------------------------------------------------------------------------------
1 | name: PushLint
2 | on: [ push ]
3 | jobs:
4 | golangci:
5 | name: lint
6 | runs-on: ubuntu-latest
7 | steps:
8 | - name: Set up Go
9 | uses: actions/setup-go@master
10 | with:
11 | go-version: '1.22'
12 |
13 | - name: Check out code into the Go module directory
14 | uses: actions/checkout@master
15 |
16 | - name: golangci-lint
17 | uses: golangci/golangci-lint-action@master
18 | with:
19 | version: latest
20 |
21 | - name: Commit back
22 | if: ${{ !github.head_ref }}
23 | continue-on-error: true
24 | run: |
25 | git config --local user.name 'github-actions[bot]'
26 | git config --local user.email '41898282+github-actions[bot]@users.noreply.github.com'
27 | git add --all
28 | git commit -m "🎨 改进代码样式"
29 |
30 | - name: Create Pull Request
31 | if: ${{ !github.head_ref }}
32 | continue-on-error: true
33 | uses: peter-evans/create-pull-request@v7
34 |
--------------------------------------------------------------------------------
/bfhelper/internal/dao/player.go:
--------------------------------------------------------------------------------
1 | // Package dao 玩家dao层操作
2 | package dao
3 |
4 | import "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/model"
5 |
6 | // CreatePlayer 创建玩家条目
7 | func (d *Dao) CreatePlayer(qid int64, name string) error {
8 | player := model.Player{Qid: qid, DisplayName: name}
9 | return player.Create(d.engine)
10 | }
11 |
12 | // DeletePlayer 删除玩家
13 | func (d *Dao) DeletePlayer(qid int64) error {
14 | player := model.Player{Qid: qid}
15 | return player.Delete(d.engine)
16 | }
17 |
18 | // UpdatePlayer 更新玩家信息
19 | func (d *Dao) UpdatePlayer(qid int64, pid, name string) error {
20 | player := model.Player{Qid: qid, PersonalID: pid, DisplayName: name}
21 | return player.Update(d.engine)
22 | }
23 |
24 | // GetPlayerByQID 根据qq号获取玩家信息
25 | func (d *Dao) GetPlayerByQID(qid int64) (*model.Player, error) {
26 | player := model.Player{Qid: qid}
27 | return player.GetByQID(d.engine, qid)
28 | }
29 |
30 | // GetPlayerByName 根据玩家名获取玩家信息
31 | func (d *Dao) GetPlayerByName(name string) (*model.Player, error) {
32 | player := model.Player{DisplayName: name}
33 | return player.GetByName(d.engine, name)
34 | }
35 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/engine.go:
--------------------------------------------------------------------------------
1 | // Package global 插件注册
2 | package global
3 |
4 | import (
5 | ctrl "github.com/FloatTech/zbpctrl"
6 | "github.com/FloatTech/zbputils/control"
7 | zero "github.com/wdvxdr1123/ZeroBot"
8 | )
9 |
10 | // Engine 引擎注册
11 | var Engine = control.Register("战地", &ctrl.Options[*zero.Ctx]{
12 | DisableOnDefault: false,
13 | Brief: "战地相关查询功能",
14 | Help: "battlefield\n" +
15 | "<-----以下是玩家查询----->\n" +
16 | "- .武器 [武器类型] [id]\t不填武器武器类型默认查询全部\n" +
17 | "- .载具 [id]\n" +
18 | "- .cb [id] 查询玩家EAC和BFBan案件信息\n" +
19 | "<-----以下是服务器管理----->\n" +
20 | "- .k id 将 id 踢出服务器\n" +
21 | "- .b alias id 在别名为 alias 的服务器封禁 id\n" +
22 | "- .ub alias id 在别名为 alias 的服务器解封 id\n" +
23 | "- .bana alias id 在所有已绑定的服务器封禁 id\n" +
24 | "- .ubana alias id 在所有已绑定的服务器解封 id\n" +
25 | "- .cm alias [地图id] 在别名为 alias 的服务器切换地图到地图id\n" +
26 | "- .qm alias 查询别名为 alias 的地图池信息\n" +
27 | "<-----以下是更多功能----->\n" +
28 | "- .交换\t查询本周战地一武器皮肤\n" +
29 | "- .行动\t查询战地一行动箱子\n" +
30 | "- .战绩 [id]\t查询生涯的战绩\n" +
31 | "- .最近 [id]\t查询最近的战绩\n" +
32 | "- .绑定 id\t进行账号绑定",
33 | PrivateDataFolder: "battlefield",
34 | })
35 |
--------------------------------------------------------------------------------
/botsetting/config.go:
--------------------------------------------------------------------------------
1 | // Package botsetting 机器人设置相关
2 | package botsetting
3 |
4 | import (
5 | _ "embed"
6 | "os"
7 | "time"
8 |
9 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/setting"
10 | "github.com/sirupsen/logrus"
11 | )
12 |
13 | // defaultConfig 默认bot 配置
14 | //
15 | //go:embed default.yaml
16 | var defaultConfig string
17 |
18 | // Config 机器人设置
19 | type Config struct {
20 | BotNames []string
21 | CommandPrefix string
22 | SuperUsers []int64
23 | RingLen uint
24 | Latency time.Duration
25 | MarkMessage bool
26 | WSClient string
27 | AccessToken string
28 | }
29 |
30 | // Read 读取配置文件
31 | func Read() *Config {
32 | s, err := setting.NewSetting("botconfig", ".")
33 | c := Config{}
34 | if err != nil {
35 | logrus.Warnln(err)
36 | generateConfig()
37 | }
38 | _ = s.ReadSection("Bot", &c)
39 | return &c
40 | }
41 |
42 | func generateConfig() {
43 | logrus.Warnln("未找到配置或者出现错误, 正在重新生成...")
44 | _ = os.WriteFile("botconfig.yaml", []byte(defaultConfig), 0o644)
45 | logrus.Warnln("配置已生成! 请修改 botconfig.yaml 后重新启动")
46 | time.Sleep(15 * time.Second)
47 | os.Exit(0)
48 | }
49 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5 |
6 | version: 2
7 | registries:
8 | github:
9 | type: git
10 | url: https://github.com
11 | username: KomeiDiSanXian
12 | password: ${{ secrets.TOKEN }}
13 | updates:
14 | - package-ecosystem: "github-actions"
15 | registries:
16 | - github
17 | directory: "/"
18 | schedule:
19 | interval: "weekly"
20 | commit-message:
21 | prefix: "chore(deps): update"
22 | labels:
23 | - "dependencies"
24 | assignees:
25 | - "dependabot[bot]"
26 |
27 | - package-ecosystem: "gomod"
28 | registries:
29 | - github
30 | directory: "/"
31 | schedule:
32 | interval: "weekly"
33 | commit-message:
34 | prefix: "chore(deps): update go dependencies"
35 | labels:
36 | - "dependencies"
37 | assignees:
38 | - "dependabot[bot]"
39 |
--------------------------------------------------------------------------------
/bfhelper/player_helper.go:
--------------------------------------------------------------------------------
1 | // Package bfhelper 战地玩家查询
2 | package bfhelper
3 |
4 | import (
5 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/handler"
6 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
7 | )
8 |
9 | func init() {
10 | // QQ绑定ID
11 | global.Engine.OnPrefixGroup([]string{".绑定", ".bind"}).SetBlock(true).Handle(handler.BindAccountHandler)
12 | // bf1个人战绩
13 | global.Engine.OnRegex(`\. *1?战绩 *(.*)$`).SetBlock(true).Handle(handler.PlayerStatsHandler)
14 | // 武器查询,只展示前五个
15 | global.Engine.OnRegex(`^\. *1?武器 *(.*)$`).SetBlock(true).Handle(handler.PlayerWeaponHandler)
16 | // 最近战绩
17 | global.Engine.OnRegex(`^\. *1?最近 *(.*)$`).SetBlock(true).Handle(handler.PlayerRecentHandler)
18 | // 获取所有种类的载具信息
19 | global.Engine.OnRegex(`^\. *1?载具 *(.*)$`).SetBlock(true).Handle(handler.PlayerVehicleHandler)
20 | // 交换查询
21 | global.Engine.OnFullMatchGroup([]string{".交换", ".exchange"}).SetBlock(true).Handle(handler.BF1ExchangeHandler)
22 | // 行动包查询
23 | global.Engine.OnFullMatchGroup([]string{".行动", ".行动包", ".pack"}).SetBlock(true).Handle(handler.BF1OpreationPackHandler)
24 | // 查询玩家是否有案件
25 | global.Engine.OnRegex(`^\. *1?cb *(.*)$`).SetBlock(true).Handle(handler.PlayerBanInfoHandler)
26 | }
27 |
--------------------------------------------------------------------------------
/.github/workflows/pull.yml:
--------------------------------------------------------------------------------
1 | name: PullLint
2 | on: [ pull_request ]
3 | jobs:
4 | golangci:
5 | name: lint
6 | runs-on: ubuntu-latest
7 | steps:
8 | - name: Set up Go
9 | uses: actions/setup-go@master
10 | with:
11 | go-version: '1.22'
12 |
13 | - name: Check out code into the Go module directory
14 | uses: actions/checkout@master
15 |
16 | - name: golangci-lint
17 | uses: golangci/golangci-lint-action@master
18 | with:
19 | # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
20 | version: latest
21 |
22 | # Optional: working directory, useful for monorepos
23 | # working-directory: somedir
24 |
25 | # Optional: golangci-lint command line arguments.
26 | # args: --issues-exit-code=0
27 |
28 | # Optional: show only new issues if it's a pull request. The default value is `false`.
29 | # only-new-issues: true
30 |
31 | # Optional: if set to true then the action don't cache or restore ~/go/pkg.
32 | # skip-pkg-cache: true
33 |
34 | # Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
35 | # skip-build-cache: true
36 |
--------------------------------------------------------------------------------
/kanban/gen/banner.go:
--------------------------------------------------------------------------------
1 | // Package main generates banner.go
2 | package main
3 |
4 | import (
5 | "bytes"
6 | "fmt"
7 | "os"
8 | "os/exec"
9 | "strings"
10 | "time"
11 | )
12 |
13 | const banner = `// Code generated by kanban/gen. DO NOT EDIT.
14 |
15 | package banner
16 |
17 | // Version ...
18 | var Version = "%s"
19 |
20 | // Copyright ...
21 | var Copyright = "© 2020 - %d FloatTech"
22 |
23 | // Banner ...
24 | var Banner = "* OneBot + ZeroBot + Golang\n" +
25 | "* Version " + Version + " - %s\n" +
26 | "* Copyright " + Copyright + ". All Rights Reserved.\n" +
27 | "* Project: https://github.com/KomeiDiSanXian/RemiliaBot\n" +
28 | "* Origin Project: https://github.com/FloatTech/ZeroBot-Plugin"
29 | `
30 |
31 | const timeformat = `2006-01-02 15:04:05 +0800 CST`
32 |
33 | func main() {
34 | f, err := os.Create("banner/banner.go")
35 | if err != nil {
36 | panic(err)
37 | }
38 | defer f.Close()
39 | vartag := bytes.NewBuffer(nil)
40 | vartagcmd := exec.Command("git", "tag", "--sort=committerdate")
41 | vartagcmd.Stdout = vartag
42 | err = vartagcmd.Run()
43 | if err != nil {
44 | panic(err)
45 | }
46 | s := strings.Split(vartag.String(), "\n")
47 | now := time.Now()
48 | _, err = fmt.Fprintf(f, banner, s[len(s)-2], now.Year(), now.Format(timeformat))
49 | if err != nil {
50 | panic(err)
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/bfhelper/internal/bf1/player/record.go:
--------------------------------------------------------------------------------
1 | // Package player 战地相关战绩查询
2 | package player
3 |
4 | import (
5 | "fmt"
6 | "sort"
7 |
8 | "github.com/tidwall/gjson"
9 | )
10 |
11 | // SortWeapon 武器排序
12 | func SortWeapon(weapons []gjson.Result) *WeaponSort {
13 | wp := WeaponSort{}
14 | for i := range weapons {
15 | gets := gjson.GetMany(weapons[i].Raw,
16 | "name",
17 | "stats.values.kills",
18 | "stats.values.headshots",
19 | "stats.values.accuracy",
20 | "stats.values.seconds",
21 | "stats.values.hits",
22 | "stats.values.shots",
23 | )
24 | kills := gets[1].Float()
25 | seconds := gets[4].Float()
26 | heads := gets[2].Float()
27 | hits := gets[5].Float()
28 | var (
29 | kpm float64
30 | headshots float64
31 | eff float64
32 | )
33 | // 除以0的情况
34 | if kills == 0 || seconds == 0 {
35 | kpm = 0
36 | headshots = 0
37 | eff = 0
38 | } else {
39 | headshots = heads / kills * 100
40 | kpm = kills / seconds * 60
41 | eff = hits / kills
42 | }
43 | wp = append(wp, Weapons{
44 | Name: gets[0].Str,
45 | Kills: kills,
46 | Accuracy: fmt.Sprintf("%.2f%%", gets[3].Float()),
47 | KPM: fmt.Sprintf("%.3f", kpm),
48 | Headshots: fmt.Sprintf("%.2f%%", headshots),
49 | Efficiency: fmt.Sprintf("%.3f", eff),
50 | })
51 | }
52 | sort.Sort(wp)
53 | return &wp
54 | }
55 |
--------------------------------------------------------------------------------
/winres/winres.json:
--------------------------------------------------------------------------------
1 | {
2 | "RT_GROUP_ICON": {
3 | "APP": {
4 | "0000": [
5 | "icon.png",
6 | "icon16.png"
7 | ]
8 | }
9 | },
10 | "RT_MANIFEST": {
11 | "#1": {
12 | "0409": {
13 | "identity": {
14 | "name": "BFHelper",
15 | "version": "1.0.0.77"
16 | },
17 | "description": "",
18 | "minimum-os": "win7",
19 | "execution-level": "as invoker",
20 | "ui-access": false,
21 | "auto-elevate": false,
22 | "dpi-awareness": "system",
23 | "disable-theming": false,
24 | "disable-window-filtering": false,
25 | "high-resolution-scrolling-aware": false,
26 | "ultra-high-resolution-scrolling-aware": false,
27 | "long-path-aware": false,
28 | "printer-driver-isolation": false,
29 | "gdi-scaling": false,
30 | "segment-heap": false,
31 | "use-common-controls-v6": false
32 | }
33 | }
34 | },
35 | "RT_VERSION": {
36 | "#1": {
37 | "0000": {
38 | "fixed": {
39 | "file_version": "1.0.0.77",
40 | "product_version": "v1.0.0",
41 | "timestamp": "2023-08-05T17:52:13+08:00"
42 | },
43 | "info": {
44 | "0409": {
45 | "Comments": "OneBot plugin based on ZeroBot",
46 | "CompanyName": "FloatTech",
47 | "FileDescription": "https://github.com/KomeiDiSanXian/BFHelper",
48 | "FileVersion": "1.0.0.77",
49 | "InternalName": "",
50 | "LegalCopyright": "© 2020 - 2023 FloatTech. All Rights Reserved.",
51 | "LegalTrademarks": "",
52 | "OriginalFilename": "BFHelper.exe",
53 | "PrivateBuild": "",
54 | "ProductName": "BFHelper",
55 | "ProductVersion": "v1.0.0",
56 | "SpecialBuild": ""
57 | }
58 | }
59 | }
60 | }
61 | }
62 | }
--------------------------------------------------------------------------------
/bfhelper/pkg/netreq/netreq.go:
--------------------------------------------------------------------------------
1 | // Package netreq 网络请求相关
2 | package netreq
3 |
4 | import (
5 | "io"
6 | "net/http"
7 | "strings"
8 | "time"
9 |
10 | "github.com/tidwall/gjson"
11 | )
12 |
13 | // Request 请求结构体
14 | type Request struct {
15 | Method string
16 | URL string
17 | Header map[string]string
18 | Body io.Reader
19 | Transport http.RoundTripper
20 | }
21 |
22 | func (r Request) client() *http.Client {
23 | return &http.Client{
24 | Timeout: time.Minute,
25 | Transport: r.Transport,
26 | }
27 | }
28 |
29 | func (r Request) do() (*http.Response, error) {
30 | if r.Method == "" {
31 | r.Method = http.MethodGet
32 | }
33 | req, err := http.NewRequest(r.Method, r.URL, r.Body)
34 | if err != nil {
35 | return nil, err
36 | }
37 |
38 | for k, v := range r.Header {
39 | req.Header.Set(k, v)
40 | }
41 | return r.client().Do(req)
42 | }
43 |
44 | func (r Request) respBody() (io.ReadCloser, error) {
45 | resp, err := r.do()
46 | if err != nil {
47 | return nil, err
48 | }
49 | return resp.Body, nil
50 | }
51 |
52 | // GetRespBodyBytes 向给定URL 发送请求,返回响应体Byte
53 | func (r Request) GetRespBodyBytes() ([]byte, error) {
54 | b, err := r.respBody()
55 | if err != nil {
56 | return nil, err
57 | }
58 | defer b.Close()
59 | return io.ReadAll(b)
60 | }
61 |
62 | // GetRespBodyJSON 向给定URL 发送请求,响应转换成JSON
63 | func (r Request) GetRespBodyJSON() (*gjson.Result, error) {
64 | b, err := r.respBody()
65 | if err != nil {
66 | return nil, err
67 | }
68 | defer b.Close()
69 |
70 | var sb strings.Builder
71 | _, err = io.Copy(&sb, b)
72 | if err != nil {
73 | return nil, err
74 | }
75 | result := gjson.Parse(sb.String())
76 | return &result, nil
77 | }
78 |
--------------------------------------------------------------------------------
/bfhelper/internal/model/playerdb.go:
--------------------------------------------------------------------------------
1 | // Package model 玩家操作
2 | package model
3 |
4 | import (
5 | "errors"
6 | "time"
7 |
8 | "github.com/jinzhu/gorm"
9 | )
10 |
11 | // Player 玩家表
12 | type Player struct {
13 | CreatedAt time.Time
14 | UpdatedAt time.Time
15 | PersonalID string // pid
16 | Qid int64 `gorm:"primary_key;auto_increment:false"` // QQ号
17 | DisplayName string // 玩家id
18 | }
19 |
20 | // Create 创建玩家条目
21 | func (player *Player) Create(db *gorm.DB) error {
22 | return db.Create(player).Error
23 | }
24 |
25 | // Update 使用Updates方法更新玩家信息,0值不更新
26 | func (player *Player) Update(db *gorm.DB) error {
27 | if player.Qid == 0 {
28 | return errors.New("qid cannot be empty")
29 | }
30 |
31 | return db.Model(&Player{}).Updates(player).Error
32 | }
33 |
34 | // Delete 删除玩家信息
35 | func (player *Player) Delete(db *gorm.DB) error {
36 | if player.Qid == 0 {
37 | return errors.New("qid cannot be empty")
38 | }
39 |
40 | return db.Where("qid = ?", player.Qid).Delete(&Player{}).Error
41 | }
42 |
43 | // GetByQID 使用qq号查询玩家表
44 | func (player *Player) GetByQID(db *gorm.DB, qid int64) (*Player, error) {
45 | if qid == 0 {
46 | return nil, errors.New("qid cannot be empty")
47 | }
48 |
49 | var playerResult Player
50 | if err := db.Where("qid = ?", qid).First(&playerResult).Error; err != nil {
51 | return nil, err
52 | }
53 | return &playerResult, nil
54 | }
55 |
56 | // GetByName 使用玩家名查询玩家表
57 | func (player *Player) GetByName(db *gorm.DB, name string) (*Player, error) {
58 | if name == "" {
59 | return nil, errors.New("name cannot be empty")
60 | }
61 | var playerResult Player
62 | if err := db.Where("display_name = ?", name).First(&playerResult).Error; err != nil {
63 | return nil, err
64 | }
65 | return &playerResult, nil
66 | }
67 |
--------------------------------------------------------------------------------
/.goreleaser.yml:
--------------------------------------------------------------------------------
1 | project_name: BFHelper
2 | env:
3 | - GO111MODULE=on
4 | before:
5 | hooks:
6 | - go mod tidy
7 | - go install github.com/tc-hib/go-winres@latest
8 | - go-winres make
9 | builds:
10 | - id: nowin
11 | env:
12 | - CGO_ENABLED=0
13 | - GO111MODULE=on
14 | goos:
15 | - linux
16 | goarch:
17 | - 386
18 | - amd64
19 | - arm
20 | - arm64
21 | goarm:
22 | - 6
23 | - 7
24 | mod_timestamp: "{{ .CommitTimestamp }}"
25 | flags:
26 | - -trimpath
27 | ldflags:
28 | - -s -w
29 | - -checklinkname=0
30 | - id: win
31 | env:
32 | - CGO_ENABLED=0
33 | - GO111MODULE=on
34 | goos:
35 | - windows
36 | goarch:
37 | - 386
38 | - amd64
39 | mod_timestamp: "{{ .CommitTimestamp }}"
40 | flags:
41 | - -trimpath
42 | ldflags:
43 | - -s -w
44 | - -checklinkname=0
45 |
46 | checksum:
47 | name_template: "{{ .ProjectName }}_checksums.txt"
48 | changelog:
49 | sort: asc
50 | filters:
51 | exclude:
52 | - "^docs:"
53 | - "^test:"
54 | - fix typo
55 | - Merge pull request
56 | - Merge branch
57 | - Merge remote-tracking
58 | - go mod tidy
59 |
60 | archives:
61 | - id: nowin
62 | builds:
63 | - nowin
64 | - win
65 | name_template: "{{ .ProjectName }}v{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
66 | format_overrides:
67 | - goos: windows
68 | format: zip
69 |
70 | nfpms:
71 | - license: AGPL 3.0
72 | homepage: https://github.com/KomeiDiSanXian/BFHelper
73 | file_name_template: "{{ .ProjectName }}v{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
74 | formats:
75 | - deb
76 | - rpm
77 | maintainer: KomeiDiSanXian
78 |
--------------------------------------------------------------------------------
/bfhelper/internal/errcode/errcode.go:
--------------------------------------------------------------------------------
1 | // Package errcode 错误码标准化
2 | package errcode
3 |
4 | import (
5 | "fmt"
6 |
7 | zero "github.com/wdvxdr1123/ZeroBot"
8 | )
9 |
10 | // Error 错误
11 | type Error struct {
12 | code int
13 | msg string
14 | details map[string]any
15 | }
16 |
17 | var codes = map[int]string{}
18 |
19 | // NewError 创建一个错误到codes并返回Error指针
20 | func NewError(code int, msg string) *Error {
21 | if _, ok := codes[code]; ok {
22 | panic(fmt.Sprintf("code %d already exists", code))
23 | }
24 | codes[code] = msg
25 | return &Error{code: code, msg: msg, details: make(map[string]any)}
26 | }
27 |
28 | // Code 返回错误码
29 | func (e *Error) Code() int {
30 | return e.code
31 | }
32 |
33 | // Message 返回错误信息
34 | func (e *Error) Message() string {
35 | return e.msg
36 | }
37 |
38 | // Error 打印错误信息
39 | func (e *Error) Error() string {
40 | return fmt.Sprintf("code: %d, message: %s, details: %v", e.Code(), e.Message(), e.Details())
41 | }
42 |
43 | // Messagef 格式化输出错误信息
44 | func (e *Error) Messagef(args ...any) string {
45 | return fmt.Sprintf(e.msg, args)
46 | }
47 |
48 | // Details 输出错误有关细节
49 | func (e *Error) Details() map[string]any {
50 | return e.details
51 | }
52 |
53 | // WithDetails 添加错误细节
54 | func (e *Error) WithDetails(k string, v any) *Error {
55 | newError := *e
56 | newDetails := make(map[string]any)
57 | for key, val := range e.details {
58 | newDetails[key] = val
59 | }
60 | newDetails[k] = v
61 | newError.details = newDetails
62 | return &newError
63 | }
64 |
65 | // WithZeroContext 添加zero.Ctx 相关细节
66 | func (e *Error) WithZeroContext(ctx *zero.Ctx) *Error {
67 | return e.
68 | WithDetails("User", ctx.Event.UserID).
69 | WithDetails("Command", ctx.Event.RawMessage).
70 | WithDetails("Time", ctx.Event.Time).
71 | WithDetails("Bot", ctx.Event.SelfID).
72 | WithDetails("Group", ctx.Event.GroupID)
73 | }
74 |
--------------------------------------------------------------------------------
/bfhelper/pkg/global/bf1.go:
--------------------------------------------------------------------------------
1 | // Package global bf1全局变量
2 | package global
3 |
4 | const (
5 | NativeAPI string = "https://sparta-gw.battlelog.com/jsonrpc/pc/api" // NativeAPI EA JSONRPC API
6 | SessionAPI string = "https://battlefield-api.sakurakooi.dev/account/login" // SessionAPI 通过SakuraKooi 获取session 信息
7 | OperationAPI string = "https://sparta-gw.battlelog.com/jsonrpc/ps4/api" // OperationAPI 交换和行动包查询
8 | )
9 |
10 | const (
11 | AddVIP string = "RSP.addServerVip" // AddVIP 单服务器添加VIP
12 | RemoveVIP string = "RSP.removeServerVip" // RemoveVIP 单服务器移除VIP
13 | AddBan string = "RSP.addServerBan" // AddBan 单服务器添加玩家进入ban列
14 | RemoveBan string = "RSP.removeServerBan" // RemoveBan 单服务器ban列移除玩家
15 | Kick string = "RSP.kickPlayer" // Kick 单服务器踢出玩家
16 | ChooseMap string = "RSP.chooseLevel" // ChooseMap 单服务器切换地图
17 | ServerDetails string = "GameServer.getFullServerDetails" // ServerDetails 单服务器完整信息查询
18 | Stats string = "Stats.detailedStatsByPersonaId" // Stats 单玩家战绩获取
19 | Weapons string = "Progression.getWeaponsByPersonaId" // Weapons 单玩家武器获取
20 | Vehicles string = "Progression.getVehiclesByPersonaId" // Vehicles 单玩家载具获取
21 | Playing string = "GameServer.getServersByPersonaIds" // Playing 多玩家正在游玩获取
22 | RecentServer string = "ServerHistory.mostRecentServers" // RecentServer 单玩家游玩服务器历史获取
23 | ServerInfo string = "GameServer.getServerDetails" // ServerInfo 单服务器游戏信息获取
24 | ServerRSP string = "RSP.getServerDetails" // ServerRSP 单服务器RSP信息获取
25 |
26 | Exchange string = "ScrapExchange.getOffers" // Exchange 交换信息获取
27 | Campaign string = "CampaignOperations.getPlayerCampaignStatus" // Campaign 行动包查询
28 | )
29 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | # This workflow uses actions that are not certified by GitHub.
2 | # They are provided by a third-party and are governed by
3 | # separate terms of service, privacy policy, and support
4 | # documentation.
5 |
6 | # This workflow lets you compile your Go project using a SLSA3 compliant builder.
7 | # This workflow will generate a so-called "provenance" file describing the steps
8 | # that were performed to generate the final binary.
9 | # The project is an initiative of the OpenSSF (openssf.org) and is developed at
10 | # https://github.com/slsa-framework/slsa-github-generator.
11 | # The provenance file can be verified using https://github.com/slsa-framework/slsa-verifier.
12 | # For more information about SLSA and how it improves the supply-chain, visit slsa.dev.
13 |
14 | name: release
15 | on:
16 | push:
17 | tags:
18 | - 'v*'
19 |
20 | jobs:
21 | # ========================================================================================================================================
22 | # Prerequesite: Create a .slsa-goreleaser.yml in the root directory of your project.
23 | # See format in https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/go/README.md#configuration-file
24 | #=========================================================================================================================================
25 | releaser:
26 | runs-on: ubuntu-latest
27 | steps:
28 | - name: Checkout
29 | uses: actions/checkout@v4
30 | with:
31 | fetch-depth: 0
32 |
33 | - name: Set up Go
34 | uses: actions/setup-go@v5
35 | with:
36 | go-version: 'stable'
37 |
38 | - name: Run GoReleaser
39 | uses: goreleaser/goreleaser-action@v6
40 | with:
41 | version: latest
42 | args: release --clean
43 | env:
44 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | linters-settings:
2 | errcheck:
3 | ignore: fmt:.*
4 | ignoretests: true
5 | forbidigo:
6 | # Forbid the following identifiers
7 | forbid:
8 | - ^fmt\.Errorf$ # consider errors.Errorf in github.com/pkg/errors
9 |
10 | linters:
11 | # please, do not use `enable-all`: it's deprecated and will be removed soon.
12 | # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
13 | disable-all: true
14 | fast: false
15 | enable:
16 | - bodyclose
17 | #- depguard
18 | - dogsled
19 | - errcheck
20 | - exportloopref
21 | - exhaustive
22 | #- funlen
23 | #- goconst
24 | - gocritic
25 | - gocyclo
26 | - gofmt
27 | - goimports
28 | - goprintffuncname
29 | #- gosec
30 | - gosimple
31 | - govet
32 | - ineffassign
33 | #- misspell
34 | - nolintlint
35 | - rowserrcheck
36 | - staticcheck
37 | - stylecheck
38 | - typecheck
39 | - unconvert
40 | - unparam
41 | - unused
42 | - whitespace
43 | - prealloc
44 | - predeclared
45 | - asciicheck
46 | - revive
47 | - forbidigo
48 | - makezero
49 |
50 | run:
51 | # default concurrency is a available CPU number.
52 | # concurrency: 4 # explicitly omit this value to fully utilize available resources.
53 | deadline: 5m
54 | issues-exit-code: 1
55 | tests: false
56 | go: '1.20'
57 |
58 | # output configuration options
59 | output:
60 | format: "colored-line-number"
61 | print-issued-lines: true
62 | print-linter-name: true
63 | uniq-by-line: true
64 |
65 | issues:
66 | # Fix found issues (if it's supported by the linter)
67 | fix: true
68 | exclude-use-default: false
69 | exclude:
70 | - "Error return value of .((os.)?std(out|err)..*|.*Close|.*Seek|.*Flush|os.Remove(All)?|.*print(f|ln)?|os.(Un)?Setenv). is not check"
71 | - 'identifier ".*" contain non-ASCII character: U\+.*'
72 |
--------------------------------------------------------------------------------
/.github/workflows/go.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a golang project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
3 |
4 | name: Bulid
5 |
6 | on: [push, pull_request,workflow_dispatch]
7 | env:
8 | BINARY_PREFIX: "BFHelper"
9 | BINARY_SUFFIX: ""
10 | COMMIT_ID: "${{ github.sha }}"
11 |
12 | jobs:
13 | build:
14 | name: Build
15 | runs-on: ubuntu-latest
16 | strategy:
17 | matrix:
18 | goos: [linux,windows,darwin]
19 | goarch: ["386",arm,arm64,amd64]
20 | # mac无需构建386和arm
21 | # windows由于libc不能构建arm
22 | exclude:
23 | - goos: darwin
24 | goarch: "386"
25 | - goos: darwin
26 | goarch: arm
27 | - goos: windows
28 | goarch: arm
29 | fail-fast: true
30 |
31 | steps:
32 | - uses: actions/checkout@v4
33 |
34 | - name: Set up Go
35 | uses: actions/setup-go@v5
36 | with:
37 | cache: true
38 | go-version: '1.22'
39 |
40 | - name: Cache Go Modules
41 | uses: actions/cache@v4
42 | with:
43 | path: ~/go/pkg/mod
44 | key: go-${{ runner.os }}-${{ hashFiles('**/go.sum') }}
45 | restore-keys: |
46 | go-${{ runner.os }}-
47 |
48 | - name: Build binary file
49 | env:
50 | GOOS: ${{ matrix.goos }}
51 | GOARCH: ${{ matrix.goarch }}
52 | IS_PR: ${{ !!github.head_ref }}
53 | # 如果是windows, 添加.exe后缀
54 | # 如果是拉取请求触发, 显示拉取请求, 不构建
55 | run: |
56 | if [ $GOOS = "windows" ]; then export BINARY_SUFFIX="$BINARY_SUFFIX.exe"; fi
57 | if $IS_PR ; then echo $PR_PROMPT; fi
58 | export BINARY_NAME="${BINARY_PREFIX}v${COMMIT_ID::5}_${GOOS}_${GOARCH}${BINARY_SUFFIX}"
59 | export CGO_ENABLED=0
60 | export LD_FLAGS="-checklinkname=0 -w -s -X github.com/KomeiDiSanXian/BFHelper/kanban/banner.Version=${COMMIT_ID::7}"
61 | go build -o "output/$BINARY_NAME" -trimpath -ldflags "$LD_FLAGS" .
62 |
63 | - name: Upload artifact
64 | uses: actions/upload-artifact@v4
65 | if: ${{ !github.head_ref }}
66 | with:
67 | name: ${{ matrix.goos }}_${{ matrix.goarch }}
68 | path: output/
--------------------------------------------------------------------------------
/bfhelper/pkg/tracer/tracer.go:
--------------------------------------------------------------------------------
1 | // Package tracer 实现链路追踪
2 | package tracer
3 |
4 | import (
5 | "context"
6 |
7 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
8 | "github.com/KomeiDiSanXian/BFHelper/kanban/banner"
9 | "go.opentelemetry.io/otel"
10 | "go.opentelemetry.io/otel/attribute"
11 | "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
12 | "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
13 | "go.opentelemetry.io/otel/sdk/resource"
14 | sdktrace "go.opentelemetry.io/otel/sdk/trace"
15 | semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
16 | "go.opentelemetry.io/otel/trace"
17 | )
18 |
19 | func newExporter(ctx context.Context, url string) (*otlptrace.Exporter, error) {
20 | opt := []otlptracehttp.Option{otlptracehttp.WithEndpoint(url)}
21 | if !global.TraceSetting.UseHTTPS {
22 | opt = append(opt, otlptracehttp.WithInsecure())
23 | }
24 | client := otlptracehttp.NewClient(opt...)
25 | return otlptrace.New(ctx, client)
26 | }
27 |
28 | func newTraceProvider(expo sdktrace.SpanExporter) (*sdktrace.TracerProvider, error) {
29 | r, err := resource.Merge(
30 | resource.Default(),
31 | resource.NewWithAttributes(
32 | semconv.SchemaURL,
33 | semconv.ServiceName("BFHelperService"),
34 | semconv.ServiceVersion(banner.Version),
35 | ),
36 | )
37 | if err != nil {
38 | return nil, err
39 | }
40 | // 总是开启追踪
41 | sampler := sdktrace.WithSampler(sdktrace.AlwaysSample())
42 | if !global.TraceSetting.Enabled {
43 | sampler = sdktrace.WithSampler(sdktrace.NeverSample())
44 | }
45 | return sdktrace.NewTracerProvider(sdktrace.WithBatcher(expo), sdktrace.WithResource(r), sampler), nil
46 | }
47 |
48 | // InstallExportPipeline 追踪导出
49 | func InstallExportPipeline(ctx context.Context, url string) (func(ctx context.Context) error, error) {
50 | expo, err := newExporter(ctx, url)
51 | if err != nil {
52 | return nil, err
53 | }
54 | tp, err := newTraceProvider(expo)
55 | if err != nil {
56 | return nil, err
57 | }
58 | otel.SetTracerProvider(tp)
59 | return tp.Shutdown, nil
60 | }
61 |
62 | // AddEventWithDescription 在span添加k-v形式的描述
63 | func AddEventWithDescription(desc ...attribute.KeyValue) trace.EventOption {
64 | return trace.WithAttributes(desc...)
65 | }
66 |
67 | // Description 返回attribute.KeyValue
68 | func Description(k, v string) attribute.KeyValue {
69 | return attribute.String(k, v)
70 | }
71 |
--------------------------------------------------------------------------------
/bfhelper/internal/errcode/code.go:
--------------------------------------------------------------------------------
1 | // Package errcode 错误码
2 | package errcode
3 |
4 | var (
5 | Success = NewError(0, "Success") // Success code 0 means success
6 | InternalError = NewError(1000, "Internal error") // InternalError code 1000 means something has gone wrong
7 | InvalidParamsError = NewError(1001, "Invalid parameters") // InvalidParamsError code 1001 means parameters are invalid
8 | NotFoundError = NewError(1002, "Not found") // NotFoundError code 1002 means we cannot find something at anywhere
9 | TimeoutError = NewError(1003, "Timeout") // TimeoutError code 1003 means operation timed out
10 |
11 | DataBaseInternalError = NewError(2000, "DataBase internal error") // DataBaseInternalError code 2000 means something has gone wrong with the database
12 | DataBaseCreateError = NewError(2001, "DataBase creation error") // DataBaseCreateError code 2001 means creating something error
13 | DataBaseUpdateError = NewError(2002, "DataBase update error") // DataBaseUpdateError code 2002 means updating something error
14 | DataBaseReadError = NewError(2003, "DataBase read error") // DataBaseReadError code 2003 means reading something error
15 | DataBaseDeleteError = NewError(2004, "DataBase delete error") // DataBaseDeleteError code 2004 means deleting something error
16 |
17 | NetworkError = NewError(3000, "Network error") // NetworkError code 3000 means something has gone wrong when doing http request
18 | ServerNotFoundError = NewError(3001, "Server not found error") // ServerNotFoundError code 3001 means we cannot find server at EA gateway
19 | InvalidAuthError = NewError(3002, "Invalid map id or invalid auth") // InvalidAuthError code 3002 means map id is invalid or invalid permission
20 | InvalidPermissionsError = NewError(3003, "Invalid permissions") // InvalidPermissionsError code 3003 means we don't have permission
21 | InvalidPlayerError = NewError(3004, "Invalid player") // InvalidPlayerError code 3004 means EA server does not have info of player
22 | ServerNotStartError = NewError(3005, "Server does not started") // ServerNotStartError code 3005 means server is not started yet
23 |
24 | Canceled = NewError(4000, "Operation canceled") // Canceled code 4000 means operation has been canceled
25 | )
26 |
--------------------------------------------------------------------------------
/bfhelper/internal/anticheat/template.html:
--------------------------------------------------------------------------------
1 |
2 |
68 | {{if .Link}}
69 | 视频链接
70 | {{end}}
71 | 
72 | {{range .Words}}
73 | {{.}}
74 | {{end}}
75 |
76 |
81 |
82 | Report By
83 | Remilia
84 |
85 |
86 |
--------------------------------------------------------------------------------
/bfhelper/server_helper.go:
--------------------------------------------------------------------------------
1 | package bfhelper
2 |
3 | import (
4 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/handler"
5 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/rule"
6 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
7 | zero "github.com/wdvxdr1123/ZeroBot"
8 | )
9 |
10 | func init() {
11 | // 群聊绑定多服务器
12 | //
13 | // 每个群聊可以绑定多个服务器, 每个服务器也可以绑定多个群聊
14 | global.Engine.OnPrefix(".创建服务器群组", zero.OnlyGroup, zero.OwnerPermission).SetBlock(true).Handle(handler.CreateGroupHandler)
15 | global.Engine.OnFullMatch(".删除服务器群组", zero.OnlyGroup, zero.OwnerPermission).SetBlock(true).Handle(handler.DeleteGroupHandler)
16 | global.Engine.OnPrefix(".更换服主", zero.OnlyGroup, rule.ServerOwnerPermission).SetBlock(true).Handle(handler.ChangeOwnerHandler)
17 | global.Engine.OnPrefix(".绑定服务器", zero.OnlyGroup, zero.SuperUserPermission).SetBlock(true).Handle(handler.AddServerHandler)
18 | global.Engine.OnPrefix(".添加管理", zero.OnlyGroup, rule.ServerOwnerPermission).SetBlock(true).Handle(handler.AddServerAdminHandler)
19 | global.Engine.OnPrefix(".设置别名", zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.SetServerAliasHandler)
20 | global.Engine.OnPrefix(".解绑服务器", zero.OnlyGroup, rule.ServerOwnerPermission).SetBlock(true).Handle(handler.DeleteServerHandler)
21 | global.Engine.OnPrefix(".删除管理", zero.OnlyGroup, rule.ServerOwnerPermission).SetBlock(true).Handle(handler.DeleteAdminHandler)
22 |
23 | global.Engine.OnPrefixGroup([]string{".踢出", ".kick", ".k"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.KickPlayerHandler)
24 | global.Engine.OnPrefixGroup([]string{".封禁", ".b"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.BanPlayerHandler)
25 | global.Engine.OnPrefixGroup([]string{".解封", ".ub"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.UnbanPlayerHandler)
26 | global.Engine.OnPrefixGroup([]string{".全封", ".bana"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.BanPlayerAtAllServerHandler)
27 | global.Engine.OnPrefixGroup([]string{".全解", ".ubana"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.UnbanPlayerAtAllServerHandler)
28 | global.Engine.OnPrefixGroup([]string{".切图", ".cm"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.ChangeMapHandler)
29 | global.Engine.OnPrefixGroup([]string{".查图", ".qm"}, zero.OnlyGroup, rule.ServerAdminPermission).SetBlock(true).Handle(handler.ReadMapsHandler)
30 | }
31 |
--------------------------------------------------------------------------------
/bfhelper/internal/dao/server.go:
--------------------------------------------------------------------------------
1 | // Package dao 服务器群组dao层操作
2 | package dao
3 |
4 | import "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/model"
5 |
6 | // CreateGroup 创建新的服务器群组
7 | func (d *Dao) CreateGroup(groupID, owner int64) error {
8 | grp := model.NewGroup(groupID)
9 | grp.Owner = owner
10 | return grp.Create(d.engine)
11 | }
12 |
13 | // DeleteGroup 删除服务器群组
14 | func (d *Dao) DeleteGroup(groupID int64) error {
15 | return model.NewGroup(groupID).DeleteByID(d.engine)
16 | }
17 |
18 | // UpdateOwner 更新服务器服主
19 | func (d *Dao) UpdateOwner(groupID, owner int64) error {
20 | grp := model.NewGroup(groupID)
21 | grp.Owner = owner
22 | return grp.Update(d.engine)
23 | }
24 |
25 | // AddGroupServer 添加服务器
26 | func (d *Dao) AddGroupServer(groupID int64, gameID, serverID, pgid, serverName string) error {
27 | srv := model.NewServer(gameID)
28 | srv.ServerID, srv.PGID, srv.ServerName = serverID, pgid, serverName
29 | grp := model.NewGroup(groupID)
30 | grp.Servers = append(grp.Servers, *srv)
31 | return grp.Update(d.engine)
32 | }
33 |
34 | // AddGroupAdmin 添加服务器管理员
35 | func (d *Dao) AddGroupAdmin(groupID int64, adminQQ ...int64) error {
36 | grp := model.NewGroup(groupID)
37 | for _, qq := range adminQQ {
38 | grp.Admins = append(grp.Admins, *model.NewAdmin(qq))
39 | }
40 | return grp.Update(d.engine)
41 | }
42 |
43 | // ServerAlias 服务器别名修改
44 | func (d *Dao) ServerAlias(gameID, alias string) error {
45 | srv := model.NewServer(gameID)
46 | srv.NameInGroup = alias
47 | return srv.Update(d.engine)
48 | }
49 |
50 | // RemoveGroupServer 移除群组服务器
51 | func (d *Dao) RemoveGroupServer(groupID int64, gameID string) error {
52 | return model.NewGroup(groupID).DeleteServer(d.engine, gameID)
53 | }
54 |
55 | // RemoveGroupAdmin 移除服务器管理员
56 | func (d *Dao) RemoveGroupAdmin(groupID, adminQQ int64) error {
57 | return model.NewGroup(groupID).DeleteAdmin(d.engine, adminQQ)
58 | }
59 |
60 | // IsServerAdmin 判断是否为服务器管理
61 | func (d *Dao) IsServerAdmin(groupID, qq int64) bool {
62 | return model.NewGroup(groupID).IsAdmin(d.engine, qq)
63 | }
64 |
65 | // IsOwner 判断是不是服务器服主
66 | func (d *Dao) IsOwner(groupID, qq int64) bool {
67 | return model.NewGroup(groupID).IsOwner(d.engine, qq)
68 | }
69 |
70 | // GetGroup 获取群组
71 | func (d *Dao) GetGroup(groupID int64) (*model.Group, error) {
72 | return model.NewGroup(groupID).GetByID(d.engine)
73 | }
74 |
75 | // GetServerByAlias 通过别名获取服务器信息
76 | func (d *Dao) GetServerByAlias(groupID int64, alias string) (*model.Server, error) {
77 | return model.NewGroup(groupID).GetByAlias(d.engine, alias)
78 | }
79 |
--------------------------------------------------------------------------------
/winres/gen/gen.go:
--------------------------------------------------------------------------------
1 | // Package main generates winres.json
2 | package main
3 |
4 | import (
5 | "fmt"
6 | "os"
7 | "os/exec"
8 | "strings"
9 | "time"
10 |
11 | "github.com/KomeiDiSanXian/BFHelper/kanban/banner"
12 | )
13 |
14 | const json = `
15 | {
16 | "RT_GROUP_ICON": {
17 | "APP": {
18 | "0000": [
19 | "icon.png",
20 | "icon16.png"
21 | ]
22 | }
23 | },
24 | "RT_MANIFEST": {
25 | "#1": {
26 | "0409": {
27 | "identity": {
28 | "name": "BFHelper",
29 | "version": "%s"
30 | },
31 | "description": "",
32 | "minimum-os": "win7",
33 | "execution-level": "as invoker",
34 | "ui-access": false,
35 | "auto-elevate": false,
36 | "dpi-awareness": "system",
37 | "disable-theming": false,
38 | "disable-window-filtering": false,
39 | "high-resolution-scrolling-aware": false,
40 | "ultra-high-resolution-scrolling-aware": false,
41 | "long-path-aware": false,
42 | "printer-driver-isolation": false,
43 | "gdi-scaling": false,
44 | "segment-heap": false,
45 | "use-common-controls-v6": false
46 | }
47 | }
48 | },
49 | "RT_VERSION": {
50 | "#1": {
51 | "0000": {
52 | "fixed": {
53 | "file_version": "%s",
54 | "product_version": "%s",
55 | "timestamp": "%s"
56 | },
57 | "info": {
58 | "0409": {
59 | "Comments": "OneBot plugin based on ZeroBot",
60 | "CompanyName": "FloatTech",
61 | "FileDescription": "https://github.com/KomeiDiSanXian/BFHelper",
62 | "FileVersion": "%s",
63 | "InternalName": "",
64 | "LegalCopyright": "%s",
65 | "LegalTrademarks": "",
66 | "OriginalFilename": "BFHelper.exe",
67 | "PrivateBuild": "",
68 | "ProductName": "BFHelper",
69 | "ProductVersion": "%s",
70 | "SpecialBuild": ""
71 | }
72 | }
73 | }
74 | }
75 | }
76 | }
77 | `
78 | const timeformat = `2006-01-02T15:04:05+08:00`
79 |
80 | func main() {
81 | f, err := os.Create("winres.json")
82 | if err != nil {
83 | panic(err)
84 | }
85 | defer f.Close()
86 | i := strings.LastIndex(banner.Version, "-")
87 | if i <= 0 {
88 | i = len(banner.Version)
89 | }
90 | commitcnt := strings.Builder{}
91 | commitcnt.WriteString(banner.Version[1:i])
92 | commitcnt.WriteByte('.')
93 | commitcntcmd := exec.Command("git", "rev-list", "--count", "HEAD")
94 | commitcntcmd.Stdout = &commitcnt
95 | err = commitcntcmd.Run()
96 | if err != nil {
97 | panic(err)
98 | }
99 | fv := commitcnt.String()[:commitcnt.Len()-1]
100 | _, err = fmt.Fprintf(f, json, fv, fv, banner.Version, time.Now().Format(timeformat), fv, banner.Copyright+". All Rights Reserved.", banner.Version)
101 | if err != nil {
102 | panic(err)
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/bfhelper/internal/handler/player.go:
--------------------------------------------------------------------------------
1 | // Package handler 事件处理函数
2 | package handler
3 |
4 | import (
5 | "context"
6 | "reflect"
7 | "runtime"
8 |
9 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/errcode"
10 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/service"
11 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
12 | "github.com/pkg/errors"
13 | "github.com/sirupsen/logrus"
14 | zero "github.com/wdvxdr1123/ZeroBot"
15 | "go.opentelemetry.io/otel/codes"
16 | )
17 |
18 | // GenericHandler 通用处理封装
19 | func GenericHandler(zctx *zero.Ctx, serviceMethod func(context.Context, *service.Service) error) {
20 | svc := service.New(zctx)
21 | funcName := runtime.FuncForPC(reflect.ValueOf(serviceMethod).Pointer()).Name()
22 | nCtx, span := global.Tracer.Start(context.Background(), "Handler")
23 | err := serviceMethod(nCtx, svc)
24 | defer span.End()
25 |
26 | if errors.Is(err, errcode.Success) || errors.Is(err, errcode.Canceled) {
27 | span.SetStatus(codes.Ok, "")
28 | return
29 | }
30 | logrus.Errorf("%s error: %v", funcName, err)
31 | svc.Log().Error(err)
32 | span.SetStatus(codes.Error, "received error")
33 | span.RecordError(err)
34 | }
35 |
36 | // BindAccountHandler 绑定账号处理函数
37 | func BindAccountHandler(zctx *zero.Ctx) {
38 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
39 | return svc.BindAccount(ctx)
40 | })
41 | }
42 |
43 | // PlayerRecentHandler 最近战绩查询处理函数
44 | func PlayerRecentHandler(zctx *zero.Ctx) {
45 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
46 | return svc.GetPlayerRecent(ctx)
47 | })
48 | }
49 |
50 | // PlayerStatsHandler 玩家战绩查询处理函数
51 | func PlayerStatsHandler(zctx *zero.Ctx) {
52 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
53 | return svc.GetPlayerStats(ctx)
54 | })
55 | }
56 |
57 | // PlayerWeaponHandler 玩家武器查询处理函数
58 | func PlayerWeaponHandler(zctx *zero.Ctx) {
59 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
60 | return svc.GetPlayerWeapon(ctx)
61 | })
62 | }
63 |
64 | // PlayerVehicleHandler 玩家载具查询处理函数
65 | func PlayerVehicleHandler(zctx *zero.Ctx) {
66 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
67 | return svc.GetPlayerVehicle(ctx)
68 | })
69 | }
70 |
71 | // BF1ExchangeHandler 获取战地一本期交换处理函数
72 | func BF1ExchangeHandler(zctx *zero.Ctx) {
73 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
74 | return svc.GetBF1Exchange(ctx)
75 | })
76 | }
77 |
78 | // BF1OpreationPackHandler 获取战地一本期行动包处理函数
79 | func BF1OpreationPackHandler(zctx *zero.Ctx) {
80 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
81 | return svc.GetBF1OpreationPack(ctx)
82 | })
83 | }
84 |
85 | // PlayerBanInfoHandler 获取玩家联ban信息
86 | func PlayerBanInfoHandler(zctx *zero.Ctx) {
87 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
88 | return svc.GetPlayerBanInfo(ctx)
89 | })
90 | }
91 |
--------------------------------------------------------------------------------
/bfhelper/internal/bf1/server/server.go:
--------------------------------------------------------------------------------
1 | // Package server 战地1服务器操作
2 | package server
3 |
4 | import (
5 | "errors"
6 | "fmt"
7 |
8 | bf1api "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/bf1/api"
9 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
10 | bf1reqbody "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/netreq/bf1"
11 | "github.com/tidwall/gjson"
12 | )
13 |
14 | // Map 服务器地图
15 | type Map struct {
16 | Name string
17 | Mode string
18 | }
19 |
20 | // Kick player, reason needs BIG5, return reason and err
21 | func Kick(gameID, pid, reason string) (string, error) {
22 | reason = fmt.Sprintf("%s%s", "Remi:", reason)
23 | if len(reason) > 32 {
24 | return "", errors.New("理由过长")
25 | }
26 | post := bf1reqbody.NewPostKick(pid, gameID, reason)
27 | data, err := bf1api.ReturnJSON(global.NativeAPI, "POST", post)
28 | if err != nil {
29 | return "", err
30 | }
31 | return data.Get("result.reason").Str, err
32 | }
33 |
34 | // Ban player, check returned id
35 | func Ban(serverID, pid string) error {
36 | post := bf1reqbody.NewPostBan(pid, serverID)
37 | data, err := bf1api.ReturnJSON(global.NativeAPI, "POST", post)
38 | if err != nil {
39 | return err
40 | }
41 | if data.Get("id").Str == "" {
42 | return errors.New("服务器未发出正确的响应,请稍后再试")
43 | }
44 | return nil
45 | }
46 |
47 | // Unban player
48 | func Unban(serverID, pid string) error {
49 | post := bf1reqbody.NewPostRemoveBan(pid, serverID)
50 | data, err := bf1api.ReturnJSON(global.NativeAPI, "POST", post)
51 | if err != nil {
52 | return err
53 | }
54 | if data.Get("id").Str == "" {
55 | return errors.New("服务器未发出正确的响应,请稍后再试")
56 | }
57 | return nil
58 | }
59 |
60 | // ChangeMap will change the map for players
61 | func ChangeMap(pgid string, index int) error {
62 | post := bf1reqbody.NewPostChangeMap(pgid, index)
63 | data, err := bf1api.ReturnJSON(global.NativeAPI, "POST", post)
64 | if err != nil {
65 | return err
66 | }
67 | if data.Get("id").Str == "" {
68 | return errors.New("服务器未发出正确的响应,请稍后再试")
69 | }
70 | return nil
71 | }
72 |
73 | func mapRequest(gameID string) ([]gjson.Result, error) {
74 | post := bf1reqbody.NewPostGetServerInfo(gameID)
75 | data, err := bf1api.ReturnJSON(global.NativeAPI, "POST", post)
76 | if err != nil {
77 | return nil, err
78 | }
79 | if data.Get("result").String() == "" {
80 | return nil, errors.New("服务器gameid可能无效,请更新服务器信息")
81 | }
82 | result := data.Get("result.rotation").Array()
83 | if result == nil {
84 | return nil, errors.New("获取到的地图池为空")
85 | }
86 | return result, nil
87 | }
88 |
89 | // GetMapSlice returns map slice
90 | func GetMapSlice(gameID string) ([]*Map, error) {
91 | result, err := mapRequest(gameID)
92 | if err != nil {
93 | return nil, err
94 | }
95 |
96 | mp := make([]*Map, 0, len(result))
97 | for _, v := range result {
98 | m := &Map{Name: v.Get("mapPrettyName").Str, Mode: v.Get("modePrettyName").Str}
99 | mp = append(mp, m)
100 | }
101 | return mp, nil
102 | }
103 |
--------------------------------------------------------------------------------
/bfhelper/internal/anticheat/bfeac.go:
--------------------------------------------------------------------------------
1 | // Package anticheat BFEAC相关
2 | package anticheat
3 |
4 | import (
5 | "bytes"
6 | _ "embed"
7 | "encoding/json"
8 | "fmt"
9 | "html/template"
10 | "net/http"
11 | "time"
12 |
13 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
14 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/netreq"
15 | )
16 |
17 | // HackEACResp 返回案件信息
18 | type HackEACResp struct {
19 | URL string
20 | Status string
21 | }
22 |
23 | // EACHackerStatus BFEAC 举报状态
24 | var EACHackerStatus = map[int]string{
25 | 0: "正在处理",
26 | 1: "实锤",
27 | 2: "证据不足",
28 | 3: "自证通过",
29 | 4: "自证中",
30 | 5: "刷枪",
31 | }
32 |
33 | // ReportHTML 举报html模板
34 | //
35 | //go:embed template.html
36 | var ReportHTML string
37 |
38 | // Report 举报信息
39 | type Report struct {
40 | Target string `json:"target_EAID"`
41 | Body string `json:"case_body"`
42 | GameType int `json:"game_type"`
43 | UploadBy Reporter `json:"report_by"`
44 | }
45 |
46 | // Reporter 举报人信息
47 | type Reporter struct {
48 | Platform string `json:"report_platform"`
49 | UserID int64 `json:"user_id"`
50 | Timestamp int64
51 | Details map[string]any
52 | }
53 |
54 | // ReportBody 用于举报上传的html模板
55 | type ReportBody struct {
56 | Link string
57 | ImageURL string
58 | Words []string
59 | SelfID int64
60 | }
61 |
62 | // NewBF1Report 生成一个bf1举报信息
63 | func NewBF1Report(susName string, body ReportBody) (*Report, error) {
64 | tmplObj := template.Must(template.New("report").Parse(ReportHTML))
65 | var buf bytes.Buffer
66 |
67 | err := tmplObj.Execute(&buf, body)
68 | if err != nil {
69 | return nil, err
70 | }
71 | return &Report{
72 | Target: susName,
73 | Body: buf.String(),
74 | GameType: 1,
75 | }, nil
76 | }
77 |
78 | // NewReporter 生成举报人信息
79 | func NewReporter(userID int64) *Reporter {
80 | return &Reporter{
81 | Platform: "qq",
82 | UserID: userID,
83 | Timestamp: time.Now().Unix(),
84 | Details: make(map[string]any),
85 | }
86 | }
87 |
88 | // WithDetails 给举报人添加更多信息
89 | func (r *Reporter) WithDetails(detail map[string]any) *Reporter {
90 | rr := *r
91 | rr.Details = r.Details
92 | for k, v := range detail {
93 | rr.Details[k] = v
94 | }
95 | return &rr
96 | }
97 |
98 | // WithReporter 附加上举报人信息
99 | func (r *Report) WithReporter(reporter *Reporter) Report {
100 | r.UploadBy = *reporter
101 | return *r
102 | }
103 |
104 | // UploadReport 用户进行举报
105 | func (r Report) UploadReport() error {
106 | jsonData, err := json.Marshal(r)
107 | if err != nil {
108 | return err
109 | }
110 | data, err := netreq.Request{
111 | Method: http.MethodPost,
112 | URL: global.BFEAC + "inner_api/case_report",
113 | Header: map[string]string{
114 | "Content-Type": "application/json",
115 | "apikey": global.BFEACSetting.APIKey,
116 | },
117 | Body: bytes.NewReader(jsonData),
118 | }.GetRespBodyJSON()
119 | if err != nil {
120 | return err
121 | }
122 | // TODO: 等eac 新后端再做解析
123 | fmt.Println(data.Map())
124 | return nil
125 | }
126 |
--------------------------------------------------------------------------------
/bfhelper/internal/bf1/player/structs.go:
--------------------------------------------------------------------------------
1 | // Package player 战地相关战绩查询结构体
2 | package player
3 |
4 | // 武器种类
5 | const (
6 | ALL string = "ALL"
7 | Elite string = "ID_P_CAT_FIELDKIT" // 精英兵
8 | LMG string = "ID_P_CAT_LMG" // 轻机枪
9 | Melee string = "ID_P_CAT_MELEE" // 近战武器
10 | Gadget string = "ID_P_CAT_GADGET" // 配备
11 | Semi string = "ID_P_CAT_SEMI" // 半自动
12 | Grenade string = "ID_P_CAT_GRENADE" // 手榴弹
13 | SIR string = "ID_P_CAT_SIR" // 制式步枪
14 | Shotgun string = "ID_P_CAT_SHOTGUN" // 霰弹枪
15 | Dirver string = "ID_P_CAT_VEHICLEKITWEAPON" // 驾驶员
16 | SMG string = "ID_P_CAT_SMG" // 冲锋枪
17 | Sidearm string = "ID_P_CAT_SIDEARM" // 手枪
18 | Bolt string = "ID_P_CAT_BOLT" // 步枪
19 | )
20 |
21 | // WeaponSort Weapons数组
22 | type WeaponSort []Weapons
23 |
24 | // VehicleSort Vehicles数组
25 | type VehicleSort []Vehicle
26 |
27 | // Len 获取长度
28 | func (a WeaponSort) Len() int { return len(a) }
29 |
30 | // Swap 交换
31 | func (a WeaponSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
32 |
33 | // Less 比较
34 | func (a WeaponSort) Less(i, j int) bool { return a[i].Kills > a[j].Kills }
35 |
36 | // Len 获取长度
37 | func (a VehicleSort) Len() int { return len(a) }
38 |
39 | // Swap 交换
40 | func (a VehicleSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
41 |
42 | // Less 比较
43 | func (a VehicleSort) Less(i, j int) bool { return a[i].Kills > a[j].Kills }
44 |
45 | // Stat 战绩
46 | type Stat struct {
47 | SPM string
48 | TotalKD string
49 | WinPercent string
50 | KillsPerGame string
51 | Kills string
52 | Deaths string
53 | KPM string
54 | Losses string
55 | Wins string
56 | InfantryKills string
57 | InfantryKPM string
58 | InfantryKD string
59 | VehicleKills string
60 | VehicleKPM string
61 | Rank string
62 | TimePlayed string
63 | MVP string
64 | Accuracy string
65 | DogtagsTaken string
66 | Headshots string
67 | HighestKillStreak string
68 | LongestHeadshot string
69 | Revives string
70 | }
71 |
72 | // Weapons 武器
73 | type Weapons struct {
74 | Name string
75 | Kills float64
76 | Accuracy string
77 | KPM string
78 | Headshots string
79 | Efficiency string
80 | }
81 |
82 | // Recent 最近战绩
83 | type Recent []struct {
84 | Server string `json:"server"`
85 | Map string `json:"map"`
86 | Mode string `json:"mode"`
87 | Date int64 `json:"date"`
88 | Score int `json:"score"`
89 | Kill int `json:"kill"`
90 | Death int `json:"death"`
91 | Kd float64 `json:"kd"`
92 | Kpm float64 `json:"kpm"`
93 | Accuracy float64 `json:"accuracy"`
94 | Time int `json:"time"`
95 | }
96 |
97 | // Vehicle 载具
98 | type Vehicle struct {
99 | Name string
100 | Kills float64
101 | Destroyed float64
102 | KPM string
103 | Time string
104 | }
105 |
--------------------------------------------------------------------------------
/bfhelper/internal/handler/server.go:
--------------------------------------------------------------------------------
1 | package handler
2 |
3 | import (
4 | "context"
5 |
6 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/service"
7 | zero "github.com/wdvxdr1123/ZeroBot"
8 | )
9 |
10 | // CreateGroupHandler 创建服务器群组处理函数
11 | func CreateGroupHandler(zctx *zero.Ctx) {
12 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
13 | return svc.CreateGroup()
14 | })
15 | }
16 |
17 | // DeleteGroupHandler 所在群删除服务器群组处理函数
18 | func DeleteGroupHandler(zctx *zero.Ctx) {
19 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
20 | return svc.DeleteGroup()
21 | })
22 | }
23 |
24 | // ChangeOwnerHandler 更换服务器群组所有人处理函数
25 | func ChangeOwnerHandler(zctx *zero.Ctx) {
26 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
27 | return svc.ChangeOwner()
28 | })
29 | }
30 |
31 | // AddServerHandler 添加服务器处理函数
32 | func AddServerHandler(zctx *zero.Ctx) {
33 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
34 | return svc.AddServer()
35 | })
36 | }
37 |
38 | // AddServerAdminHandler 添加服务器管理员
39 | func AddServerAdminHandler(zctx *zero.Ctx) {
40 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
41 | return svc.AddServerAdmin()
42 | })
43 | }
44 |
45 | // SetServerAliasHandler 设置服务器别名
46 | func SetServerAliasHandler(zctx *zero.Ctx) {
47 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
48 | return svc.SetServerAlias()
49 | })
50 | }
51 |
52 | // DeleteServerHandler 删除服务器处理函数
53 | func DeleteServerHandler(zctx *zero.Ctx) {
54 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
55 | return svc.DeleteServer()
56 | })
57 | }
58 |
59 | // DeleteAdminHandler 删除群组服务器管理员
60 | func DeleteAdminHandler(zctx *zero.Ctx) {
61 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
62 | return svc.DeleteAdmin()
63 | })
64 | }
65 |
66 | // KickPlayerHandler 踢出玩家处理
67 | func KickPlayerHandler(zctx *zero.Ctx) {
68 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
69 | return svc.KickPlayer(ctx)
70 | })
71 | }
72 |
73 | // BanPlayerHandler 单服务器封禁玩家处理
74 | func BanPlayerHandler(zctx *zero.Ctx) {
75 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
76 | return svc.BanPlayer(ctx)
77 | })
78 | }
79 |
80 | // BanPlayerAtAllServerHandler 已绑定服务器封禁玩家
81 | func BanPlayerAtAllServerHandler(zctx *zero.Ctx) {
82 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
83 | return svc.BanPlayerAtAllServer(ctx)
84 | })
85 | }
86 |
87 | // UnbanPlayerHandler 单服务器解封玩家处理
88 | func UnbanPlayerHandler(zctx *zero.Ctx) {
89 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
90 | return svc.UnbanPlayer(ctx)
91 | })
92 | }
93 |
94 | // UnbanPlayerAtAllServerHandler 已绑定服务器解封玩家
95 | func UnbanPlayerAtAllServerHandler(zctx *zero.Ctx) {
96 | GenericHandler(zctx, func(ctx context.Context, svc *service.Service) error {
97 | return svc.UnbanPlayerAtAllServer(ctx)
98 | })
99 | }
100 |
101 | // ChangeMapHandler 切换地图处理
102 | func ChangeMapHandler(zctx *zero.Ctx) {
103 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
104 | return svc.ChangeMap()
105 | })
106 | }
107 |
108 | // ReadMapsHandler 查看地图池处理函数
109 | func ReadMapsHandler(zctx *zero.Ctx) {
110 | GenericHandler(zctx, func(_ context.Context, svc *service.Service) error {
111 | return svc.GetMap()
112 | })
113 | }
114 |
--------------------------------------------------------------------------------
/bfhelper/internal/rule/rule.go:
--------------------------------------------------------------------------------
1 | // Package rule 命令触发条件
2 | package rule
3 |
4 | import (
5 | "context"
6 | _ "embed"
7 | "encoding/json"
8 | "io"
9 | "log"
10 | "os"
11 | "os/signal"
12 | "strings"
13 |
14 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/dao"
15 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/model"
16 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
17 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/logger"
18 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/setting"
19 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/tracer"
20 | "github.com/sirupsen/logrus"
21 | zero "github.com/wdvxdr1123/ZeroBot"
22 | "gopkg.in/natefinch/lumberjack.v2"
23 | )
24 |
25 | //go:embed template.yml
26 | var defaultConfig string
27 |
28 | //go:embed dic.json
29 | var traditionalChinese string
30 |
31 | func init() {
32 | dbname := global.Engine.DataFolder() + "battlefield.db"
33 | err := model.Init(dbname)
34 | if err != nil {
35 | logrus.Fatalf("Failed to initialize database: %v", err)
36 | }
37 | global.DB, err = model.Open(dbname)
38 | if err != nil {
39 | logrus.Fatalf("Failed to open database: %v", err)
40 | }
41 | if err := setupSetting(); err != nil {
42 | generateConfig()
43 | os.Exit(1)
44 | }
45 | // 读字典
46 | err = readDictionary()
47 | if err != nil {
48 | logrus.Errorf("read dictionary: %v", err)
49 | }
50 |
51 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
52 | shutdown, err := tracer.InstallExportPipeline(ctx, global.TraceSetting.URL)
53 | if err != nil {
54 | logrus.Error(err)
55 | return
56 | }
57 | go func() {
58 | <-ctx.Done()
59 | stop()
60 | _ = shutdown(context.Background())
61 | }()
62 | }
63 |
64 | func setupSetting() error {
65 | settings, err := setting.NewSetting("settings", global.Engine.DataFolder())
66 | if err != nil {
67 | return err
68 | }
69 | if err := settings.ReadSection("Account", &global.AccountSetting); err != nil {
70 | return err
71 | }
72 | if err := settings.ReadSection("BFEAC", &global.BFEACSetting); err != nil {
73 | return err
74 | }
75 | if err := settings.ReadSection("Trace", &global.TraceSetting); err != nil {
76 | return err
77 | }
78 | setupLogger()
79 | return settings.ReadSection("SakuraKooi", &global.SessionAPISetting)
80 | }
81 |
82 | func setupLogger() {
83 | fileName := global.Engine.DataFolder() + "/log/bfhelper.log"
84 | global.Logger = logger.NewLogger(&lumberjack.Logger{
85 | Filename: fileName,
86 | MaxSize: 1024, // 最大为1G
87 | MaxAge: 10, // 日志保存10天
88 | LocalTime: true,
89 | }, "", log.LstdFlags)
90 | }
91 |
92 | func readDictionary() error {
93 | content, err := io.ReadAll(strings.NewReader(traditionalChinese))
94 | if err != nil {
95 | return err
96 | }
97 | err = json.Unmarshal(content, &global.Dictionary)
98 | if err != nil {
99 | return err
100 | }
101 | return nil
102 | }
103 |
104 | func generateConfig() {
105 | logrus.Warnln("[battlefield]未找到配置或者出现错误, 正在重新生成...")
106 | _ = os.WriteFile(global.Engine.DataFolder()+"settings.yml", []byte(defaultConfig), 0o644)
107 | logrus.Warnln("配置已生成! 请修改 settings.yml")
108 | }
109 |
110 | // ServerAdminPermission 是否拥有权限
111 | func ServerAdminPermission(ctx *zero.Ctx) bool {
112 | if zero.AdminPermission(ctx) {
113 | return true
114 | }
115 | return dao.New(global.DB).IsServerAdmin(ctx.Event.GroupID, ctx.Event.UserID)
116 | }
117 |
118 | // ServerOwnerPermission 腐竹权限
119 | func ServerOwnerPermission(ctx *zero.Ctx) bool {
120 | if zero.OwnerPermission(ctx) {
121 | return true
122 | }
123 | return dao.New(global.DB).IsOwner(ctx.Event.GroupID, ctx.Event.UserID)
124 | }
125 |
--------------------------------------------------------------------------------
/console/console_windows.go:
--------------------------------------------------------------------------------
1 | // Package console sets console's behavior on init
2 | package console
3 |
4 | import (
5 | "bytes"
6 | "os"
7 | "strings"
8 | "syscall"
9 | "unsafe"
10 |
11 | "golang.org/x/sys/windows"
12 |
13 | "github.com/KomeiDiSanXian/BFHelper/kanban/banner"
14 | "github.com/sirupsen/logrus"
15 | )
16 |
17 | var (
18 | //go:linkname modkernel32 golang.org/x/sys/windows.modkernel32
19 | modkernel32 *windows.LazyDLL
20 | procSetConsoleTitle = modkernel32.NewProc("SetConsoleTitleW")
21 | )
22 |
23 | //go:linkname errnoErr golang.org/x/sys/windows.errnoErr
24 | func errnoErr(e syscall.Errno) error
25 |
26 | func setConsoleTitle(title string) (err error) {
27 | var p0 *uint16
28 | p0, err = syscall.UTF16PtrFromString(title)
29 | if err != nil {
30 | return
31 | }
32 | r1, _, e1 := syscall.SyscallN(procSetConsoleTitle.Addr(), uintptr(unsafe.Pointer(p0)))
33 | if r1 == 0 {
34 | err = errnoErr(e1)
35 | }
36 | return
37 | }
38 |
39 | func init() {
40 | stdin := windows.Handle(os.Stdin.Fd())
41 |
42 | var mode uint32
43 | err := windows.GetConsoleMode(stdin, &mode)
44 | if err != nil {
45 | panic(err)
46 | }
47 |
48 | mode &^= windows.ENABLE_QUICK_EDIT_MODE // 禁用快速编辑模式
49 | mode |= windows.ENABLE_EXTENDED_FLAGS // 启用扩展标志
50 |
51 | mode &^= windows.ENABLE_MOUSE_INPUT // 禁用鼠标输入
52 | mode |= windows.ENABLE_PROCESSED_INPUT // 启用控制输入
53 |
54 | mode &^= windows.ENABLE_INSERT_MODE // 禁用插入模式
55 | mode |= windows.ENABLE_ECHO_INPUT | windows.ENABLE_LINE_INPUT // 启用输入回显&逐行输入
56 |
57 | mode &^= windows.ENABLE_WINDOW_INPUT // 禁用窗口输入
58 | mode &^= windows.ENABLE_VIRTUAL_TERMINAL_INPUT // 禁用虚拟终端输入
59 |
60 | err = windows.SetConsoleMode(stdin, mode)
61 | if err != nil {
62 | panic(err)
63 | }
64 |
65 | stdout := windows.Handle(os.Stdout.Fd())
66 | err = windows.GetConsoleMode(stdout, &mode)
67 | if err != nil {
68 | panic(err)
69 | }
70 |
71 | mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING // 启用虚拟终端处理
72 | mode |= windows.ENABLE_PROCESSED_OUTPUT // 启用处理后的输出
73 |
74 | err = windows.SetConsoleMode(stdout, mode)
75 | // windows 带颜色 log 自定义格式
76 | logrus.SetFormatter(&logFormat{hasColor: err == nil})
77 | if err != nil {
78 | logrus.Warnln("VT100设置失败, 将以无色模式输出")
79 | }
80 |
81 | err = setConsoleTitle("RemiliaBot " + banner.Version + " " + banner.Copyright)
82 | if err != nil {
83 | panic(err)
84 | }
85 | }
86 |
87 | const (
88 | colorCodePanic = "\x1b[1;31m" // color.Style{color.Bold, color.Red}.String()
89 | colorCodeFatal = "\x1b[1;31m" // color.Style{color.Bold, color.Red}.String()
90 | colorCodeError = "\x1b[31m" // color.Style{color.Red}.String()
91 | colorCodeWarn = "\x1b[33m" // color.Style{color.Yellow}.String()
92 | colorCodeInfo = "\x1b[37m" // color.Style{color.White}.String()
93 | colorCodeDebug = "\x1b[32m" // color.Style{color.Green}.String()
94 | colorCodeTrace = "\x1b[36m" // color.Style{color.Cyan}.String()
95 | colorReset = "\x1b[0m"
96 | )
97 |
98 | // logFormat specialize for zbp
99 | type logFormat struct {
100 | hasColor bool
101 | }
102 |
103 | // Format implements logrus.Formatter
104 | func (f logFormat) Format(entry *logrus.Entry) ([]byte, error) {
105 | buf := new(bytes.Buffer)
106 |
107 | buf.WriteByte('[')
108 | if f.hasColor {
109 | buf.WriteString(getLogLevelColorCode(entry.Level))
110 | }
111 | buf.WriteString(strings.ToUpper(entry.Level.String()))
112 | if f.hasColor {
113 | buf.WriteString(colorReset)
114 | }
115 | buf.WriteString("] ")
116 | buf.WriteString(entry.Message)
117 | buf.WriteString(" \n")
118 |
119 | return buf.Bytes(), nil
120 | }
121 |
122 | // getLogLevelColorCode 获取日志等级对应色彩code
123 | func getLogLevelColorCode(level logrus.Level) string {
124 | switch level {
125 | case logrus.PanicLevel:
126 | return colorCodePanic
127 | case logrus.FatalLevel:
128 | return colorCodeFatal
129 | case logrus.ErrorLevel:
130 | return colorCodeError
131 | case logrus.WarnLevel:
132 | return colorCodeWarn
133 | case logrus.InfoLevel:
134 | return colorCodeInfo
135 | case logrus.DebugLevel:
136 | return colorCodeDebug
137 | case logrus.TraceLevel:
138 | return colorCodeTrace
139 |
140 | default:
141 | return colorCodeInfo
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/bfhelper/pkg/netreq/bf1/body.go:
--------------------------------------------------------------------------------
1 | // Package bf1reqbody 战地服务器操作请求body
2 | package bf1reqbody
3 |
4 | import (
5 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
6 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/uuid"
7 | )
8 |
9 | // Post 结构体
10 | type Post struct {
11 | Jsonrpc string `json:"jsonrpc"`
12 | Method string `json:"method"`
13 | Params Param `json:"params"`
14 | ID string `json:"id"`
15 | }
16 |
17 | // Param parameters
18 | type Param struct {
19 | Game string `json:"game"`
20 | PersonaID string `json:"personaId"`
21 | PersonaIDs []string `json:"personaIds"`
22 | GameID string `json:"gameId"`
23 | ServerID string `json:"serverId"`
24 | PGid string `json:"persistedGameId"`
25 | LevelIndex int `json:"levelIndex"`
26 | Reason string `json:"reason"`
27 | }
28 |
29 | // NewPostKick 踢出游戏
30 | func NewPostKick(pid, gid, reason string) *Post {
31 | return &Post{
32 | Jsonrpc: "2.0",
33 | Method: global.Kick,
34 | Params: Param{
35 | Game: global.BF1,
36 | PersonaID: pid,
37 | GameID: gid,
38 | Reason: reason,
39 | },
40 | ID: uuid.NewUUID(),
41 | }
42 | }
43 |
44 | // NewPostBan 服务器封禁
45 | func NewPostBan(pid, sid string) *Post {
46 | return &Post{
47 | Jsonrpc: "2.0",
48 | Method: global.AddBan,
49 | Params: Param{
50 | Game: global.BF1,
51 | PersonaID: pid,
52 | ServerID: sid,
53 | },
54 | ID: uuid.NewUUID(),
55 | }
56 | }
57 |
58 | // NewPostRemoveBan 服务器解封
59 | func NewPostRemoveBan(pid, sid string) *Post {
60 | return &Post{
61 | Jsonrpc: "2.0",
62 | Method: global.RemoveBan,
63 | Params: Param{
64 | Game: global.BF1,
65 | PersonaID: pid,
66 | ServerID: sid,
67 | },
68 | ID: uuid.NewUUID(),
69 | }
70 | }
71 |
72 | // NewPostChangeMap 换图
73 | func NewPostChangeMap(pgid string, index int) *Post {
74 | return &Post{
75 | Jsonrpc: "2.0",
76 | Method: global.ChooseMap,
77 | Params: Param{
78 | Game: global.BF1,
79 | PGid: pgid,
80 | LevelIndex: index,
81 | },
82 | ID: uuid.NewUUID(),
83 | }
84 | }
85 |
86 | // NewPostGetServerDetails 获取完整服务器信息
87 | func NewPostGetServerDetails(gid string) *Post {
88 | return &Post{
89 | Jsonrpc: "2.0",
90 | Method: global.ServerDetails,
91 | Params: Param{
92 | Game: global.BF1,
93 | GameID: gid,
94 | },
95 | ID: uuid.NewUUID(),
96 | }
97 | }
98 |
99 | // NewPostGetServerInfo 获取服务器部分信息
100 | func NewPostGetServerInfo(gid string) *Post {
101 | return &Post{
102 | Jsonrpc: "2.0",
103 | Method: global.ServerInfo,
104 | Params: Param{
105 | Game: global.BF1,
106 | GameID: gid,
107 | },
108 | ID: uuid.NewUUID(),
109 | }
110 | }
111 |
112 | // NewPostRSPInfo 获取服务器rsp信息
113 | func NewPostRSPInfo(sid string) *Post {
114 | return &Post{
115 | Jsonrpc: "2.0",
116 | Method: global.ServerRSP,
117 | Params: Param{
118 | Game: global.BF1,
119 | ServerID: sid,
120 | },
121 | ID: uuid.NewUUID(),
122 | }
123 | }
124 |
125 | // NewPostWeapon 武器结构体
126 | func NewPostWeapon(pid string) *Post {
127 | return &Post{
128 | Jsonrpc: "2.0",
129 | Method: global.Weapons,
130 | Params: Param{
131 | Game: global.BF1,
132 | PersonaID: pid,
133 | },
134 | ID: uuid.NewUUID(),
135 | }
136 | }
137 |
138 | // NewPostVehicle 载具结构体
139 | func NewPostVehicle(pid string) *Post {
140 | return &Post{
141 | Jsonrpc: "2.0",
142 | Method: global.Vehicles,
143 | Params: Param{
144 | Game: global.BF1,
145 | PersonaID: pid,
146 | },
147 | ID: uuid.NewUUID(),
148 | }
149 | }
150 |
151 | // NewPostRecent 最近游玩的服务器
152 | func NewPostRecent(pid string) *Post {
153 | return &Post{
154 | Jsonrpc: "2.0",
155 | Method: global.RecentServer,
156 | Params: Param{
157 | Game: global.BF1,
158 | PersonaID: pid,
159 | },
160 | ID: uuid.NewUUID(),
161 | }
162 | }
163 |
164 | // NewPostPlaying 正在游玩
165 | func NewPostPlaying(pid string) *Post {
166 | return &Post{
167 | Jsonrpc: "2.0",
168 | Method: global.Playing,
169 | Params: Param{
170 | Game: global.BF1,
171 | PersonaIDs: []string{pid},
172 | },
173 | ID: uuid.NewUUID(),
174 | }
175 | }
176 |
177 | // NewPostStats 战绩
178 | func NewPostStats(pid string) *Post {
179 | return &Post{
180 | Jsonrpc: "2.0",
181 | Method: global.Stats,
182 | Params: Param{
183 | Game: global.BF1,
184 | PersonaID: pid,
185 | },
186 | ID: uuid.NewUUID(),
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/KomeiDiSanXian/BFHelper
2 |
3 | go 1.23.0
4 |
5 | toolchain go1.24.1
6 |
7 | require (
8 | github.com/FloatTech/zbpctrl v1.7.0
9 | github.com/FloatTech/zbputils v1.7.1
10 | github.com/jinzhu/gorm v1.9.16
11 | github.com/sirupsen/logrus v1.9.3
12 | github.com/tidwall/gjson v1.18.0
13 | github.com/wdvxdr1123/ZeroBot v1.8.1
14 | go.opentelemetry.io/otel v1.36.0
15 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.36.0
16 | go.opentelemetry.io/otel/sdk v1.36.0
17 | go.opentelemetry.io/otel/trace v1.36.0
18 | )
19 |
20 | require (
21 | github.com/RomiChan/websocket v1.4.3-0.20220227141055-9b2c6168c9c5 // indirect
22 | github.com/boombuler/barcode v1.0.1 // indirect
23 | github.com/cenkalti/backoff/v5 v5.0.2 // indirect
24 | github.com/dustin/go-humanize v1.0.1 // indirect
25 | github.com/fumiama/terasu v0.0.0-20240507144117-547a591149c0 // indirect
26 | github.com/go-logr/logr v1.4.2 // indirect
27 | github.com/go-logr/stdr v1.2.2 // indirect
28 | github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
29 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect
30 | github.com/mattn/go-sqlite3 v1.14.22 // indirect
31 | github.com/ncruces/go-strftime v0.1.9 // indirect
32 | github.com/sagikazarmark/locafero v0.7.0 // indirect
33 | github.com/sourcegraph/conc v0.3.0 // indirect
34 | go.opentelemetry.io/auto/sdk v1.1.0 // indirect
35 | go.opentelemetry.io/otel/metric v1.36.0 // indirect
36 | go.opentelemetry.io/proto/otlp v1.6.0 // indirect
37 | go.uber.org/multierr v1.11.0 // indirect
38 | golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 // indirect
39 | golang.org/x/net v0.40.0 // indirect
40 | google.golang.org/genproto/googleapis/api v0.0.0-20250519155744-55703ea1f237 // indirect
41 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250519155744-55703ea1f237 // indirect
42 | google.golang.org/grpc v1.72.1 // indirect
43 | google.golang.org/protobuf v1.36.6 // indirect
44 | )
45 |
46 | require (
47 | github.com/fsnotify/fsnotify v1.9.0
48 | github.com/pelletier/go-toml/v2 v2.2.3 // indirect
49 | github.com/spf13/afero v1.12.0 // indirect
50 | github.com/spf13/cast v1.7.1 // indirect
51 | github.com/spf13/pflag v1.0.6 // indirect
52 | github.com/subosito/gotenv v1.6.0 // indirect
53 | gopkg.in/yaml.v3 v3.0.1 // indirect
54 | )
55 |
56 | require (
57 | github.com/google/uuid v1.6.0
58 | github.com/tidwall/match v1.1.1 // indirect
59 | github.com/tidwall/pretty v1.2.1 // indirect
60 | golang.org/x/sys v0.33.0
61 | )
62 |
63 | require (
64 | github.com/FloatTech/floatbox v0.0.0-20240505082030-226ec6713e14
65 | github.com/FloatTech/gg v1.1.3 // indirect
66 | github.com/FloatTech/imgfactory v0.2.2-0.20230315152233-49741fc994f9 // indirect
67 | github.com/FloatTech/rendercard v0.1.2 // indirect
68 | github.com/FloatTech/sqlite v1.7.0 // indirect
69 | github.com/FloatTech/ttl v0.0.0-20240716161252-965925764562 // indirect
70 | github.com/RomiChan/syncx v0.0.0-20240418144900-b7402ffdebc7 // indirect
71 | github.com/disintegration/imaging v1.6.2 // indirect
72 | github.com/ericpauley/go-quantize v0.0.0-20200331213906-ae555eb2afa4 // indirect
73 | github.com/fumiama/cron v1.3.0 // indirect
74 | github.com/fumiama/go-base16384 v1.7.0 // indirect
75 | github.com/fumiama/go-registry v0.2.7 // indirect
76 | github.com/fumiama/go-simple-protobuf v0.2.0 // indirect
77 | github.com/fumiama/gofastTEA v0.0.10 // indirect
78 | github.com/fumiama/imgsz v0.0.4 // indirect
79 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
80 | github.com/jinzhu/inflection v1.0.0 // indirect
81 | github.com/jinzhu/now v1.1.5 // indirect
82 | github.com/mattn/go-isatty v0.0.20 // indirect
83 | github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
84 | github.com/pkg/errors v0.9.1
85 | github.com/pquerna/otp v1.5.0
86 | github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
87 | github.com/spf13/viper v1.20.1
88 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.36.0
89 | golang.org/x/image v0.18.0 // indirect
90 | golang.org/x/text v0.25.0 // indirect
91 | gopkg.in/natefinch/lumberjack.v2 v2.2.1
92 | modernc.org/libc v1.61.0 // indirect
93 | modernc.org/mathutil v1.6.0 // indirect
94 | modernc.org/memory v1.8.0 // indirect
95 | modernc.org/sqlite v1.33.1 // indirect
96 | )
97 |
98 | replace modernc.org/sqlite => github.com/fumiama/sqlite3 v1.20.0-with-win386
99 |
100 | replace github.com/FloatTech/zbputils => github.com/KomeiDiSanXian/zbputils v0.0.0-20230923095115-55ba2c51620d
101 |
102 | replace github.com/remyoudompheng/bigfft => github.com/fumiama/bigfft v0.0.0-20211011143303-6e0bfa3c836b
103 |
--------------------------------------------------------------------------------
/bfhelper/pkg/logger/logger.go:
--------------------------------------------------------------------------------
1 | // Package logger 日志
2 | package logger
3 |
4 | import (
5 | "context"
6 | "encoding/json"
7 | "fmt"
8 | "io"
9 | "log"
10 | "runtime"
11 | "time"
12 | )
13 |
14 | // Level 日志等级
15 | type Level int8
16 |
17 | // Fields 日志字段
18 | type Fields map[string]any
19 |
20 | const (
21 | LevelDebug Level = iota // LevelDebug Debug
22 | LevelInfo // LevelInfo Info
23 | LevelWarn // LevelWarn Warn
24 | LevelError // LevelError Error
25 | LevelFatal // LevelFatal Fatal
26 | LevelPanic // LevelPanic Panic
27 | )
28 |
29 | // String returns a string representation of level
30 | func (l Level) String() string {
31 | switch l {
32 | case LevelDebug:
33 | return "Debug"
34 | case LevelInfo:
35 | return "Info"
36 | case LevelWarn:
37 | return "Warning"
38 | case LevelError:
39 | return "Error"
40 | case LevelFatal:
41 | return "Fatal"
42 | case LevelPanic:
43 | return "Panic"
44 | }
45 | return ""
46 | }
47 |
48 | // Logger 日志结构体
49 | type Logger struct {
50 | newLogger *log.Logger
51 | ctx context.Context
52 | fields Fields
53 | callers []string
54 | }
55 |
56 | // NewLogger 新建日志
57 | func NewLogger(w io.Writer, prefix string, flag int) *Logger {
58 | return &Logger{newLogger: log.New(w, prefix, flag)}
59 | }
60 |
61 | func (l *Logger) clone() *Logger {
62 | ll := *l
63 | return &ll
64 | }
65 |
66 | // WithContext 设置日志上下文字段
67 | func (l *Logger) WithContext(ctx context.Context) *Logger {
68 | ll := l.clone()
69 | ll.ctx = ctx
70 | return ll
71 | }
72 |
73 | // WithFields 设置日志公共字段
74 | func (l *Logger) WithFields(f Fields) *Logger {
75 | ll := l.clone()
76 | if ll.fields == nil {
77 | ll.fields = make(Fields)
78 | }
79 | for k, v := range f {
80 | ll.fields[k] = v
81 | }
82 | return ll
83 | }
84 |
85 | // WithCaller 设置当前某一层的调用栈信息
86 | func (l *Logger) WithCaller(skip int) *Logger {
87 | ll := l.clone()
88 | pc, file, line, ok := runtime.Caller(skip)
89 | if ok {
90 | f := runtime.FuncForPC(pc)
91 | // 打出文件名, 行号和函数名
92 | ll.callers = []string{fmt.Sprintf("%s:%d %s", file, line, f.Name())}
93 | }
94 | return ll
95 | }
96 |
97 | // WithCallerFrames 设置当前的整个调用栈信息
98 | func (l *Logger) WithCallerFrames() *Logger {
99 | // 限制调用栈深度
100 | maxCallerDepth := 25
101 | minCallerDepth := 1
102 |
103 | callers := make([]string, 0, maxCallerDepth)
104 | pcs := make([]uintptr, maxCallerDepth)
105 | depth := runtime.Callers(minCallerDepth, pcs)
106 |
107 | frames := runtime.CallersFrames(pcs[:depth])
108 | for frame, more := frames.Next(); more; frame, more = frames.Next() {
109 | currentCaller := fmt.Sprintf("%s:%d %s", frame.File, frame.Line, frame.Function)
110 | callers = append(callers, currentCaller)
111 | if !more {
112 | break
113 | }
114 | }
115 |
116 | ll := l.clone()
117 | ll.callers = callers
118 | return ll
119 | }
120 |
121 | // JSONFormat 将日志格式化为JSON
122 | func (l *Logger) JSONFormat(level Level, message string) map[string]any {
123 | data := make(Fields, len(l.fields)+4)
124 | data["level"] = level.String()
125 | data["time"] = time.Now().Local().Unix()
126 | data["message"] = message
127 | data["callers"] = l.callers
128 |
129 | if len(l.fields) > 0 {
130 | for k, v := range l.fields {
131 | if _, ok := data[k]; !ok {
132 | data[k] = v
133 | }
134 | }
135 | }
136 |
137 | return data
138 | }
139 |
140 | // Output 输出日志
141 | func (l *Logger) Output(level Level, message string) {
142 | body, _ := json.Marshal(l.WithCaller(3).JSONFormat(level, message))
143 | content := string(body)
144 | switch level {
145 | case LevelDebug, LevelInfo, LevelWarn, LevelError:
146 | l.newLogger.Print(content)
147 | case LevelFatal:
148 | l.newLogger.Fatal(content)
149 | case LevelPanic:
150 | l.newLogger.Panic(content)
151 | }
152 | }
153 |
154 | // Debug 输出Debug级别日志
155 | func (l *Logger) Debug(v ...any) {
156 | l.Output(LevelDebug, fmt.Sprint(v...))
157 | }
158 |
159 | // Debugf 格式化输出Debug级别日志
160 | func (l *Logger) Debugf(format string, v ...any) {
161 | l.Output(LevelDebug, fmt.Sprintf(format, v...))
162 | }
163 |
164 | // Info 输出Info级别日志
165 | func (l *Logger) Info(v ...any) {
166 | l.Output(LevelInfo, fmt.Sprint(v...))
167 | }
168 |
169 | // Infof 格式化输出Info级别日志
170 | func (l *Logger) Infof(format string, v ...any) {
171 | l.Output(LevelInfo, fmt.Sprintf(format, v...))
172 | }
173 |
174 | // Warn 输出Warn级别日志
175 | func (l *Logger) Warn(v ...any) {
176 | l.Output(LevelWarn, fmt.Sprint(v...))
177 | }
178 |
179 | // Warnf 格式化输出Warn级别日志
180 | func (l *Logger) Warnf(format string, v ...any) {
181 | l.Output(LevelWarn, fmt.Sprintf(format, v...))
182 | }
183 |
184 | // Error 输出Error级别日志
185 | func (l *Logger) Error(v ...any) {
186 | l.Output(LevelError, fmt.Sprint(v...))
187 | }
188 |
189 | // Errorf 格式化输出Error级别日志
190 | func (l *Logger) Errorf(format string, v ...any) {
191 | l.Output(LevelError, fmt.Sprintf(format, v...))
192 | }
193 |
194 | // Fatal 输出Fatal级别日志
195 | func (l *Logger) Fatal(v ...any) {
196 | l.Output(LevelFatal, fmt.Sprint(v...))
197 | }
198 |
199 | // Fatalf 格式化输出Fatal级别日志
200 | func (l *Logger) Fatalf(format string, v ...any) {
201 | l.Output(LevelFatal, fmt.Sprintf(format, v...))
202 | }
203 |
204 | // Panic 输出Panic级别日志,并触发 panic
205 | func (l *Logger) Panic(v ...any) {
206 | l.Output(LevelPanic, fmt.Sprint(v...))
207 | }
208 |
209 | // Panicf 格式化输出Panic级别日志,并触发 panic
210 | func (l *Logger) Panicf(format string, v ...any) {
211 | l.Output(LevelPanic, fmt.Sprintf(format, v...))
212 | }
213 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # BFHelper
5 |
6 | BFHelper是依赖于 [ZeroBot](https://github.com/wdvxdr1123/ZeroBot) 的插件
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | ---
35 |
36 | ## 声明
37 | > 任何的查询不会导致被查询用户被EA封禁
38 |
39 | > 请注意,任何开发者都**没有义务**回答您的问题
40 | >
41 | > 本插件仅是一个工具,开发者只是提供了这样的一个工具,并不是您攻击谩骂的对象
42 |
43 | 开发者**不**负责解封
44 |
45 | 开发者**不**负责解封
46 |
47 | 开发者**不**负责解封
48 |
49 | 如果您遭到了联合封禁,本插件不提供任何有关BFEAC及BFBan解封的实际帮助
50 |
51 | 请前往[BFEAC申诉](https://bfeac.com/#/about)和[BFBan申诉](mailto:ban-appeals@bfban.com)
52 |
53 | 如果您因本插件未来添加的功能导致被某一服务器添加进该服Ban列,请进入该服务器的QQ群,联系管理员解封
54 |
55 | ---
56 |
57 | ## 功能
58 |
59 | > 前往 [src](https://github.com/KomeiDiSanXian/BFHelper/tree/master/bfhelper) 查看更多
60 |
61 | - [ ] 举报作弊行为
62 | - [x] 查询玩家是否被联合封禁 (在 [BFEAC](https://bfeac.com/#/) & [BFban](https://bfban.gametools.network/) 中查询)
63 |
64 | ### 战地一 BattleField 1
65 | #### 玩家
66 | - [x] 查询玩家战绩 (通过 [BTR](https://battlefieldtracker.com/) 实现)
67 | - [x] 查询玩家武器信息 (Battlefield Gateway 实现)
68 | - [x] 查询玩家载具击杀信息 (Battlefield Gateway 实现)
69 | - [x] 查询玩家最近游玩信息 (借助 @Bili22 的api实现)
70 | - [x] 查询本期的交换信息 (Battlefield Gateway 实现)
71 | - [x] 查询本期行动包 (Battlefield Gateway 实现)
72 |
73 | #### 服务器
74 | - [x] 踢出玩家
75 | - [x] 封禁&解封玩家
76 | - [x] 切换地图
77 | - [ ] 添加&删除VIP `推迟`
78 | - [ ] 修改服务器配置
79 |
80 | ### 战地五 BattleField V
81 | > 目前计划支持
82 |
83 | ### 战地2042 BattleField 2042
84 | > 目前没有计划
85 |
86 | ---
87 |
88 | ## 如何使用
89 | > 玩家相关命令
90 | >
91 | > 中括号内可填可不填
92 | - [x] **.绑定 xxx** 用于将xxx绑定到发送该命令的用户, 便于以后的查询
93 | - [x] **.战绩 [xxx]** 用于查询xxx的战绩, 如果没有xxx将会查询发送该命令用户的战绩
94 | - [x] **.武器 [xxx]** 类似上者, 改为查询武器击杀数据
95 | - [x] **.最近 [xxx]** 类似上者, 改为查询最近战绩
96 | - [x] **.载具 [xxx]** 类似上者, 改为查询载具击杀数据
97 | - [x] **.交换** 查询战地一本期交换皮肤
98 | - [x] **.行动** 查询战地一本期行动包信息
99 | - [x] **.cb [xxx]** 查询xxx联合封禁信息
100 |
101 | > 战地一服务器相关命令
102 | >
103 | > 中括号内可填可不填. 服主权限于群主权限等同; 服管理员于群管理员权限等同
104 | - [x] **.创建服务器群组 [qq号]** 让群聊可以开始绑定服务器, 这些服务器的服主是所填的qq, 不填则为发送人 **`需要群主及以上权限`**
105 | - [x] **.删除服务器群组** 删除群聊所有的服务器绑定信息 **`需要群主及以上权限`**
106 | - [x] **.更换服主 qq号** 更换群聊绑定的群组的所属人 **`需要服主及以上权限`**
107 | - [x] **.绑定服务器 群号 gameid1 gameid2...** 将gameid1, gameid2...的服务器绑定到群号 **`需要超级管理员权限`**
108 | - [x] **.添加管理 qq1 qq2...** 将qq1, qq2...添加为服务器群组的管理员 **`需要服主及以上权限`**
109 | - [x] **.设置别名 gameid 别名** 设置gameid的服务器别名为 别名 **`需要服管理员及以上权限`**
110 | - [x] **.解绑服务器 gameid** 解除为gameid的服务器与群聊的绑定 **`需要服主及以上权限`**
111 | - [x] **.删除管理 qq** 解除qq的服管理员权限 **`需要服主及以上权限`**
112 | - [x] **.k 玩家** 在所有已绑定的服务器踢出 玩家 **`需要服管理员及以上权限`**
113 | - [x] **.b [别名] 玩家** 在 别名 的服务器将 玩家 封禁. **`需要服管理员及以上权限`**
114 | - [x] **.ub [别名] 玩家** 在 别名 的服务器将 玩家 解封. **`需要服管理员及以上权限`**
115 | - [x] **.bana 玩家** 在 所有已绑定 的服务器将 玩家 封禁. **`需要服管理员及以上权限`**
116 | - [x] **.ubana 玩家** 在 所有已绑定 的服务器将 玩家 解封. **`需要服管理员及以上权限`**
117 | - [x] **.cm 别名 [地图号]** 将 别名 的服务器的地图切换到地图号, 不填地图号则有地图提示 **`需要服管理员及以上权限`**
118 | - [x] **.qm 别名** 查询 别名 的服务器地图池 **`所有人`**
119 |
120 | ---
121 |
122 | ## 如何安装
123 |
124 | > **注意**: release 中的插件有且仅有本插件
125 | >
126 | > 对于Windows 系统,仅支持win 7 (win server 2008 R2) 及以上
127 | ### a. 下载二进制程序
128 |
129 | 1. 前往 [release](https://github.com/KomeiDiSanXian/BFHelper/releases) 或 [CI](https://github.com/KomeiDiSanXian/BFHelper/actions/workflows/go.yml) 下载符合您系统的版本
130 | 2. 启动应用程序
131 | > **注意**: 第一次启动会生成配置文件 `botcongfig.yaml`,请修改该配置
132 |
133 | 3. 修改配置后,重新启动应用,同时启动 OneBot 框架 (如 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp))
134 | 4. 修改 `data/battlefield` 中的 `settings.yml`
135 | > **注意**: 如果没有该文件,请使用一次本插件, 插件将会生成一份 `settings.yml`
136 | >
137 | > 修改后无需重启
138 |
139 | ### b. 本地编译
140 |
141 | 1. 下载并安装最新的 [golang](https://studygolang.com/dl) 环境
142 | > [!IMPORTANT]
143 | > 如果你使用的是**1.23**及以上版本的golang, 需要在编译时额外添加 `-checklinkname=0` 参数, 如下
144 | > ```bash
145 | > go build -ldflags=-checklinkname=0 .
146 | > ```
147 | 2. clone [FloatTech/ZeroBot-Plugin](https://github.com/FloatTech/ZeroBot-Plugin)
148 | 3. 编辑`main.go`文件中的import, 在其中添加
149 |
150 | ```go
151 | _ "github.com/KomeiDiSanXian/BFHelper/bfhelper"
152 | ```
153 | 4. 下载本项目中的data文件夹,复制进 `ZeroBot-Plugin` 并对其中的 `data/battlefield/settings.yml` 按需编辑
154 | 5. 根据你所使用的平台进行编译
155 | 6. 运行 OneBot 框架 然后运行你编译的文件
156 |
157 | ### c. 使用RemiliaBot
158 | > [RemiliaBot](https://github.com/KomeiDiSanXian/RemiliaBot) 是 [FloatTech/ZeroBot-Plugin](https://github.com/FloatTech/ZeroBot-Plugin) 的 fork 分支
159 |
160 | 1. 下载 [RemiliaBot](https://github.com/KomeiDiSanXian/RemiliaBot/releases)
161 | 2. 编辑其中的 `data/battlefield/settings.yml`
162 | 3. 编辑 RemiliaBot (参考 RemiliaBot 的 [README.md](https://github.com/KomeiDiSanXian/RemiliaBot/blob/master/README.md))
163 | 4. 启动 OneBot 框架和 RemiliaBot
164 |
165 | ----
166 | ## 特别感谢
167 | - [ZeroBot](https://github.com/wdvxdr1123/ZeroBot)
168 | - [ZeroBot-Plugin](https://github.com/FloatTech/ZeroBot-Plugin)
169 | - [Bili22](mailto:b22lengfeng@qq.com)
170 | - [SakuraKooi](https://github.com/SakuraKoi)
171 | - [GameTools](https://github.com/Community-network)
172 |
--------------------------------------------------------------------------------
/bfhelper/internal/model/serverdb.go:
--------------------------------------------------------------------------------
1 | // Package model 服务器数据操作
2 | package model
3 |
4 | import (
5 | "time"
6 |
7 | "github.com/jinzhu/gorm"
8 | "github.com/pkg/errors"
9 | )
10 |
11 | // Group 群组表
12 | type Group struct {
13 | GroupID int64 `gorm:"primary_key;auto_increment:false"`
14 | Owner int64
15 | Servers []Server `gorm:"many2many:group_servers"`
16 | Admins []Admin `gorm:"many2many:group_admins"`
17 | CreatedAt time.Time
18 | UpdatedAt time.Time
19 | }
20 |
21 | // Server 服务器表
22 | type Server struct {
23 | GameID string `gorm:"primary_key"`
24 | ServerID string
25 | PGID string
26 | NameInGroup string
27 | ServerName string
28 | CreatedAt time.Time
29 | UpdatedAt time.Time
30 | }
31 |
32 | // Admin 管理表
33 | type Admin struct {
34 | QQID int64 `gorm:"primary_key;auto_increment:false"`
35 | CreatedAt time.Time
36 | UpdatedAt time.Time
37 | }
38 |
39 | // NewGroup creates a new Group
40 | func NewGroup(groupID int64) *Group {
41 | return &Group{GroupID: groupID}
42 | }
43 |
44 | // NewServer creates a new Server
45 | func NewServer(gameID string) *Server {
46 | return &Server{GameID: gameID}
47 | }
48 |
49 | // NewAdmin creates a new Admin
50 | func NewAdmin(qid int64) *Admin {
51 | return &Admin{QQID: qid}
52 | }
53 |
54 | // Create 创建一个新的 Group 记录
55 | func (g *Group) Create(db *gorm.DB) error {
56 | if g.GroupID == 0 {
57 | return errors.New("invalid Group ID")
58 | }
59 | return db.Create(g).Error
60 | }
61 |
62 | // GetByID 根据 GroupID 获取 Group 记录
63 | func (g *Group) GetByID(db *gorm.DB) (*Group, error) {
64 | if g.GroupID == 0 {
65 | return nil, errors.New("invalid Group ID")
66 | }
67 | err := db.Preload("Servers").Preload("Admins").First(&g, g.GroupID).Error
68 | if err != nil {
69 | return nil, err
70 | }
71 | return g, nil
72 | }
73 |
74 | // GetByAlias 根据别名获取 Server 记录
75 | func (g *Group) GetByAlias(db *gorm.DB, alias string) (*Server, error) {
76 | if g.GroupID == 0 {
77 | return nil, errors.New("invalid Group ID")
78 | }
79 | err := db.Preload("Servers").Preload("Admins").First(&g).Error
80 | if err != nil {
81 | return nil, err
82 | }
83 | for _, srv := range g.Servers {
84 | if srv.NameInGroup == alias {
85 | return &srv, nil
86 | }
87 | }
88 | return nil, errors.New("not found server")
89 | }
90 |
91 | // Update 更新 Group 记录
92 | //
93 | // 注意不能修改为各类型零值
94 | func (g *Group) Update(db *gorm.DB) error {
95 | if g.GroupID == 0 {
96 | return errors.New("invalid Group ID")
97 | }
98 | // 开始事务
99 | tx := db.Begin()
100 | if err := tx.Model(g).Updates(g).Error; err != nil {
101 | tx.Rollback()
102 | return err
103 | }
104 | // 添加关联
105 | if err := tx.Model(g).Association("Servers").Append(g.Servers).Error; err != nil {
106 | tx.Rollback()
107 | return err
108 | }
109 | if err := tx.Model(g).Association("Admins").Append(g.Admins).Error; err != nil {
110 | tx.Rollback()
111 | return err
112 | }
113 | // 提交
114 | if err := tx.Commit().Error; err != nil {
115 | tx.Rollback() // 回滚事务
116 | return err
117 | }
118 |
119 | return nil
120 | }
121 |
122 | // DeleteByID 根据 GroupID 删除 Group 记录
123 | func (g *Group) DeleteByID(db *gorm.DB) error {
124 | if g.GroupID == 0 {
125 | return errors.New("invalid Group ID")
126 | }
127 | // 删除 Group 表中的记录
128 | if err := db.Delete(&Group{GroupID: g.GroupID}).Error; err != nil {
129 | return err
130 | }
131 |
132 | // 删除关联表中的数据
133 | if err := db.Exec("DELETE FROM group_servers WHERE group_group_id = ?", g.GroupID).Error; err != nil {
134 | return err
135 | }
136 |
137 | return db.Exec("DELETE FROM group_admins WHERE group_group_id = ?", g.GroupID).Error
138 | }
139 |
140 | // IsAdmin 检查是否为该服务器群管理
141 | func (g *Group) IsAdmin(db *gorm.DB, qid int64) bool {
142 | grpdb, err := g.GetByID(db)
143 | if err != nil {
144 | return false
145 | }
146 | for _, admin := range grpdb.Admins {
147 | if qid == admin.QQID {
148 | return true
149 | }
150 | }
151 | return qid == grpdb.Owner
152 | }
153 |
154 | // IsOwner 检查是否为服务器拥有者
155 | func (g *Group) IsOwner(db *gorm.DB, qid int64) bool {
156 | grpdb, err := g.GetByID(db)
157 | if err != nil {
158 | return false
159 | }
160 | return grpdb.Owner == qid
161 | }
162 |
163 | // DeleteServer 删除联表中的server
164 | func (g *Group) DeleteServer(db *gorm.DB, gameID string) error {
165 | return db.Exec("DELETE FROM group_servers WHERE group_group_id = ? AND server_game_id = ?", g.GroupID, gameID).Error
166 | }
167 |
168 | // DeleteAdmin 删除联表中的admin
169 | func (g *Group) DeleteAdmin(db *gorm.DB, adminQQ int64) error {
170 | return db.Exec("DELETE FROM group_admins WHERE group_group_id = ? AND admin_qq_id = ?", g.GroupID, adminQQ).Error
171 | }
172 |
173 | // Create 创建一个新的 Server 记录
174 | func (s *Server) Create(db *gorm.DB) error {
175 | if s.GameID == "" {
176 | return errors.New("invalid GameID")
177 | }
178 | return db.Create(s).Error
179 | }
180 |
181 | // GetByGameID 根据 GameID 获取 Server 记录
182 | func (s *Server) GetByGameID(db *gorm.DB) (*Server, error) {
183 | if s.GameID == "" {
184 | return nil, errors.New("invalid GameID")
185 | }
186 | err := db.First(&s, s.GameID).Error
187 | if err != nil {
188 | return nil, err
189 | }
190 | return s, nil
191 | }
192 |
193 | // Update 更新 Server 记录
194 | func (s *Server) Update(db *gorm.DB) error {
195 | if s.GameID == "" {
196 | return errors.New("invalid GameID")
197 | }
198 | return db.Model(&Server{}).Updates(s).Error
199 | }
200 |
201 | // DeleteByGameID 根据 GameID 删除 Server 记录
202 | func (s *Server) DeleteByGameID(db *gorm.DB) error {
203 | if s.GameID == "" {
204 | return errors.New("invalid GameID")
205 | }
206 | return db.Delete(&Server{GameID: s.GameID}).Error
207 | }
208 |
209 | // Create 创建一个新的 Admin 记录
210 | func (a *Admin) Create(db *gorm.DB) error {
211 | if a.QQID == 0 {
212 | return errors.New("invalid QQ")
213 | }
214 | return db.Create(a).Error
215 | }
216 |
217 | // GetByQQID 根据 QQID 获取 Admin 记录
218 | func (a *Admin) GetByQQID(db *gorm.DB) (*Admin, error) {
219 | if a.QQID == 0 {
220 | return nil, errors.New("invalid QQ")
221 | }
222 | err := db.First(a, a.QQID).Error
223 | if err != nil {
224 | return nil, err
225 | }
226 | return a, nil
227 | }
228 |
229 | // Update 更新 Admin 记录
230 | func (a *Admin) Update(db *gorm.DB) error {
231 | if a.QQID == 0 {
232 | return errors.New("invalid QQ")
233 | }
234 | return db.Model(&Admin{}).Updates(a).Error
235 | }
236 |
237 | // DeleteByQQID 根据 QQID 删除 Admin 记录
238 | func (a *Admin) DeleteByQQID(db *gorm.DB) error {
239 | if a.QQID == 0 {
240 | return errors.New("invalid QQ")
241 | }
242 | return db.Delete(&Admin{QQID: a.QQID}).Error
243 | }
244 |
--------------------------------------------------------------------------------
/bfhelper/internal/bf1/player/player.go:
--------------------------------------------------------------------------------
1 | // Package player 玩家信息查询
2 | package player
3 |
4 | import (
5 | "bytes"
6 | "encoding/json"
7 | "fmt"
8 | "net/http"
9 | "sort"
10 | "strings"
11 | "sync"
12 |
13 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/anticheat"
14 | rsp "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/bf1/api"
15 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
16 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/netreq"
17 | bf1reqbody "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/netreq/bf1"
18 | "github.com/pkg/errors"
19 | "github.com/tidwall/gjson"
20 | )
21 |
22 | // Cheater 作弊玩家结构体
23 | type Cheater struct {
24 | EAC anticheat.HackEACResp
25 | BFBan anticheat.HackBFBanResp
26 | }
27 |
28 | // GetStats 获取战绩信息
29 | func GetStats(id string) (*Stat, error) {
30 | transport := http.DefaultTransport.(*http.Transport).Clone()
31 | transport.ForceAttemptHTTP2 = false
32 | transport.TLSClientConfig.NextProtos = []string{"http/1.1"}
33 | res, err := netreq.Request{
34 | URL: "https://api.tracker.gg/api/v2/bf1/standard/profile/origin/" + id,
35 | Header: map[string]string{
36 | "Host": "api.tracker.gg",
37 | "User-Agent": "Tracker Network App / 3.22.9",
38 | "Accept": "application/json; charset=utf-8",
39 | "x-app-version": "3.22.9",
40 | },
41 | Transport: transport,
42 | }.GetRespBodyJSON()
43 | if res == nil {
44 | return nil, errors.New("empty response")
45 | }
46 | if err != nil {
47 | return nil, err
48 | }
49 | if res.Get("errors").Exists() {
50 | return nil, errors.New("invalid id")
51 | }
52 |
53 | data := res.Get("data.segments.0")
54 | stat := &Stat{
55 | SPM: data.Get("stats.scorePerMinute.displayValue").Str,
56 | TotalKD: data.Get("stats.kdRatio.displayValue").Str,
57 | WinPercent: data.Get("stats.winPercentage.displayValue").Str,
58 | KillsPerGame: data.Get("stats.killsPerRound.displayValue").Str,
59 | Kills: data.Get("stats.kills.displayValue").Str,
60 | Deaths: data.Get("stats.deaths.displayValue").Str,
61 | KPM: data.Get("stats.killsPerMinute.displayValue").Str,
62 | Losses: data.Get("stats.losses.displayValue").Str,
63 | Wins: data.Get("stats.wins.displayValue").Str,
64 | InfantryKills: data.Get("stats.infantryKills.displayValue").Str,
65 | InfantryKPM: data.Get("stats.infantryKillsPerMinute.displayValue").Str,
66 | InfantryKD: data.Get("stats.infantryKdRatio.displayValue").Str,
67 | VehicleKills: data.Get("stats.vehicleKills.displayValue").Str,
68 | VehicleKPM: data.Get("stats.vehicleKillsPerMinute.displayValue").Str,
69 | Rank: data.Get("stats.rank.displayValue").Str,
70 | TimePlayed: data.Get("stats.timePlayed.displayValue").Str,
71 | MVP: data.Get("stats.mvp.displayValue").Str,
72 | Accuracy: data.Get("stats.shotsAccuracy.displayValue").Str,
73 | DogtagsTaken: data.Get("stats.dogtagsTaken.displayValue").Str,
74 | Headshots: data.Get("stats.headshots.displayValue").Str,
75 | HighestKillStreak: data.Get("stats.killStreak.displayValue").Str,
76 | LongestHeadshot: data.Get("stats.longestHeadshot.displayValue").Str,
77 | Revives: data.Get("stats.revive.displayValue").Str,
78 | }
79 | return stat, err
80 | }
81 |
82 | // GetWeapons 获取武器
83 | func GetWeapons(pid, class string) (*WeaponSort, error) {
84 | post := bf1reqbody.NewPostWeapon(pid)
85 | data, err := rsp.ReturnJSON(global.NativeAPI, "POST", post)
86 | if err != nil {
87 | return nil, err
88 | }
89 | var result []gjson.Result
90 | if class == ALL {
91 | result = data.Get("result.#.weapons|@flatten").Array()
92 | } else {
93 | result = data.Get("result.#(categoryId=\"" + class + "\").weapons").Array()
94 | }
95 | return SortWeapon(result), err
96 | }
97 |
98 | // GetVehicles 获取载具信息
99 | func GetVehicles(pid string) (*VehicleSort, error) {
100 | post := bf1reqbody.NewPostVehicle(pid)
101 | data, err := rsp.ReturnJSON(global.NativeAPI, "POST", post)
102 | if err != nil {
103 | return nil, err
104 | }
105 | gets := data.Get("result").Array()
106 | var vehicle VehicleSort
107 | for i := range gets {
108 | res := gjson.GetMany(gets[i].Raw,
109 | "name",
110 | "stats.values.kills",
111 | "stats.values.destroyed",
112 | "stats.values.seconds",
113 | )
114 | kills := res[1].Float()
115 | seconds := res[3].Float()
116 | var kpm float64
117 | if seconds != 0 {
118 | kpm = kills / seconds * 60
119 | }
120 | vehicle = append(vehicle, Vehicle{
121 | Name: res[0].Str,
122 | Kills: kills,
123 | Destroyed: res[2].Float(),
124 | KPM: fmt.Sprintf("%.3f", kpm),
125 | Time: fmt.Sprintf("%.2f", seconds/3600),
126 | })
127 | }
128 | sort.Sort(vehicle)
129 | return &vehicle, err
130 | }
131 |
132 | // Get2k battlelog 获取kd,kpm
133 | func Get2k(pid string) (kd float64, kpm float64, err error) {
134 | post := bf1reqbody.NewPostStats(pid)
135 | data, err := rsp.ReturnJSON(global.NativeAPI, "POST", post)
136 | if err != nil {
137 | return -1, -1, err
138 | }
139 | death := data.Get("result.basicStats.deaths").Float()
140 | if death == 0 {
141 | kd = data.Get("result.basicStats.kills").Float()
142 | return kd, data.Get("result.basicStats.kpm").Float(), nil
143 | }
144 | kd = data.Get("result.basicStats.kills").Float() / death
145 | kpm = data.Get("result.basicStats.kpm").Float()
146 | return kd, kpm, err
147 | }
148 |
149 | // IsHacker 借助id 获取举报信息
150 | func IsHacker(id string) *Cheater {
151 | var c Cheater
152 | var wg sync.WaitGroup
153 | wg.Add(2)
154 | // bfban
155 | go func() {
156 | defer wg.Done()
157 | result, err := netreq.Request{URL: global.BFBan + "checkban/?names=" + id}.GetRespBodyJSON()
158 | if err != nil || result.Get("errors").String() != "" {
159 | c.BFBan.Status = "查询失败"
160 | c.BFBan.URL = "无"
161 | return
162 | }
163 | bfban := result.Get("names." + strings.ToLower(id))
164 | c.BFBan.IsCheater = bfban.Get("hacker").Bool()
165 | if bfban.Get("originId").Str != "" {
166 | c.BFBan.Status = anticheat.BFBanHackerStatus[int(bfban.Get("status").Int())]
167 | c.BFBan.URL = bfban.Get("url").Str
168 | }
169 | }()
170 | // bfeac
171 | go func() {
172 | defer wg.Done()
173 | result, err := netreq.Request{URL: global.BFEAC + "case/EAID/" + id}.GetRespBodyJSON()
174 | if err != nil || result.Get("error_code").Int() != 0 {
175 | c.EAC.Status = "查询失败: " + result.Get("error_msg").Str
176 | c.EAC.URL = "无"
177 | return
178 | }
179 | bfeac := result.Get("data.0")
180 | c.EAC.Status = anticheat.EACHackerStatus[int(bfeac.Get("current_status").Int())]
181 | c.EAC.URL = "https://bfeac.com/?#/case/" + bfeac.Get("case_id").String()
182 | }()
183 | wg.Wait()
184 | return &c
185 | }
186 |
187 | // GetBF1Recent 获取bf1最近战绩
188 | func GetBF1Recent(id string) (result *Recent, err error) {
189 | u := "https://api.bili22.me/bf1/recent?name=" + id
190 | data, err := netreq.Request{URL: u}.GetRespBodyBytes()
191 | if err != nil {
192 | return nil, err
193 | }
194 | err = json.NewDecoder(bytes.NewReader(data)).Decode(&result)
195 | if err != nil {
196 | return nil, errors.New("ERR: JSON decode failed")
197 | }
198 | return result, err
199 | }
200 |
--------------------------------------------------------------------------------
/bfhelper/internal/bf1/api/rpc.go:
--------------------------------------------------------------------------------
1 | // Package bf1api 战地相关api库
2 | package bf1api
3 |
4 | import (
5 | "bytes"
6 | "encoding/json"
7 | "fmt"
8 | "io"
9 | "net/http"
10 | "time"
11 |
12 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/errcode"
13 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
14 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/netreq"
15 | bf1reqbody "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/netreq/bf1"
16 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/uuid"
17 | "github.com/pkg/errors"
18 | "github.com/pquerna/otp/totp"
19 | "github.com/sirupsen/logrus"
20 | "github.com/tidwall/gjson"
21 | )
22 |
23 | // post operation struct
24 | type post struct {
25 | Jsonrpc string `json:"jsonrpc"`
26 | Method string `json:"method"`
27 | Params struct {
28 | Game string `json:"game"`
29 | } `json:"params"`
30 | ID string `json:"id"`
31 | }
32 |
33 | func newpost(method string) *post {
34 | return &post{
35 | Jsonrpc: "2.0",
36 | Method: method,
37 | Params: struct {
38 | Game string "json:\"game\""
39 | }{
40 | Game: global.BF1,
41 | },
42 | ID: uuid.NewUUID(),
43 | }
44 | }
45 |
46 | // Pack unmarshal json
47 | type Pack struct {
48 | RemainTime int64
49 | ResetTime int64
50 | Name string
51 | Desc string
52 | Op1Name string
53 | Op2Name string
54 | }
55 |
56 | // Login 获取 Session token cookies
57 | func Login(username, password string) error {
58 | if username == "" || password == "" {
59 | return errors.New("账号信息不完整!")
60 | }
61 | var mfaCode string
62 | var err error
63 | if global.SessionAPISetting.MFASecret != "" {
64 | mfaCode, err = totp.GenerateCode(global.SessionAPISetting.MFASecret, time.Now())
65 | if err != nil {
66 | return err
67 | }
68 | }
69 | user := map[string]interface{}{
70 | "username": username,
71 | "password": password,
72 | "refreshToken": true,
73 | "allowSaveSession": false,
74 | "mfaCode": mfaCode,
75 | }
76 | bodyJSON, err := toJSON(user)
77 | if err != nil {
78 | return errors.New("更新session时出错: json marshal error")
79 | }
80 | result, err := netreq.Request{
81 | Method: http.MethodPost,
82 | URL: global.SessionAPI,
83 | Header: map[string]string{
84 | "Sakura-Instance-Id": global.SessionAPISetting.SakuraID,
85 | "Sakura-Access-Token": global.SessionAPISetting.SakuraToken,
86 | },
87 | Body: bodyJSON,
88 | }.GetRespBodyJSON()
89 | if err != nil {
90 | return err
91 | }
92 | code := result.Get("code").Int()
93 | if code != 0 {
94 | return errors.Errorf("更新session时出错: code: %d, msg: %s", code, result.Get("message").Str)
95 | }
96 | global.AccountSetting.Session = result.Get("data.gatewaySession").Str
97 | global.AccountSetting.Token = fmt.Sprintf("%s%s", "Bearer ", result.Get("data.bearerAccessToken").Str)
98 | global.AccountSetting.SID = result.Get("data.sid").Str
99 | global.AccountSetting.Remid = result.Get("data.remid").Str
100 | return nil
101 | }
102 |
103 | // ReturnJSON NativeAPI 返回json
104 | func ReturnJSON(url, method string, body interface{}) (*gjson.Result, error) {
105 | for i := 0; i < 3; i++ { // 3次重试
106 | // body is json
107 | bodyjson, err := toJSON(body)
108 | if err != nil {
109 | logrus.Errorln("[battlefield]", err)
110 | return nil, err
111 | }
112 | result, err := netreq.Request{
113 | Method: method,
114 | URL: url,
115 | Header: map[string]string{"X-Gatewaysession": global.AccountSetting.Session},
116 | Body: bodyjson,
117 | }.GetRespBodyJSON()
118 |
119 | code := result.Get("error.code").Int()
120 | if code == -32501 {
121 | if err := Login(global.AccountSetting.Username, global.AccountSetting.Password); err != nil {
122 | logrus.Errorln("[battlefield]", err)
123 | return nil, err
124 | }
125 | continue
126 | }
127 | if err == nil {
128 | return result, Exception(code)
129 | }
130 | }
131 | return nil, errors.New("请求超时,可能是session更新失败")
132 | }
133 |
134 | // GetExchange 查询该周交换
135 | func GetExchange() (map[string][]string, error) {
136 | post := newpost(global.Exchange)
137 | data, err := ReturnJSON(global.OperationAPI, http.MethodPost, post)
138 | if err != nil {
139 | return nil, errors.New("获取交换失败")
140 | }
141 | var exmap = make(map[string][]string)
142 | for _, v := range data.Get("result.items.#.item").Array() {
143 | var wpname = v.Get("parentName").Str
144 | if wpname == "" {
145 | wpname = "其他"
146 | }
147 | exmap[wpname] = append(exmap[wpname], v.Get("name").Str)
148 | }
149 | return exmap, err
150 | }
151 |
152 | // GetCampaignPacks 查询本周行动包
153 | func GetCampaignPacks() (*Pack, error) {
154 | post := newpost(global.Campaign)
155 | data, err := ReturnJSON(global.OperationAPI, http.MethodPost, post)
156 | if err != nil {
157 | return nil, errors.New("获取行动包失败")
158 | }
159 | return &Pack{
160 | RemainTime: data.Get("result.minutesRemaining").Int(),
161 | Name: data.Get("result.name").Str,
162 | Desc: data.Get("result.shortDesc").Str,
163 | Op1Name: data.Get("result.op1.name").Str,
164 | Op2Name: data.Get("result.op2.name").Str,
165 | ResetTime: data.Get("result.minutesToDailyReset").Int(),
166 | }, err
167 | }
168 |
169 | // GetPersonalID 由name获取玩家pid
170 | func GetPersonalID(name string) (string, error) {
171 | result, err := netreq.Request{
172 | Method: http.MethodGet,
173 | URL: "https://gateway.ea.com/proxy/identity/personas?namespaceName=cem_ea_id&displayName=" + name,
174 | Header: map[string]string{
175 | "X-Expand-Results": "true",
176 | "Authorization": global.AccountSetting.Token,
177 | },
178 | }.GetRespBodyJSON()
179 | if err != nil {
180 | return "", err
181 | }
182 | info := result.Get("error").Str
183 | if info == "invalid_access_token" || info == "invalid_oauth_info" {
184 | err := Login(global.AccountSetting.Username, global.AccountSetting.Password)
185 | if err != nil {
186 | return "", err
187 | }
188 | return GetPersonalID(name)
189 | }
190 | if info != "" {
191 | return "", errors.New(info)
192 | }
193 | pid := result.Get("personas.persona.0.personaId").String()
194 | if pid == "" {
195 | return "", errors.New("获取玩家pid失败")
196 | }
197 | return pid, err
198 | }
199 |
200 | // GetServerFullInfo 获取服务器完整信息
201 | func GetServerFullInfo(gameID string) (*gjson.Result, error) {
202 | post := bf1reqbody.NewPostGetServerDetails(gameID)
203 | return ReturnJSON(global.NativeAPI, http.MethodPost, post)
204 | }
205 |
206 | // Exception 错误码转换
207 | func Exception(code int64) error {
208 | switch code {
209 | case -34501:
210 | return errcode.ServerNotFoundError
211 | case -32603:
212 | return errcode.InvalidAuthError
213 | case -32851:
214 | return errcode.ServerNotFoundError
215 | case -32857:
216 | return errcode.InvalidPermissionsError
217 | case -32856:
218 | return errcode.InvalidPlayerError
219 | case -32858:
220 | return errcode.ServerNotStartError
221 | }
222 | return nil
223 | }
224 |
225 | // any to Reader
226 | func toJSON(data any) (io.Reader, error) {
227 | buf := &bytes.Buffer{}
228 | switch data := data.(type) {
229 | case string:
230 | buf.WriteString(data)
231 | case []byte:
232 | buf.Write(data)
233 | default:
234 | if err := json.NewEncoder(buf).Encode(data); err != nil {
235 | return nil, errors.New("JSON encoding error")
236 | }
237 | }
238 | return io.NopCloser(buf), nil
239 | }
240 |
--------------------------------------------------------------------------------
/bfhelper/internal/service/player.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "regexp"
7 | "strconv"
8 | "strings"
9 |
10 | bf1api "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/bf1/api"
11 | bf1player "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/bf1/player"
12 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/errcode"
13 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/model"
14 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
15 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/renderer"
16 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/tracer"
17 | "github.com/jinzhu/gorm"
18 | "github.com/pkg/errors"
19 | "github.com/wdvxdr1123/ZeroBot/message"
20 | "go.opentelemetry.io/otel/codes"
21 | )
22 |
23 | // BindAccount 绑定账号
24 | func (s *Service) BindAccount(ctx context.Context) error {
25 | _, span := global.Tracer.Start(ctx, "BindAccount")
26 | defer span.End()
27 | id := s.zctx.State["args"].(string)
28 | if id == "" {
29 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("绑定失败, ERR: 空id"))
30 | return errcode.InvalidPlayerError
31 | }
32 | // 数据库查询是否绑定
33 | span.AddEvent("start query database", tracer.AddEventWithDescription(tracer.Description("query player", id)))
34 | player, err := s.dao.GetPlayerByQID(s.zctx.Event.UserID)
35 | if errors.Is(err, gorm.ErrRecordNotFound) {
36 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("正在绑定id为 ", id))
37 | span.AddEvent("try to bind account")
38 | err = s.dao.CreatePlayer(s.zctx.Event.UserID, id)
39 | if err != nil {
40 | span.RecordError(err)
41 | span.SetStatus(codes.Error, "database error")
42 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("绑定失败, ERR: 数据库错误"))
43 | return errcode.DataBaseCreateError
44 | }
45 | span.AddEvent("bind success")
46 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("绑定成功"))
47 | return errcode.Success
48 | }
49 | if err != nil {
50 | span.RecordError(err)
51 | span.SetStatus(codes.Error, "database error")
52 | return errcode.DataBaseReadError.WithDetails("Error", err).WithZeroContext(s.zctx)
53 | }
54 | // 绑定的是旧id
55 | if id == player.DisplayName {
56 | span.AddEvent("detected user try to bind same, operation cancelled ")
57 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("笨蛋! 你现在绑的就是这个id"))
58 | return errcode.Canceled
59 | }
60 | span.AddEvent("detected user try to change display name")
61 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("将原绑定id为 ", player.DisplayName, " 改绑为 ", id))
62 | err = s.dao.UpdatePlayer(s.zctx.Event.UserID, "", id)
63 | if err != nil {
64 | span.RecordError(err)
65 | span.SetStatus(codes.Error, "database error")
66 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("绑定失败, ERR: 数据库错误"))
67 | return errcode.DataBaseUpdateError
68 | }
69 | span.AddEvent("bind success")
70 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("绑定 ", id, " 成功"))
71 | span.AddEvent("try to get pid")
72 | pid, err := bf1api.GetPersonalID(id)
73 | if err != nil {
74 | span.RecordError(err)
75 | span.SetStatus(codes.Error, "network error")
76 | return errcode.NetworkError.WithDetails("bf1api.GetPersonalID", err).WithZeroContext(s.zctx)
77 | }
78 | span.AddEvent("write pid")
79 | err = s.dao.UpdatePlayer(s.zctx.Event.UserID, pid, "")
80 | if err != nil {
81 | span.RecordError(err)
82 | span.SetStatus(codes.Error, "database error")
83 | return errcode.DataBaseUpdateError
84 | }
85 | span.AddEvent("write success")
86 | span.SetStatus(codes.Ok, "")
87 | return errcode.Success
88 | }
89 |
90 | func (s *Service) getPlayerID(ctx context.Context) (string, bool) {
91 | _, span := global.Tracer.Start(ctx, "GetPlayerDisplayName")
92 | defer span.End()
93 | id := s.zctx.State["regex_matched"].([]string)[1]
94 | span.AddEvent("get name", tracer.AddEventWithDescription(tracer.Description("player name", id)))
95 | // id 为空就去数据库查
96 | if id == "" {
97 | span.AddEvent("empty name, query database")
98 | p, err := s.dao.GetPlayerByQID(s.zctx.Event.UserID)
99 | if err != nil {
100 | span.RecordError(err)
101 | span.SetStatus(codes.Error, "database error")
102 | // 查不到或者失败就是无效
103 | return "", false
104 | }
105 | span.AddEvent("query success", tracer.AddEventWithDescription(tracer.Description("player name", p.DisplayName)))
106 | span.SetStatus(codes.Ok, "")
107 | return p.DisplayName, true
108 | }
109 | // id 不为空就认为有效
110 | span.SetStatus(codes.Ok, "")
111 | return id, true
112 | }
113 |
114 | func (s *Service) getPlayer(ctx context.Context, name string) (*model.Player, error) {
115 | _, span := global.Tracer.Start(ctx, "GetPlayer")
116 | defer span.End()
117 | if name == "" {
118 | span.AddEvent("detected name empty, query database")
119 | return s.dao.GetPlayerByQID(s.zctx.Event.UserID)
120 | }
121 | span.AddEvent("query database")
122 | player, err := s.dao.GetPlayerByName(name)
123 | if err == nil && player.PersonalID != "" {
124 | span.AddEvent("success")
125 | span.SetStatus(codes.Ok, "")
126 | return player, nil
127 | }
128 | span.AddEvent("detected pid empty")
129 | // 有错误或者pid残缺
130 | pid, err := bf1api.GetPersonalID(name)
131 | if err != nil {
132 | span.RecordError(err)
133 | span.SetStatus(codes.Error, "get pid failed")
134 | return nil, err
135 | }
136 | span.AddEvent("get pid success")
137 | span.SetStatus(codes.Ok, "")
138 | // 残缺
139 | if player != nil {
140 | player.PersonalID = pid
141 | span.AddEvent("rewrite pid")
142 | _ = player.Update(global.DB)
143 | return player, nil
144 | }
145 | return &model.Player{DisplayName: name, PersonalID: pid}, nil
146 | }
147 |
148 | func (s *Service) sendWeaponInfo(ctx context.Context, id, class string) error {
149 | nCtx, span := global.Tracer.Start(ctx, "SendWeaponInfo")
150 | defer span.End()
151 | span.AddEvent("try to get player")
152 | s.zctx.Send("少女折寿中...")
153 | player, err := s.getPlayer(nCtx, id)
154 | if err != nil {
155 | span.RecordError(err)
156 | span.SetStatus(codes.Error, "get player failed")
157 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 数据库中没有查到该账号! 请检查是否绑定! 如需绑定请使用[.绑定 id], 中括号不需要输入"))
158 | return errcode.NotFoundError.WithDetails("s.getPlayer", err).WithZeroContext(s.zctx)
159 | }
160 | span.AddEvent("try to get weapon info")
161 | weapons, err := bf1player.GetWeapons(player.PersonalID, class)
162 | if err != nil {
163 | span.RecordError(err)
164 | span.SetStatus(codes.Error, "get weapon info failed")
165 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 获取武器失败"))
166 | return errcode.NetworkError.WithDetails("bf1player.GetWeapons", err).WithZeroContext(s.zctx)
167 | }
168 |
169 | txt := "id:" + player.DisplayName + "\n"
170 | wp := ([]bf1player.Weapons)(*weapons)
171 | for i := 0; i < 5; i++ {
172 | txt += fmt.Sprintf("%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n",
173 | "---------------",
174 | "武器名:", wp[i].Name,
175 | "击杀数:", strconv.FormatFloat(wp[i].Kills, 'f', 0, 64),
176 | "准度:", wp[i].Accuracy,
177 | "爆头率:", wp[i].Headshots,
178 | "KPM:", wp[i].KPM,
179 | "效率:", wp[i].Efficiency,
180 | )
181 | }
182 |
183 | span.AddEvent("success")
184 | span.SetStatus(codes.Ok, "")
185 | renderer.Txt2Img(s.zctx, txt)
186 | return errcode.Success
187 | }
188 |
189 | // GetPlayerRecent 获取玩家最近游玩
190 | func (s *Service) GetPlayerRecent(ctx context.Context) error {
191 | nCtx, span := global.Tracer.Start(ctx, "GetPlayerRecent")
192 | defer span.End()
193 | span.AddEvent("try to get player name")
194 | id, isVaild := s.getPlayerID(nCtx)
195 | if !isVaild {
196 | span.AddEvent("failed to get player")
197 | span.SetStatus(codes.Error, "get invalid player display name")
198 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 数据库中没有查到该账号! 请检查是否绑定! 如需绑定请使用[.绑定 id], 中括号不需要输入"))
199 | return errcode.NotFoundError
200 | }
201 | s.zctx.Send("少女折寿中...")
202 | span.AddEvent("try to get player recent")
203 | recent, err := bf1player.GetBF1Recent(id)
204 | if err != nil {
205 | span.RecordError(err)
206 | span.SetStatus(codes.Error, "network error")
207 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 获取最近战绩失败"))
208 | return errcode.NetworkError.WithDetails("bf1player.GetBF1Recent", err).WithZeroContext(s.zctx)
209 | }
210 | // 发送最近战绩
211 | // TODO: 修改为卡片发送
212 | msg := "id:" + id + "\n"
213 | for i := range *recent {
214 | msg += "服务器:" + (*recent)[i].Server[:24] + "\n"
215 | msg += "地图:" + (*recent)[i].Map + " (" + (*recent)[i].Mode + ")\n"
216 | msg += "kd:" + strconv.FormatFloat((*recent)[i].Kd, 'f', -1, 64) + "\n"
217 | msg += "kpm:" + strconv.FormatFloat((*recent)[i].Kpm, 'f', -1, 64) + "\n"
218 | msg += "游玩时长:" + strconv.FormatFloat(float64((*recent)[i].Time/60), 'f', -1, 64) + "分钟"
219 | msg += "\n---------------\n"
220 | }
221 | span.AddEvent("success")
222 | span.SetStatus(codes.Ok, "")
223 | renderer.Txt2Img(s.zctx, msg)
224 | return errcode.Success
225 | }
226 |
227 | // GetPlayerStats 获取玩家战绩
228 | func (s *Service) GetPlayerStats(ctx context.Context) error {
229 | nCtx, span := global.Tracer.Start(ctx, "GetPlayerStats")
230 | defer span.End()
231 | span.AddEvent("try to get player name")
232 | id, isVaild := s.getPlayerID(nCtx)
233 | if !isVaild {
234 | span.AddEvent("failed to get player")
235 | span.SetStatus(codes.Error, "get invalid player display name")
236 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 数据库中没有查到该账号! 请检查是否绑定! 如需绑定请使用[.绑定 id], 中括号不需要输入"))
237 | return errcode.NotFoundError
238 | }
239 | s.zctx.Send("少女折寿中...")
240 | span.AddEvent("try to get player status")
241 | stat, err := bf1player.GetStats(id)
242 | if err != nil {
243 | span.RecordError(err)
244 | span.SetStatus(codes.Error, "network error")
245 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 获取玩家战绩失败, 请自行检查id是否正确"))
246 | return errcode.NetworkError.WithDetails("bf1player.GetStats", err).WithZeroContext(s.zctx)
247 | }
248 | if stat.Rank == "" {
249 | span.SetStatus(codes.Error, "invalid status")
250 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("获取到的部分数据为空,请检查id是否有效"))
251 | return errcode.InternalError.WithDetails("Unexpected", errors.Errorf("%s stat.Rank is blank", id))
252 | }
253 | // 发送战绩
254 | // TODO: 修改为卡片发送, 部分数据不准确,等待更改
255 | txt := "id:" + id + "\n" +
256 | "等级:" + stat.Rank + "\n" +
257 | "游玩时长:" + stat.TimePlayed + "\n" +
258 | "总kd:" + stat.TotalKD + "(" + stat.Kills + "/" + stat.Deaths + ")" + "\n" +
259 | "总kpm:" + stat.KPM + "\n" +
260 | "准度:" + stat.Accuracy + "\n" +
261 | "爆头数:" + stat.Headshots + "\n" +
262 | "胜率:" + stat.WinPercent + "(" + stat.Wins + "/" + stat.Losses + ")" + "\n" +
263 | "场均击杀:" + stat.KillsPerGame + "\n" +
264 | "步战kd:" + stat.InfantryKD + "\n" +
265 | "步战击杀:" + stat.InfantryKills + "\n" +
266 | "步战kpm:" + stat.InfantryKPM + "\n" +
267 | "载具击杀:" + stat.VehicleKills + "\n" +
268 | "载具kpm:" + stat.VehicleKPM + "\n" +
269 | "近战击杀:" + stat.DogtagsTaken + "\n" +
270 | "最高连杀:" + stat.HighestKillStreak + "\n" +
271 | "最远爆头:" + stat.LongestHeadshot + "\n" +
272 | "MVP数:" + stat.MVP + "\n" +
273 | "作为神医拉起了 " + stat.Revives + " 人"
274 |
275 | span.AddEvent("success")
276 | span.SetStatus(codes.Ok, "")
277 | renderer.Txt2Img(s.zctx, txt)
278 | return errcode.Success
279 | }
280 |
281 | // GetPlayerWeapon 获取玩家武器
282 | func (s *Service) GetPlayerWeapon(ctx context.Context) error {
283 | nCtx, span := global.Tracer.Start(ctx, "GetPlayerWeapon")
284 | defer span.End()
285 |
286 | span.AddEvent("phase user command")
287 | str := strings.Split(s.zctx.State["regex_matched"].([]string)[1], " ")
288 | var id string
289 | span.SetStatus(codes.Ok, "")
290 | // 相当于只输入 .武器
291 | if str[0] == "" {
292 | return s.sendWeaponInfo(nCtx, id, bf1player.ALL)
293 | }
294 | if len(str) > 1 {
295 | id = str[1]
296 | }
297 | switch str[0] {
298 | // 除default 相当于输入 .武器 class id
299 | case "半自动", "semi":
300 | return s.sendWeaponInfo(nCtx, id, bf1player.Semi)
301 | case "冲锋枪", "冲锋":
302 | return s.sendWeaponInfo(nCtx, id, bf1player.SMG)
303 | case "轻机枪", "机枪":
304 | return s.sendWeaponInfo(nCtx, id, bf1player.LMG)
305 | case "步枪", "狙击枪", "狙击":
306 | return s.sendWeaponInfo(nCtx, id, bf1player.Bolt)
307 | case "霰弹枪", "散弹枪", "霰弹", "散弹":
308 | return s.sendWeaponInfo(nCtx, id, bf1player.Shotgun)
309 | case "配枪", "手枪", "副手":
310 | return s.sendWeaponInfo(nCtx, id, bf1player.Sidearm)
311 | case "近战", "刀":
312 | return s.sendWeaponInfo(nCtx, id, bf1player.Melee)
313 | case "手榴弹", "手雷", "雷":
314 | return s.sendWeaponInfo(nCtx, id, bf1player.Grenade)
315 | case "驾驶员", "坦克兵", "载具":
316 | return s.sendWeaponInfo(nCtx, id, bf1player.Dirver)
317 | case "配备", "装备":
318 | return s.sendWeaponInfo(nCtx, id, bf1player.Gadget)
319 | case "精英", "精英兵":
320 | return s.sendWeaponInfo(nCtx, id, bf1player.Elite)
321 | default:
322 | // 相当于 .武器 id
323 | if regexp.MustCompile(`\w+`).MatchString(str[0]) {
324 | id = str[0]
325 | return s.sendWeaponInfo(nCtx, id, bf1player.ALL)
326 | }
327 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 获取玩家武器失败, 不能识别的输入格式"))
328 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
329 | }
330 | }
331 |
332 | // GetPlayerVehicle 获取玩家载具信息
333 | func (s *Service) GetPlayerVehicle(ctx context.Context) error {
334 | nCtx, span := global.Tracer.Start(ctx, "GetPlayerVehicle")
335 | defer span.End()
336 | s.zctx.Send("少女折寿中...")
337 | span.AddEvent("try to get player")
338 | player, err := s.getPlayer(nCtx, s.zctx.State["regex_matched"].([]string)[1])
339 | if err != nil {
340 | span.RecordError(err)
341 | span.SetStatus(codes.Error, "get player failed")
342 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 数据库中没有查到该账号! 请检查是否绑定! 如需绑定请使用[.绑定 id], 中括号不需要输入"))
343 | return errcode.NotFoundError
344 | }
345 | span.AddEvent("try to get vehicle")
346 | car, err := bf1player.GetVehicles(player.PersonalID)
347 | if err != nil {
348 | span.RecordError(err)
349 | span.SetStatus(codes.Error, "get vehicle failed")
350 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 获取玩家载具失败, 请自行检查id是否正确"))
351 | return errcode.NetworkError.WithDetails("bf1player.GetVehicles", err).WithZeroContext(s.zctx)
352 | }
353 | msg := "id:" + player.DisplayName + "\n"
354 | for i := range *car {
355 | msg += "------------\n"
356 | msg += (*car)[i].Name + "\n"
357 | msg += fmt.Sprintf("%s%6.0f\t", "击杀数:", (*car)[i].Kills)
358 | msg += "kpm:" + (*car)[i].KPM + "\n"
359 | msg += fmt.Sprintf("%s%6.0f\t", "击毁数:", (*car)[i].Destroyed)
360 | msg += "游玩时间:" + (*car)[i].Time + " 小时\n"
361 | }
362 | span.AddEvent("success")
363 | span.SetStatus(codes.Ok, "")
364 | renderer.Txt2Img(s.zctx, msg)
365 | return errcode.Success
366 | }
367 |
368 | // GetBF1Exchange 获取BF1本期交换信息
369 | func (s *Service) GetBF1Exchange(ctx context.Context) error {
370 | _, span := global.Tracer.Start(ctx, "GetBF1Exchange")
371 | defer span.End()
372 | span.AddEvent("try to get exchange")
373 | exchange, err := bf1api.GetExchange()
374 | if err != nil {
375 | span.RecordError(err)
376 | span.SetStatus(codes.Error, "get exchange failed")
377 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERR: 获取交换失败"))
378 | return errcode.NetworkError.WithDetails("bf1api.GetExchange", err).WithZeroContext(s.zctx)
379 | }
380 | var msg string
381 | for i, v := range exchange {
382 | msg += i + ": \n"
383 | for _, skin := range v {
384 | msg += "\t" + skin + "\n"
385 | }
386 | }
387 | span.AddEvent("success")
388 | span.SetStatus(codes.Ok, "")
389 | renderer.Txt2Img(s.zctx, msg)
390 | return errcode.Success
391 | }
392 |
393 | // GetBF1OpreationPack 获取本期行动包信息
394 | func (s *Service) GetBF1OpreationPack(ctx context.Context) error {
395 | _, span := global.Tracer.Start(ctx, "GetBF1OpreationPack")
396 | defer span.End()
397 | span.AddEvent("try to get pack")
398 | pack, err := bf1api.GetCampaignPacks()
399 | if err != nil {
400 | span.RecordError(err)
401 | span.SetStatus(codes.Error, "get pack failed")
402 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERR: 获取行动包失败"))
403 | return errcode.NetworkError.WithDetails("bf1api.GetCampaignPacks", err).WithZeroContext(s.zctx)
404 | }
405 | var msg string
406 | msg += "行动名:" + pack.Name + "\n"
407 | msg += "剩余时间:" + fmt.Sprintf("%.2f", float64(pack.RemainTime)/60/24) + " 天\n"
408 | msg += "箱子重置时间:" + fmt.Sprintf("%.2f", float64(pack.ResetTime)/60) + " 小时\n"
409 | msg += "行动地图:" + pack.Op1Name + " 与 " + pack.Op2Name + "\n"
410 | msg += "行动简介:" + pack.Desc
411 |
412 | span.AddEvent("success")
413 | span.SetStatus(codes.Ok, "")
414 | renderer.Txt2Img(s.zctx, msg)
415 | return errcode.Success
416 | }
417 |
418 | // GetPlayerBanInfo 获取玩家联ban信息
419 | func (s *Service) GetPlayerBanInfo(ctx context.Context) error {
420 | nCtx, span := global.Tracer.Start(ctx, "GetPlayerBanInfo")
421 | defer span.End()
422 | s.zctx.Send("少女折寿中...")
423 | span.AddEvent("try to get player name")
424 | id, isVaild := s.getPlayerID(nCtx)
425 | if !isVaild {
426 | span.AddEvent("failed to get player")
427 | span.SetStatus(codes.Error, "get invalid player display name")
428 | s.zctx.SendChain(message.At(s.zctx.Event.UserID), message.Text("ERR: 数据库中没有查到该账号! 请检查是否绑定! 如需绑定请使用[.绑定 id], 中括号不需要输入"))
429 | return errcode.NotFoundError
430 | }
431 | span.AddEvent("try to get player ban info")
432 | info := bf1player.IsHacker(id)
433 | var msg string
434 | msg += "id: " + id + "\n"
435 | msg += "EAC: " + "\n\t" + info.EAC.Status + "\n\t案件链接: " + info.EAC.URL + "\n"
436 | msg += "BFBan: " + "\n\t状态: " + info.BFBan.Status + "\n\t"
437 | if info.BFBan.IsCheater {
438 | msg += "案件链接: " + info.BFBan.URL
439 | }
440 | span.AddEvent("success")
441 | span.SetStatus(codes.Ok, "")
442 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text(msg))
443 | return errcode.Success
444 | }
445 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/FloatTech/floatbox v0.0.0-20240505082030-226ec6713e14 h1:8O0Iq9MnKsKowltY9txhOqcJdmGTjxHPQ4gEYzbJc9A=
2 | github.com/FloatTech/floatbox v0.0.0-20240505082030-226ec6713e14/go.mod h1:OzGLhvmtz1TKIdGaJDd8pQumvD36UqK+dWsiCISmzQQ=
3 | github.com/FloatTech/gg v1.1.3 h1:+GlL02lTKsxJQr4WCuNwVxC1/eBZrCvypCIBtxuOFb4=
4 | github.com/FloatTech/gg v1.1.3/go.mod h1:/9oLP54CMfq4r+71XL26uaFTJ1uL1boAyX67680/1HE=
5 | github.com/FloatTech/imgfactory v0.2.2-0.20230315152233-49741fc994f9 h1:IzZLuM/fgKclyMaU/Qb1qlLdGrs2FTietkqOWhh07Gw=
6 | github.com/FloatTech/imgfactory v0.2.2-0.20230315152233-49741fc994f9/go.mod h1:el5hGpj1C1bDRxcTXYRwEivDCr40zZeJpcrLrB1fajs=
7 | github.com/FloatTech/rendercard v0.1.2 h1:W4SF9fSxv6Ava+kIUI0T1ILOjId/cgZ0huuEpMpHJbU=
8 | github.com/FloatTech/rendercard v0.1.2/go.mod h1:Sbojcy1t3NfFz7/WicZRmR/uKFxNMYkKF8qHx69dxY0=
9 | github.com/FloatTech/sqlite v1.7.0 h1:FGSn4pCR12kESozn7IvNx3U39dwR/AcFM9oPyGACsl0=
10 | github.com/FloatTech/sqlite v1.7.0/go.mod h1:/4tzfCGhrZnnjC1U8vcfwGQeF6eR649fhOsS3+Le0+s=
11 | github.com/FloatTech/ttl v0.0.0-20240716161252-965925764562 h1:snfw7FNFym1eNnLrQ/VCf80LiQo9C7jHgrunZDwiRcY=
12 | github.com/FloatTech/ttl v0.0.0-20240716161252-965925764562/go.mod h1:fHZFWGquNXuHttu9dUYoKuNbm3dzLETnIOnm1muSfDs=
13 | github.com/FloatTech/zbpctrl v1.7.0 h1:Hxo6EIhJo+pHjcQP9QgIJgluaT1pHH99zkk3njqTNMo=
14 | github.com/FloatTech/zbpctrl v1.7.0/go.mod h1:xmM4dSwHA02Gei3ogCRiG+RTrw/7Z69PfrN5NYf8BPE=
15 | github.com/KomeiDiSanXian/zbputils v0.0.0-20230923095115-55ba2c51620d h1:xDRTbCeUNaCWSzSqlmbOJE7VqTtYgn5tNKeCZmy9eyU=
16 | github.com/KomeiDiSanXian/zbputils v0.0.0-20230923095115-55ba2c51620d/go.mod h1:6DMCU2lhpS1x6BjM15XGzlAUcEPTKqjUaalmbJED198=
17 | github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
18 | github.com/RomiChan/syncx v0.0.0-20240418144900-b7402ffdebc7 h1:S/ferNiehVjNaBMNNBxUjLtVmP/YWD6Yh79RfPv4ehU=
19 | github.com/RomiChan/syncx v0.0.0-20240418144900-b7402ffdebc7/go.mod h1:vD7Ra3Q9onRtojoY5sMCLQ7JBgjUsrXDnDKyFxqpf9w=
20 | github.com/RomiChan/websocket v1.4.3-0.20220227141055-9b2c6168c9c5 h1:bBmmB7he0iVN4m5mcehfheeRUEer/Avo4ujnxI3uCqs=
21 | github.com/RomiChan/websocket v1.4.3-0.20220227141055-9b2c6168c9c5/go.mod h1:0UcFaCkhp6vZw6l5Dpq0Dp673CoF9GdvA8lTfst0GiU=
22 | github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
23 | github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
24 | github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs=
25 | github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
26 | github.com/cenkalti/backoff/v5 v5.0.2 h1:rIfFVxEf1QsI7E1ZHfp/B4DF/6QBAUhmgkxc0H7Zss8=
27 | github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
28 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
29 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
30 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
31 | github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM=
32 | github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
33 | github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
34 | github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
35 | github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
36 | github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
37 | github.com/ericpauley/go-quantize v0.0.0-20200331213906-ae555eb2afa4 h1:BBade+JlV/f7JstZ4pitd4tHhpN+w+6I+LyOS7B4fyU=
38 | github.com/ericpauley/go-quantize v0.0.0-20200331213906-ae555eb2afa4/go.mod h1:H7chHJglrhPPzetLdzBleF8d22WYOv7UM/lEKYiwlKM=
39 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=
40 | github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
41 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
42 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
43 | github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
44 | github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
45 | github.com/fumiama/bigfft v0.0.0-20211011143303-6e0bfa3c836b h1:Zt3pFQditAdWTHCOVkiloc9ZauBoWrb37guFV4iIRvE=
46 | github.com/fumiama/bigfft v0.0.0-20211011143303-6e0bfa3c836b/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
47 | github.com/fumiama/cron v1.3.0 h1:ZWlwuexF+HQHl3cYytEE5HNwD99q+3vNZF1GrEiXCFo=
48 | github.com/fumiama/cron v1.3.0/go.mod h1:bz5Izvgi/xEUI8tlBN8BI2jr9Moo8N4or0KV8xXuPDY=
49 | github.com/fumiama/go-base16384 v1.7.0 h1:6fep7XPQWxRlh4Hu+KsdH+6+YdUp+w6CwRXtMWSsXCA=
50 | github.com/fumiama/go-base16384 v1.7.0/go.mod h1:OEn+947GV5gsbTAnyuUW/SrfxJYUdYupSIQXOuGOcXM=
51 | github.com/fumiama/go-registry v0.2.7 h1:tLEqgEpsiybQMqBv0dLHm5leia/z1DhajMupwnOHeNs=
52 | github.com/fumiama/go-registry v0.2.7/go.mod h1:m+wp5fF8dYgVoFkBPZl+vlK90loymaJE0JCtocVQLEs=
53 | github.com/fumiama/go-simple-protobuf v0.2.0 h1:ACyN1MAlu7pDR3EszWgzUeNP+IRsSHwH6V9JCJA5R5o=
54 | github.com/fumiama/go-simple-protobuf v0.2.0/go.mod h1:5yYNapXq1tQMOZg9bOIVhQlZk9pQqpuFIO4DZLbsdy4=
55 | github.com/fumiama/gofastTEA v0.0.10 h1:JJJ+brWD4kie+mmK2TkspDXKzqq0IjXm89aGYfoGhhQ=
56 | github.com/fumiama/gofastTEA v0.0.10/go.mod h1:RIdbYZyB4MbH6ZBlPymRaXn3cD6SedlCu5W/HHfMPBk=
57 | github.com/fumiama/imgsz v0.0.4 h1:Lsasu2hdSSFS+vnD+nvR1UkiRMK7hcpyYCC0FzgSMFI=
58 | github.com/fumiama/imgsz v0.0.4/go.mod h1:bISOQVTlw9sRytPwe8ir7tAaEmyz9hSNj9n8mXMBG0E=
59 | github.com/fumiama/sqlite3 v1.20.0-with-win386 h1:ZR1AXGBEtkfq9GAXehOVcwn+aaCG8itrkgEsz4ggx5k=
60 | github.com/fumiama/sqlite3 v1.20.0-with-win386/go.mod h1:Os58MHwYCcYZCy2PGChBrQtBAw5/LS1ZZOkfc+C/I7s=
61 | github.com/fumiama/terasu v0.0.0-20240507144117-547a591149c0 h1:So/3Bg/m2ZcUvqCzzEjjkjHBjcvnV3AN5tCxwsdMwYU=
62 | github.com/fumiama/terasu v0.0.0-20240507144117-547a591149c0/go.mod h1:UVx8YP1jKKL1Cj+uy+OnQRM2Ih6U36Mqy9GSf7jabsI=
63 | github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
64 | github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
65 | github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
66 | github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
67 | github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
68 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
69 | github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
70 | github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
71 | github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
72 | github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
73 | github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
74 | github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
75 | github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
76 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
77 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
78 | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
79 | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
80 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
81 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
82 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
83 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
84 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
85 | github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
86 | github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o=
87 | github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs=
88 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
89 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
90 | github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
91 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
92 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
93 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
94 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
95 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
96 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
97 | github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4=
98 | github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
99 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
100 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
101 | github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
102 | github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
103 | github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
104 | github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
105 | github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
106 | github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
107 | github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
108 | github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
109 | github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
110 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
111 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
112 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
113 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
114 | github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
115 | github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
116 | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
117 | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
118 | github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
119 | github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
120 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
121 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
122 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
123 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
124 | github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
125 | github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
126 | github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
127 | github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
128 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
129 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
130 | github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
131 | github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
132 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
133 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
134 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
135 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
136 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
137 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
138 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
139 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
140 | github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
141 | github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
142 | github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
143 | github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
144 | github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
145 | github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
146 | github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
147 | github.com/wdvxdr1123/ZeroBot v1.8.1 h1:/+NV/mvheMgpWFDZjjlJBBUEZYsMtMYo3JeuNRQehjY=
148 | github.com/wdvxdr1123/ZeroBot v1.8.1/go.mod h1:C86nQ0gIdAri4K2vg8IIQIslt08zzrKMcqYt8zhkx1M=
149 | go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
150 | go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
151 | go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg=
152 | go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E=
153 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.36.0 h1:dNzwXjZKpMpE2JhmO+9HsPl42NIXFIFSUSSs0fiqra0=
154 | go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.36.0/go.mod h1:90PoxvaEB5n6AOdZvi+yWJQoE95U8Dhhw2bSyRqnTD0=
155 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.36.0 h1:nRVXXvf78e00EwY6Wp0YII8ww2JVWshZ20HfTlE11AM=
156 | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.36.0/go.mod h1:r49hO7CgrxY9Voaj3Xe8pANWtr0Oq916d0XAmOoCZAQ=
157 | go.opentelemetry.io/otel/metric v1.36.0 h1:MoWPKVhQvJ+eeXWHFBOPoBOi20jh6Iq2CcCREuTYufE=
158 | go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs=
159 | go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs=
160 | go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY=
161 | go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
162 | go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
163 | go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrsNd4w=
164 | go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA=
165 | go.opentelemetry.io/proto/otlp v1.6.0 h1:jQjP+AQyTf+Fe7OKj/MfkDrmK4MNVtw2NpXsf9fefDI=
166 | go.opentelemetry.io/proto/otlp v1.6.0/go.mod h1:cicgGehlFuNdgZkcALOCh3VE6K/u2tAjzlRhDwmVpZc=
167 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
168 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
169 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
170 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
171 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
172 | golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
173 | golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
174 | golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
175 | golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
176 | golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY=
177 | golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI=
178 | golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
179 | golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
180 | golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
181 | golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
182 | golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
183 | golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
184 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
185 | golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
186 | golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
187 | golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
188 | golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
189 | golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
190 | golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
191 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
192 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
193 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
194 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
195 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
196 | golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
197 | golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
198 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
199 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
200 | golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
201 | golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
202 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
203 | golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
204 | golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
205 | google.golang.org/genproto/googleapis/api v0.0.0-20250519155744-55703ea1f237 h1:Kog3KlB4xevJlAcbbbzPfRG0+X9fdoGM+UBRKVz6Wr0=
206 | google.golang.org/genproto/googleapis/api v0.0.0-20250519155744-55703ea1f237/go.mod h1:ezi0AVyMKDWy5xAncvjLWH7UcLBB5n7y2fQ8MzjJcto=
207 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250519155744-55703ea1f237 h1:cJfm9zPbe1e873mHJzmQ1nwVEeRDU/T1wXDK2kUSU34=
208 | google.golang.org/genproto/googleapis/rpc v0.0.0-20250519155744-55703ea1f237/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
209 | google.golang.org/grpc v1.72.1 h1:HR03wO6eyZ7lknl75XlxABNVLLFc2PAb6mHlYh756mA=
210 | google.golang.org/grpc v1.72.1/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
211 | google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
212 | google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
213 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
214 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
215 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
216 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
217 | gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
218 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
219 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
220 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
221 | modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
222 | modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
223 | modernc.org/ccgo/v4 v4.21.0 h1:kKPI3dF7RIag8YcToh5ZwDcVMIv6VGa0ED5cvh0LMW4=
224 | modernc.org/ccgo/v4 v4.21.0/go.mod h1:h6kt6H/A2+ew/3MW/p6KEoQmrq/i3pr0J/SiwiaF/g0=
225 | modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
226 | modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
227 | modernc.org/gc/v2 v2.5.0 h1:bJ9ChznK1L1mUtAQtxi0wi5AtAs5jQuw4PrPHO5pb6M=
228 | modernc.org/gc/v2 v2.5.0/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
229 | modernc.org/libc v1.61.0 h1:eGFcvWpqlnoGwzZeZe3PWJkkKbM/3SUGyk1DVZQ0TpE=
230 | modernc.org/libc v1.61.0/go.mod h1:DvxVX89wtGTu+r72MLGhygpfi3aUGgZRdAYGCAVVud0=
231 | modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
232 | modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
233 | modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
234 | modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
235 | modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
236 | modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
237 | modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
238 | modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
239 | modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
240 | modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
241 | modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
242 | modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
243 |
--------------------------------------------------------------------------------
/bfhelper/internal/service/server.go:
--------------------------------------------------------------------------------
1 | package service
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "strconv"
7 | "strings"
8 | "sync"
9 | "time"
10 |
11 | bf1api "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/bf1/api"
12 | bf1server "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/bf1/server"
13 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/errcode"
14 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/model"
15 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/internal/textutil"
16 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/global"
17 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/renderer"
18 | "github.com/KomeiDiSanXian/BFHelper/bfhelper/pkg/tracer"
19 | zero "github.com/wdvxdr1123/ZeroBot"
20 | "github.com/wdvxdr1123/ZeroBot/message"
21 | "go.opentelemetry.io/otel/codes"
22 | )
23 |
24 | type server struct {
25 | name, gameID, serverID, pgid string
26 | }
27 |
28 | // CreateGroup 所在群创建一个服务器群组
29 | //
30 | // @permission: GroupOwner
31 | func (s *Service) CreateGroup() error {
32 | o := s.zctx.State["args"].(string)
33 | owner, _ := strconv.ParseInt(o, 10, 64)
34 | create := func(o int64) error {
35 | err := s.dao.CreateGroup(s.zctx.Event.GroupID, o)
36 | if err != nil {
37 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 创建服务器群组失败"))
38 | return errcode.DataBaseCreateError
39 | }
40 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("创建成功!"))
41 | return errcode.Success
42 | }
43 | s.zctx.Send("少女折寿中...")
44 | if owner != 0 {
45 | return create(owner)
46 | }
47 | return create(s.zctx.Event.UserID)
48 | }
49 |
50 | // DeleteGroup 所在群删除服务器群组
51 | //
52 | // @permission: ServerOwner
53 | func (s *Service) DeleteGroup() error {
54 | err := s.dao.DeleteGroup(s.zctx.Event.GroupID)
55 | if err != nil {
56 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 删除服务器群组失败"))
57 | return errcode.DataBaseDeleteError
58 | }
59 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("删除成功"))
60 | return errcode.Success
61 | }
62 |
63 | // ChangeOwner 更换服务器群组所有人
64 | //
65 | // @permission: ServerOwner
66 | func (s *Service) ChangeOwner() error {
67 | o := s.zctx.State["args"].(string)
68 | owner, _ := strconv.ParseInt(o, 10, 64)
69 | if owner == 0 {
70 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 未输入要更换的QQ号"))
71 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
72 | }
73 | err := s.dao.UpdateOwner(s.zctx.Event.GroupID, owner)
74 | if err != nil {
75 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 更换服务器群组所属失败"))
76 | return errcode.DataBaseUpdateError
77 | }
78 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("更换成功"))
79 | s.Log().Infof("Group %d changed owner, new owner: %d", s.zctx.Event.GroupID, owner)
80 | return errcode.Success
81 | }
82 |
83 | func (s *Service) getServer(gameID string) (*server, error) {
84 | result, err := bf1api.GetServerFullInfo(gameID)
85 | if err != nil {
86 | return nil, err
87 | }
88 | srv := server{
89 | serverID: result.Get("result.rspInfo.server.serverId").Str,
90 | gameID: result.Get("result.serverInfo.gameId").Str,
91 | pgid: result.Get("result.serverInfo.guid").Str,
92 | }
93 | srv.name = result.Get("result.serverInfo.name").Str
94 | return &srv, nil
95 | }
96 |
97 | func (s *Service) addServerProcess(gameID string, groupID int64) error {
98 | server, err := s.getServer(gameID)
99 | if err != nil {
100 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 添加服务器 ", gameID, " 失败"))
101 | return err
102 | }
103 | err = s.dao.AddGroupServer(groupID, server.gameID, server.serverID, server.pgid, server.name)
104 | if err != nil {
105 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 添加服务器 ", gameID, " 失败"))
106 | return err
107 | }
108 | return nil
109 | }
110 |
111 | func (s *Service) addServer(gameID string, groupID int64, wg *sync.WaitGroup, mu *sync.Mutex) {
112 | mu.Lock()
113 | defer mu.Unlock()
114 | defer wg.Done()
115 | _ = s.addServerProcess(gameID, groupID)
116 | }
117 |
118 | func (s *Service) addServers(gameIDs []string, groupID int64) {
119 | var wg sync.WaitGroup
120 | var mu sync.Mutex
121 | for _, gameID := range gameIDs {
122 | wg.Add(1)
123 | go s.addServer(gameID, groupID, &wg, &mu)
124 | }
125 | wg.Wait()
126 | }
127 |
128 | // AddServer 添加服务器
129 | //
130 | // @permission: SuperAdmin
131 | func (s *Service) AddServer() error {
132 | str := s.zctx.State["args"].(string)
133 | if str == "" {
134 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 无效的输入"))
135 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
136 | }
137 | strs := strings.Split(str, " ")
138 | groupID, _ := strconv.ParseInt(strs[0], 10, 64)
139 | if len(strs) < 2 {
140 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: GameID 为空"))
141 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
142 | }
143 | s.addServers(strs[1:], groupID)
144 | s.Log().Infof("Added server %v to group %d", strs[1:], groupID)
145 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("添加完成"))
146 | return errcode.Success
147 | }
148 |
149 | // AddServerAdmin 添加服务器管理员
150 | //
151 | // @permission: ServerOwner
152 | func (s *Service) AddServerAdmin() error {
153 | str := s.zctx.State["args"].(string)
154 | if str == "" {
155 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 填写的管理员qq为空"))
156 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
157 | }
158 | admins := strings.Split(str, " ")
159 | qqs := make([]int64, 0, len(admins))
160 | for _, a := range admins {
161 | adminQQ, _ := strconv.ParseInt(a, 10, 64)
162 | qqs = append(qqs, adminQQ)
163 | }
164 | err := s.dao.AddGroupAdmin(s.zctx.Event.GroupID, qqs...)
165 | if err != nil {
166 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 添加管理失败"))
167 | return errcode.DataBaseUpdateError
168 | }
169 | s.Log().Infof("Group %d added admin: %v", s.zctx.Event.GroupID, qqs)
170 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("添加成功"))
171 | return errcode.Success
172 | }
173 |
174 | // SetServerAlias 设置服务器别名
175 | //
176 | // @permission: ServerAdmin
177 | func (s *Service) SetServerAlias() error {
178 | str := s.zctx.State["args"].(string)
179 | if str == "" {
180 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
181 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
182 | }
183 | strs := strings.Split(str, " ")
184 | if len(strs) != 2 {
185 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 不能识别的输入"))
186 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
187 | }
188 | gameID, alias := strs[0], strs[1]
189 | err := s.dao.ServerAlias(gameID, alias)
190 | if err != nil {
191 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 设置别名失败"))
192 | return errcode.DataBaseUpdateError
193 | }
194 | s.Log().Infof("Group %d changed server %s alias to %s", s.zctx.Event.GroupID, gameID, alias)
195 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("设置成功"))
196 | return errcode.Success
197 | }
198 |
199 | // DeleteServer 删除服务器
200 | //
201 | // @permission: ServerOwner
202 | func (s *Service) DeleteServer() error {
203 | gameID := s.zctx.State["args"].(string)
204 | if gameID == "" {
205 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
206 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
207 | }
208 | err := s.dao.RemoveGroupServer(s.zctx.Event.GroupID, gameID)
209 | if err != nil {
210 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 删除服务器 ", gameID, " 失败"))
211 | return errcode.DataBaseDeleteError
212 | }
213 | s.Log().Infof("Group %d deleted server %s", s.zctx.Event.GroupID, gameID)
214 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("删除成功"))
215 | return errcode.Success
216 | }
217 |
218 | // DeleteAdmin 删除群组服务器管理员
219 | //
220 | // @permission: ServerOwner
221 | func (s *Service) DeleteAdmin() error {
222 | o := s.zctx.State["args"].(string)
223 | qq, _ := strconv.ParseInt(o, 10, 64)
224 | if qq == 0 {
225 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
226 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
227 | }
228 | err := s.dao.RemoveGroupAdmin(s.zctx.Event.GroupID, qq)
229 | if err != nil {
230 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 删除管理员 ", qq, " 失败"))
231 | return errcode.DataBaseDeleteError
232 | }
233 | s.Log().Infof("Group %d removed server admin %d", s.zctx.Event.GroupID, qq)
234 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("删除成功"))
235 | return errcode.Success
236 | }
237 |
238 | func (s *Service) kickProcess(server model.Server, pid, reason string, msgChan chan string, wg *sync.WaitGroup) {
239 | defer wg.Done()
240 | name := server.NameInGroup
241 | if name == "" {
242 | name = server.ServerName
243 | }
244 | returned, err := bf1server.Kick(server.GameID, pid, reason)
245 | if err != nil {
246 | msgChan <- fmt.Sprintf("ERROR: 在 %s%s\n", name, " 踢出失败")
247 | } else {
248 | msgChan <- fmt.Sprintf("在 %s%s%s\n", name, " 踢出成功: ", returned)
249 | }
250 | }
251 |
252 | func (s *Service) kick(pid string, reason string, group *model.Group) {
253 | var wg sync.WaitGroup
254 | var tosend string
255 | msgChan := make(chan string, len(group.Servers))
256 | for _, server := range group.Servers {
257 | wg.Add(1)
258 | go s.kickProcess(server, pid, reason, msgChan, &wg)
259 | }
260 | wg.Wait()
261 | close(msgChan)
262 | for msg := range msgChan {
263 | tosend += msg
264 | }
265 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text(tosend))
266 | }
267 |
268 | // KickPlayer 在绑定的服务器里踢出玩家
269 | //
270 | // @permission: ServerAdmin
271 | func (s *Service) KickPlayer(ctx context.Context) error {
272 | nCtx, span := global.Tracer.Start(ctx, "KickPlayer")
273 | defer span.End()
274 | span.AddEvent("phase command")
275 | cmdString := s.zctx.State["args"].(string)
276 | if cmdString == "" {
277 | span.AddEvent("invalid command")
278 | span.SetStatus(codes.Error, "invalid command")
279 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
280 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
281 | }
282 | cmds := strings.Split(cmdString, " ")
283 | span.AddEvent("try to get group")
284 | group, err := s.dao.GetGroup(s.zctx.Event.GroupID)
285 | if err != nil {
286 | span.RecordError(err)
287 | span.SetStatus(codes.Error, "database error")
288 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 获取绑定服务器失败"))
289 | return errcode.DataBaseReadError.WithDetails("Error", err).WithZeroContext(s.zctx)
290 | }
291 | player := cmds[0]
292 | reason := "Admin kick"
293 | if len(cmds) >= 2 {
294 | reason = cmds[1]
295 | }
296 | span.AddEvent("traditionalize reason")
297 | reason = textutil.Traditionalize(reason)
298 | if cleaned, has := textutil.CleanPersonalID(player); has {
299 | span.AddEvent("start kick process", tracer.AddEventWithDescription(
300 | tracer.Description("operator", strconv.FormatInt(s.zctx.Event.UserID, 10)),
301 | tracer.Description("reason", reason),
302 | tracer.Description("at", strconv.FormatInt(s.zctx.Event.GroupID, 10)),
303 | tracer.Description("target", cleaned),
304 | ))
305 | s.kick(cleaned, reason, group)
306 | span.AddEvent("finish kick process")
307 | span.SetStatus(codes.Ok, "")
308 | return errcode.Success
309 | }
310 | span.AddEvent("try to get player info")
311 | pl, err := s.getPlayer(nCtx, player)
312 | if err != nil {
313 | span.RecordError(err)
314 | span.SetStatus(codes.Error, "get player info failed")
315 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 踢出失败: 未查询到目标玩家pid"))
316 | return errcode.NotFoundError.WithDetails("Error", err).WithZeroContext(s.zctx)
317 | }
318 | span.AddEvent("start kick process", tracer.AddEventWithDescription(
319 | tracer.Description("operator", strconv.FormatInt(s.zctx.Event.UserID, 10)),
320 | tracer.Description("reason", reason),
321 | tracer.Description("at", strconv.FormatInt(s.zctx.Event.GroupID, 10)),
322 | tracer.Description("target", pl.PersonalID),
323 | ))
324 | s.kick(pl.PersonalID, reason, group)
325 | span.AddEvent("finish kick process")
326 | span.SetStatus(codes.Ok, "")
327 |
328 | s.Log().Infof("Group %d try to kick player %s", group.GroupID, pl.DisplayName)
329 | return errcode.Success
330 | }
331 |
332 | // 单服务器封禁/解封
333 | func (s *Service) banFunc(ctx context.Context, banfunc func(sid string, pid string) error) error {
334 | nCtx, span := global.Tracer.Start(ctx, "SingleServer")
335 | defer span.End()
336 | span.AddEvent("phase command")
337 | cmdString := s.zctx.State["args"].(string)
338 | if cmdString == "" {
339 | span.AddEvent("invalid command")
340 | span.SetStatus(codes.Error, "invalid command")
341 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
342 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
343 | }
344 | cmds := strings.Split(cmdString, " ")
345 | if len(cmds) != 2 {
346 | span.AddEvent("invalid command")
347 | span.SetStatus(codes.Error, "invalid command")
348 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 不能识别的输入"))
349 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
350 | }
351 | srvName, player := cmds[0], cmds[1]
352 | span.AddEvent("try to get server")
353 | srv, err := s.dao.GetServerByAlias(s.zctx.Event.GroupID, srvName)
354 | if err != nil {
355 | span.RecordError(err)
356 | span.SetStatus(codes.Error, "get server failed")
357 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 查询服务器失败"))
358 | return errcode.DataBaseReadError.WithDetails("Error", err).WithZeroContext(s.zctx)
359 | }
360 | if cleaned, has := textutil.CleanPersonalID(player); has {
361 | span.AddEvent("start process", tracer.AddEventWithDescription(
362 | tracer.Description("operator", strconv.FormatInt(s.zctx.Event.UserID, 10)),
363 | tracer.Description("at", strconv.FormatInt(s.zctx.Event.GroupID, 10)),
364 | tracer.Description("target", cleaned),
365 | tracer.Description("server", srv.GameID),
366 | ))
367 | err := banfunc(srv.ServerID, cleaned)
368 | if err != nil {
369 | span.RecordError(err)
370 | span.SetStatus(codes.Error, "ban player failed")
371 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 失败"))
372 | return errcode.InternalError.WithDetails("Error", err).WithZeroContext(s.zctx)
373 | }
374 | span.AddEvent("success")
375 | span.SetStatus(codes.Ok, "")
376 | return errcode.Success
377 | }
378 | span.AddEvent("try to get player")
379 | pl, err := s.getPlayer(nCtx, player)
380 | if err != nil {
381 | span.RecordError(err)
382 | span.SetStatus(codes.Error, "get player failed")
383 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 未查询到目标玩家pid"))
384 | return errcode.NotFoundError.WithDetails("Error", err)
385 | }
386 | span.AddEvent("start process", tracer.AddEventWithDescription(
387 | tracer.Description("operator", strconv.FormatInt(s.zctx.Event.UserID, 10)),
388 | tracer.Description("at", strconv.FormatInt(s.zctx.Event.GroupID, 10)),
389 | tracer.Description("target", player),
390 | tracer.Description("server", srv.GameID),
391 | ))
392 | err = banfunc(srv.ServerID, pl.PersonalID)
393 | if err != nil {
394 | span.RecordError(err)
395 | span.SetStatus(codes.Error, "ban player failed")
396 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 失败"))
397 | return errcode.InternalError.WithDetails("Error", err).WithZeroContext(s.zctx)
398 | }
399 | span.AddEvent("success")
400 | span.SetStatus(codes.Ok, "")
401 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("操作", pl.DisplayName, "成功"))
402 | return errcode.Success
403 | }
404 |
405 | // 多服务器封禁/解封
406 | func (s *Service) bansFunc(ctx context.Context, banfunc func(sid string, pid string) error) error {
407 | nCtx, span := global.Tracer.Start(ctx, "MutipleServer")
408 | defer span.End()
409 | span.AddEvent("try to get player name")
410 | playerName := s.zctx.State["args"].(string)
411 | if playerName == "" {
412 | span.AddEvent("empty player name")
413 | span.SetStatus(codes.Error, "empty player name")
414 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
415 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
416 | }
417 | span.AddEvent("try to get player info")
418 | player, err := s.getPlayer(nCtx, playerName)
419 | if err != nil {
420 | span.RecordError(err)
421 | span.SetStatus(codes.Error, "get player failed")
422 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 未查询到目标玩家pid"))
423 | return errcode.NotFoundError.WithDetails("Error", err)
424 | }
425 | span.AddEvent("try to get group info")
426 | group, err := s.dao.GetGroup(s.zctx.Event.GroupID)
427 | if err != nil {
428 | span.RecordError(err)
429 | span.SetStatus(codes.Error, "get group failed")
430 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 获取绑定服务器失败"))
431 | return errcode.DataBaseReadError.WithDetails("Error", err).WithZeroContext(s.zctx)
432 | }
433 |
434 | var wg sync.WaitGroup
435 | var tosend string
436 | msgChan := make(chan string, len(group.Servers))
437 | span.AddEvent("start goroutine", tracer.AddEventWithDescription(
438 | tracer.Description("operator", strconv.FormatInt(s.zctx.Event.UserID, 10)),
439 | tracer.Description("at", strconv.FormatInt(s.zctx.Event.GroupID, 10)),
440 | tracer.Description("target", player.PersonalID),
441 | ))
442 | for _, server := range group.Servers {
443 | wg.Add(1)
444 | go s.bansProcess(&server, player, msgChan, &wg, banfunc)
445 | }
446 | wg.Wait()
447 | close(msgChan)
448 | for msg := range msgChan {
449 | tosend += msg
450 | }
451 | span.AddEvent("finish")
452 | span.SetStatus(codes.Ok, "")
453 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text(tosend))
454 | return errcode.Success
455 | }
456 |
457 | func (s *Service) bansProcess(srv *model.Server, player *model.Player, msgChan chan string, wg *sync.WaitGroup, banfunc func(sid string, pid string) error) {
458 | defer wg.Done()
459 | srvName := srv.NameInGroup
460 | if srvName == "" {
461 | srvName = srv.ServerName
462 | }
463 | err := banfunc(srv.ServerID, player.PersonalID)
464 | if err != nil {
465 | msgChan <- fmt.Sprintf("ERROR: 在 %s%s\n", srvName, " 操作失败")
466 | return
467 | }
468 | msgChan <- fmt.Sprintf("在 %s%s\n", srvName, " 操作成功")
469 | }
470 |
471 | // BanPlayer 指定一个已绑定的服务器中封禁玩家
472 | //
473 | // @permission: ServerAdmin
474 | // TODO: #13 添加 vban
475 | func (s *Service) BanPlayer(ctx context.Context) error {
476 | nCtx, span := global.Tracer.Start(ctx, "Ban")
477 | defer span.End()
478 | return s.banFunc(nCtx, bf1server.Ban)
479 | }
480 |
481 | // UnbanPlayer 指定一个已绑定的服务器中解封玩家
482 | //
483 | // @permission: ServerAdmin
484 | func (s *Service) UnbanPlayer(ctx context.Context) error {
485 | nCtx, span := global.Tracer.Start(ctx, "UnBan")
486 | defer span.End()
487 | return s.banFunc(nCtx, bf1server.Unban)
488 | }
489 |
490 | // BanPlayerAtAllServer 在所有已绑定的服务器里封禁玩家
491 | //
492 | // @permission: ServerAdmin
493 | func (s *Service) BanPlayerAtAllServer(ctx context.Context) error {
494 | nCtx, span := global.Tracer.Start(ctx, "BanAll")
495 | defer span.End()
496 | return s.bansFunc(nCtx, bf1server.Ban)
497 | }
498 |
499 | // UnbanPlayerAtAllServer 在所有已绑定的服务器里封禁玩家
500 | //
501 | // @permission: ServerAdmin
502 | func (s *Service) UnbanPlayerAtAllServer(ctx context.Context) error {
503 | nCtx, span := global.Tracer.Start(ctx, "UnBanAll")
504 | defer span.End()
505 | return s.bansFunc(nCtx, bf1server.Unban)
506 | }
507 |
508 | func (s *Service) sendMaps(maptxt string, next *zero.FutureEvent, srv *model.Server, maps []*bf1server.Map) error {
509 | renderer.Txt2Img(s.zctx, maptxt)
510 | recv, cancle := next.Repeat()
511 | defer cancle()
512 | tick := time.NewTimer(time.Minute)
513 | for {
514 | select {
515 | case <-tick.C:
516 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 等待回复超时"))
517 | return errcode.TimeoutError.WithZeroContext(s.zctx)
518 | case c := <-recv:
519 | index, _ := strconv.Atoi(c.Event.Message.String())
520 | if index >= len(maps) || index < 0 {
521 | s.zctx.SendChain(message.Reply(c.Event.MessageID), message.Text("ERROR: 无效的地图序号,取值范围为 0-", len(maps)-1))
522 | return errcode.InvalidParamsError.WithDetails("MapID", "out of index").WithZeroContext(c)
523 | }
524 | err := bf1server.ChangeMap(srv.PGID, index)
525 | if err != nil {
526 | s.zctx.SendChain(message.Reply(c.Event.MessageID), message.Text("ERROR: 切图失败"))
527 | return errcode.NetworkError.WithDetails("bf1server.ChangeMap", err)
528 | }
529 | s.zctx.SendChain(message.Reply(c.Event.MessageID), message.Text("已切到 ", maps[index].Name, "(", maps[index].Mode, ")"))
530 | return errcode.Success
531 | }
532 | }
533 | }
534 |
535 | // ChangeMap 切换指定服务器的地图
536 | //
537 | // @permission: ServerAdmin
538 | func (s *Service) ChangeMap() error {
539 | cmdString := s.zctx.State["args"].(string)
540 | if cmdString == "" {
541 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
542 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
543 | }
544 | cmds := strings.Split(cmdString, " ")
545 | srvName := cmds[0]
546 | srv, err := s.dao.GetServerByAlias(s.zctx.Event.GroupID, srvName)
547 | if err != nil {
548 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 找不到别名为 ", srvName, " 的服务器"))
549 | return errcode.NotFoundError.WithDetails("Error", err).WithZeroContext(s.zctx)
550 | }
551 | maps, err := bf1server.GetMapSlice(srv.GameID)
552 | if err != nil {
553 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 获取地图池失败"))
554 | return errcode.NetworkError.WithDetails("Error", err)
555 | }
556 |
557 | maptxt := "请在一分钟内选择一个序号来回复\n------\n图池序号和模式\n"
558 | for i, m := range maps {
559 | maptxt += fmt.Sprintf("\t%2d %s(%s)\n", i, m.Name, m.Mode)
560 | }
561 |
562 | next := zero.NewFutureEvent("message", 999, false, zero.RegexRule(`^\d{1,2}$`), zero.OnlyGroup, s.zctx.CheckSession())
563 | if len(cmds) == 1 {
564 | return s.sendMaps(maptxt, next, srv, maps)
565 | }
566 |
567 | index, _ := strconv.Atoi(cmds[1])
568 | if index >= len(maps) || index < 0 {
569 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 无效的地图序号,取值范围为 0-", len(maps)-1))
570 | return errcode.InvalidParamsError.WithDetails("MapID", "out of index").WithZeroContext(s.zctx)
571 | }
572 | err = bf1server.ChangeMap(srv.PGID, index)
573 | if err != nil {
574 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 切图失败"))
575 | return errcode.NetworkError.WithDetails("bf1server.ChangeMap", err)
576 | }
577 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("已切到 ", maps[index].Name, "(", maps[index].Mode, ")"))
578 | return errcode.Success
579 | }
580 |
581 | // GetMap 查看地图池
582 | //
583 | // @permission: Everyone
584 | func (s *Service) GetMap() error {
585 | srvName := s.zctx.State["args"].(string)
586 | if srvName == "" {
587 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 输入为空"))
588 | return errcode.InvalidParamsError.WithZeroContext(s.zctx)
589 | }
590 | srv, err := s.dao.GetServerByAlias(s.zctx.Event.GroupID, srvName)
591 | if err != nil {
592 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 找不到别名为 ", srvName, " 的服务器"))
593 | return errcode.NotFoundError.WithDetails("Error", err).WithZeroContext(s.zctx)
594 | }
595 | maps, err := bf1server.GetMapSlice(srv.GameID)
596 | if err != nil {
597 | s.zctx.SendChain(message.Reply(s.zctx.Event.MessageID), message.Text("ERROR: 获取地图池失败"))
598 | return errcode.NetworkError.WithDetails("bf1server.GetMapSlice", err)
599 | }
600 | maptxt := "图池序号和模式\n"
601 | for i, m := range maps {
602 | maptxt += fmt.Sprintf("\t%2d %s(%s)\n", i, m.Name, m.Mode)
603 | }
604 | renderer.Txt2Img(s.zctx, maptxt)
605 | return errcode.Success
606 | }
607 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------