diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml new file mode 100644 index 0000000..5531d91 --- /dev/null +++ b/.github/workflows/pull.yml @@ -0,0 +1,35 @@ +name: PullLint +on: [ pull_request ] +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - name: Set up Go + uses: actions/setup-go@master + with: + go-version: 1.19 + + - name: Check out code into the Go module directory + uses: actions/checkout@master + + - name: golangci-lint + uses: golangci/golangci-lint-action@master + with: + # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version + version: latest + + # Optional: working directory, useful for monorepos + # working-directory: somedir + + # Optional: golangci-lint command line arguments. + # args: --issues-exit-code=0 + + # Optional: show only new issues if it's a pull request. The default value is `false`. + # only-new-issues: true + + # Optional: if set to true then the action don't cache or restore ~/go/pkg. + # skip-pkg-cache: true + + # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. + # skip-build-cache: true \ No newline at end of file diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml new file mode 100644 index 0000000..4b4d234 --- /dev/null +++ b/.github/workflows/push.yml @@ -0,0 +1,32 @@ +name: PushLint +on: [ push ] +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - name: Set up Go + uses: actions/setup-go@master + with: + go-version: 1.19 + + - name: Check out code into the Go module directory + uses: actions/checkout@master + + - name: golangci-lint + uses: golangci/golangci-lint-action@master + with: + version: latest + + - name: Commit back + if: ${{ !github.head_ref }} + continue-on-error: true + run: | + git config --local user.name 'github-actions[bot]' + git config --local user.email '41898282+github-actions[bot]@users.noreply.github.com' + git add --all + git commit -m "🎨 改进代码样式" + - name: Create Pull Request + if: ${{ !github.head_ref }} + continue-on-error: true + uses: peter-evans/create-pull-request@v4 \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..5e73907 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,77 @@ +linters-settings: + errcheck: + ignore: fmt:.* + ignoretests: true + + goimports: + local-prefixes: github.com/FloatTech/AnimeAPI + + forbidigo: + # Forbid the following identifiers + forbid: + - ^fmt\.Errorf$ # consider errors.Errorf in github.com/pkg/errors + +linters: + # please, do not use `enable-all`: it's deprecated and will be removed soon. + # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint + disable-all: true + fast: false + enable: + - bodyclose + - depguard + - dogsled + - errcheck + - exportloopref + - exhaustive + #- funlen + #- goconst + - gocritic + #- gocyclo + - gofmt + - goimports + - goprintffuncname + #- gosec + - gosimple + - govet + - ineffassign + #- misspell + - nolintlint + - rowserrcheck + - staticcheck + - stylecheck + - typecheck + - unconvert + - unparam + - unused + - whitespace + - prealloc + - predeclared + - asciicheck + - revive + - forbidigo + - makezero + +run: + # default concurrency is a available CPU number. + # concurrency: 4 # explicitly omit this value to fully utilize available resources. + deadline: 5m + issues-exit-code: 1 + tests: false + skip-dirs: + - order + go: '1.19' + +# output configuration options +output: + format: "colored-line-number" + print-issued-lines: true + print-linter-name: true + uniq-by-line: true + +issues: + # Fix found issues (if it's supported by the linter) + fix: true + exclude-use-default: false + exclude: + - "Error return value of .((os.)?std(out|err)..*|.*Close|.*Seek|.*Flush|os.Remove(All)?|.*print(f|ln)?|os.(Un)?Setenv). is not check" + - 'identifier ".*" contain non-ASCII character: U\+.*' \ No newline at end of file diff --git a/aireply/qingyunke.go b/aireply/qingyunke.go index b2424f0..6b25845 100644 --- a/aireply/qingyunke.go +++ b/aireply/qingyunke.go @@ -19,7 +19,9 @@ type QYK struct { } const ( - QYKURL = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=%v" + // QYKURL api地址 + QYKURL = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=%v" + // QYKBotName ... QYKBotName = "菲菲" ) @@ -27,10 +29,12 @@ var ( qykMatchFace = regexp.MustCompile(`\{face:(\d+)\}(.*)`) ) +// NewQYK ... func NewQYK(u, name string, banwords ...string) *QYK { return &QYK{u: u, n: name, b: banwords} } +// String ... func (*QYK) String() string { return "青云客" } diff --git a/aireply/xiaoai.go b/aireply/xiaoai.go index df2dd85..8447b75 100644 --- a/aireply/xiaoai.go +++ b/aireply/xiaoai.go @@ -17,14 +17,18 @@ type XiaoAi struct { } const ( - XiaoAiURL = "http://81.70.100.130/api/xiaoai.php?n=text&msg=%v" + // XiaoAiURL api地址 + XiaoAiURL = "http://81.70.100.130/api/xiaoai.php?n=text&msg=%v" + // XiaoAiBotName ... XiaoAiBotName = "小爱" ) +// NewXiaoAi ... func NewXiaoAi(u, name string, banwords ...string) *XiaoAi { return &XiaoAi{u: u, n: name, b: banwords} } +// String ... func (*XiaoAi) String() string { return "小爱" } diff --git a/ascii2d/ascii2d.go b/ascii2d/ascii2d.go index d4c6828..47bc8ab 100644 --- a/ascii2d/ascii2d.go +++ b/ascii2d/ascii2d.go @@ -1,3 +1,4 @@ +// Package ascii2d ascii2d搜图api package ascii2d import ( @@ -10,6 +11,7 @@ import ( xpath "github.com/antchfx/htmlquery" ) +// Result ... type Result struct { Info string // Info 图片分辨率 格式 大小信息 Link string // Link 图片链接 @@ -20,7 +22,8 @@ type Result struct { Type string // Type pixiv / twitter ... } -func Ascii2d(image string) (r []*Result, err error) { +// ASCII2d ... +func ASCII2d(image string) (r []*Result, err error) { const api = "https://ascii2d.net/search/uri" client := web.NewTLS12Client() // 包装请求参数 diff --git a/ascii2d/ascii2d_test.go b/ascii2d/ascii2d_test.go index b885298..954ad91 100644 --- a/ascii2d/ascii2d_test.go +++ b/ascii2d/ascii2d_test.go @@ -8,7 +8,7 @@ import ( ) func TestSearch(t *testing.T) { - r, err := Ascii2d("https://gchat.qpic.cn/gchatpic_new//--05F47960F2546E874F515A403FD174DF/0?term=3") + r, err := ASCII2d("https://gchat.qpic.cn/gchatpic_new//--05F47960F2546E874F515A403FD174DF/0?term=3") if err != nil { t.Fatal(err) } diff --git a/bilibili/api.go b/bilibili/api.go index f8abf55..df2abd1 100644 --- a/bilibili/api.go +++ b/bilibili/api.go @@ -14,6 +14,7 @@ import ( ) var ( + // ErrAPINeedCookie ... ErrAPINeedCookie = errors.New("api need cookie") ) @@ -134,6 +135,9 @@ func GetMedalWall(cookiecfg *CookieConfig, uid string) (result []Medal, err erro func GetAllGuard(mid string) (guardUser GuardUser, err error) { var data []byte data, err = web.GetData(AllGuardURL) + if err != nil { + return + } m := gjson.ParseBytes(data).Get("@this").Map() err = json.Unmarshal(binary.StringToBytes(m[mid].String()), &guardUser) if err != nil { diff --git a/bilibili/types.go b/bilibili/types.go index 7141c3f..82c0819 100644 --- a/bilibili/types.go +++ b/bilibili/types.go @@ -265,24 +265,31 @@ type MedalInfo struct { MedalColorBorder int64 `json:"medal_color_border"` } +// Medal ... type Medal struct { Uname string `json:"target_name"` MedalInfo `json:"medal_info"` } +// MedalSorter ... type MedalSorter []Medal +// Len ... func (m MedalSorter) Len() int { return len(m) } + +// Swap ... func (m MedalSorter) Swap(i, j int) { m[i], m[j] = m[j], m[i] } + +// Less ... func (m MedalSorter) Less(i, j int) bool { return m[i].Level > m[j].Level } -// vtb信息 +// VtbDetail vtb信息 type VtbDetail struct { Mid int `json:"mid"` Uname string `json:"uname"` @@ -343,23 +350,26 @@ type Danmakusuki struct { } `json:"data"` } -// 配置结构体 +// CookieConfig 配置结构体 type CookieConfig struct { BilibiliCookie string `json:"bilibili_cookie"` file string } +// NewCookieConfig ... func NewCookieConfig(file string) *CookieConfig { return &CookieConfig{ file: file, } } +// Set ... func (cfg *CookieConfig) Set(cookie string) (err error) { cfg.BilibiliCookie = cookie return cfg.Save() } +// Load ... func (cfg *CookieConfig) Load() (cookie string, err error) { if cfg.BilibiliCookie != "" { cookie = cfg.BilibiliCookie @@ -379,6 +389,7 @@ func (cfg *CookieConfig) Load() (cookie string, err error) { return } +// Save ... func (cfg *CookieConfig) Save() (err error) { reader, err := os.Create(cfg.file) if err != nil { diff --git a/bilibili/util.go b/bilibili/util.go index 63b1396..d867095 100644 --- a/bilibili/util.go +++ b/bilibili/util.go @@ -13,8 +13,8 @@ func HumanNum(res int) string { return strconv.Itoa(res) } -// GetRealUrl 获取跳转后的链接 -func GetRealUrl(url string) (realurl string, err error) { +// GetRealURL 获取跳转后的链接 +func GetRealURL(url string) (realurl string, err error) { data, err := http.Head(url) if err != nil { return diff --git a/go.mod b/go.mod index 440c0bf..5db4fce 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/FloatTech/AnimeAPI -go 1.18 +go 1.19 require ( github.com/FloatTech/floatbox v0.0.0-20230111053652-a03d6334fadf diff --git a/huggingface/huggingface.go b/huggingface/huggingface.go index 60805d7..dab2d05 100644 --- a/huggingface/huggingface.go +++ b/huggingface/huggingface.go @@ -33,7 +33,7 @@ const ( TimeoutMax = 300 ) -// 推送默认请求 +// PushRequest 推送默认请求 type PushRequest struct { Action string `json:"action,omitempty"` FnIndex int `json:"fn_index"` @@ -41,18 +41,18 @@ type PushRequest struct { SessionHash string `json:"session_hash"` } -// 推送默认响应 +// PushResponse 推送默认响应 type PushResponse struct { Hash string `json:"hash"` QueuePosition int `json:"queue_position"` } -// 状态默认请求 +// StatusRequest 状态默认请求 type StatusRequest struct { Hash string `json:"hash"` } -// 状态默认响应 +// StatusResponse 状态默认响应 type StatusResponse struct { Status string `json:"status"` Data struct { @@ -62,7 +62,7 @@ type StatusResponse struct { } } -// 推送请求 +// Push 推送请求 func Push(pushURL string, pushReq PushRequest) (pushRes PushResponse, err error) { b, err := json.Marshal(pushReq) if err != nil { @@ -76,7 +76,7 @@ func Push(pushURL string, pushReq PushRequest) (pushRes PushResponse, err error) return } -// 状态请求 +// Status 状态请求 func Status(statusURL string, statusReq StatusRequest) (data []byte, err error) { b, err := json.Marshal(statusReq) if err != nil { diff --git a/neteasemusic/neteasemusic.go b/neteasemusic/neteasemusic.go index 8f5e06a..12f8a0b 100644 --- a/neteasemusic/neteasemusic.go +++ b/neteasemusic/neteasemusic.go @@ -78,7 +78,7 @@ type musicLrc struct { Code int `json:"code"` } -// 搜索网易云音乐歌曲 +// SearchMusic 搜索网易云音乐歌曲 // // keyword:搜索内容 n:输出数量 // @@ -124,7 +124,7 @@ func SearchMusic(keyword string, n int) (list map[string]int, err error) { return } -// 下载网易云音乐(歌曲ID,歌曲名称,下载路径) +// DownloadMusic 下载网易云音乐(歌曲ID,歌曲名称,下载路径) func DownloadMusic(musicID int, musicName, pathOfMusic string) error { downMusic := pathOfMusic + "/" + musicName + ".mp3" musicURL := "http://music.163.com/song/media/outer/url?id=" + strconv.Itoa(musicID) @@ -146,7 +146,7 @@ func DownloadMusic(musicID int, musicName, pathOfMusic string) error { return nil } -// 搜索网易云音乐歌词(歌曲ID) +// SreachLrc 搜索网易云音乐歌词(歌曲ID) func SreachLrc(musicID int) (lrc string, err error) { musicURL := "http://music.163.com/api/song/media?id=" + strconv.Itoa(musicID) data, err := web.GetData(musicURL) @@ -161,7 +161,7 @@ func SreachLrc(musicID int) (lrc string, err error) { return } -// 下载网易云音乐歌词(歌曲ID,歌曲名称,下载路径) +// DownloadLrc 下载网易云音乐歌词(歌曲ID,歌曲名称,下载路径) func DownloadLrc(musicID int, musicName, pathOfMusic string) error { err := os.MkdirAll(pathOfMusic, 0777) if err != nil { diff --git a/novelai/main.go b/novelai/main.go index b10337a..c515034 100644 --- a/novelai/main.go +++ b/novelai/main.go @@ -1,3 +1,4 @@ +// Package novelai ... package novelai import ( @@ -19,12 +20,14 @@ const ( genapi = "https://api.novelai.net/ai/generate-image" ) +// NovalAI ... type NovalAI struct { Tok string `json:"accessToken"` key string conf *Payload } +// NewNovalAI ... func NewNovalAI(key string, config *Payload) *NovalAI { return &NovalAI{ key: key, @@ -32,6 +35,7 @@ func NewNovalAI(key string, config *Payload) *NovalAI { } } +// Login ... func (nv *NovalAI) Login() error { if nv.Tok != "" { return nil @@ -47,6 +51,7 @@ func (nv *NovalAI) Login() error { return json.NewDecoder(resp.Body).Decode(nv) } +// Draw ... func (nv *NovalAI) Draw(tags string) (seed int, tagsproceeded string, img []byte, err error) { tags = strings.ReplaceAll(tags, ",", ",") if !strings.Contains(tags, ",") { @@ -101,6 +106,7 @@ func (nv *NovalAI) Draw(tags string) (seed int, tagsproceeded string, img []byte return } +// Para ... type Para struct { Width int `json:"width"` Height int `json:"height"` @@ -115,12 +121,14 @@ type Para struct { Uc string `json:"uc"` } +// Payload ... type Payload struct { Input string `json:"input"` Model string `json:"model"` Parameters Para `json:"parameters"` } +// NewDefaultPayload ... func NewDefaultPayload() *Payload { return &Payload{ Model: "safe-diffusion", @@ -139,6 +147,7 @@ func NewDefaultPayload() *Payload { } } +// String ... func (p *Payload) String() string { b, err := json.Marshal(p) if err != nil { @@ -147,6 +156,7 @@ func (p *Payload) String() string { return binary.BytesToString(b) } +// WrtieTo ... func (p *Payload) WrtieTo(w io.Writer) error { return json.NewEncoder(w).Encode(p) } diff --git a/nsfw/api.go b/nsfw/api.go index 51b53da..030349e 100644 --- a/nsfw/api.go +++ b/nsfw/api.go @@ -1,3 +1,4 @@ +// Package nsfw 图片鉴赏 package nsfw import ( @@ -7,6 +8,7 @@ import ( "github.com/FloatTech/floatbox/web" ) +// Picture ... type Picture struct { Sexy float64 `json:"sexy"` Neutral float64 `json:"neutral"` @@ -17,6 +19,7 @@ type Picture struct { const apiurl = "https://nsfwtag.azurewebsites.net/api/nsfw?url=" +// Classify ... func Classify(u string) (*Picture, error) { u = apiurl + url.QueryEscape(u) var data []byte diff --git a/pixiv/download.go b/pixiv/download.go index 1dc36b3..b5222cc 100644 --- a/pixiv/download.go +++ b/pixiv/download.go @@ -18,6 +18,7 @@ import ( "github.com/FloatTech/floatbox/web" ) +// CacheDir ... const CacheDir = "data/pixiv/" func init() { diff --git a/pixiv/pixiv.go b/pixiv/pixiv.go index 955f85b..fab5f2b 100644 --- a/pixiv/pixiv.go +++ b/pixiv/pixiv.go @@ -1,3 +1,4 @@ +// Package pixiv pixiv相关api package pixiv import ( @@ -10,7 +11,7 @@ import ( "github.com/tidwall/gjson" ) -// 插画结构体 +// Illust 插画结构体 type Illust struct { Pid int64 `db:"pid"` Title string `db:"title"` @@ -19,7 +20,7 @@ type Illust struct { ImageUrls []string `db:"image_urls"` AgeLimit string `db:"age_limit"` CreatedTime string `db:"created_time"` - UserId int64 `db:"user_id"` + UserID int64 `db:"user_id"` UserName string `db:"user_name"` } @@ -58,12 +59,12 @@ func Works(id int64) (i *Illust, err error) { } i.AgeLimit = ageLimit i.CreatedTime = json.Get("createDate").Str - i.UserId = json.Get("userId").Int() + i.UserID = json.Get("userId").Int() i.UserName = json.Get("userName").Str return i, err } -// 搜索元素 +// RankValue 搜索元素 type RankValue struct { /* required, possible rank modes: - daily (default) @@ -91,7 +92,7 @@ type RankValue struct { Date string } -// 画作排行榜 +// Rank 画作排行榜 func (value RankValue) Rank() (r [18]int, err error) { if value.Mode == "male_r18" || value.Mode == "male" || value.Mode == "female_r18" || value.Mode == "female" { value.Type = "all" diff --git a/qzone/types.go b/qzone/types.go index 81dde0f..ae0adc3 100644 --- a/qzone/types.go +++ b/qzone/types.go @@ -139,7 +139,7 @@ type MsgListRequest struct { Uin string `json:"uin"` } -// MsgListRequest 说说列表响应体 +// MsgListVo 说说列表响应体 type MsgListVo struct { AuthFlag int `json:"auth_flag"` CensorCount int `json:"censor_count"` @@ -196,7 +196,7 @@ type Pic struct { Width int `json:"width"` } -// 单个说说的详细信息 +// Msglist 单个说说的详细信息 type Msglist struct { Certified int `json:"certified"` Cmtnum int `json:"cmtnum"` @@ -242,7 +242,7 @@ type Usrinfo struct { Uin int `json:"uin"` } -// 空间点赞请求体 +// LikeRequest 空间点赞请求体 type LikeRequest struct { Curkey string `json:"curkey"` Face string `json:"face"` diff --git a/runoob/runoob.go b/runoob/runoob.go index 12fced3..4dc4ea1 100644 --- a/runoob/runoob.go +++ b/runoob/runoob.go @@ -1,3 +1,4 @@ +// Package runoob 在线运行代码 package runoob import ( @@ -13,6 +14,7 @@ import ( ) var ( + // Templates ... Templates = map[string]string{ "py2": "print 'Hello World!'", "ruby": "puts \"Hello World!\";", @@ -48,6 +50,7 @@ var ( "typescript": "const hello : string = \"Hello World!\"\nconsole.log(hello)", "ts": "const hello : string = \"Hello World!\"\nconsole.log(hello)", } + // LangTable ... LangTable = map[string][2]string{ "py2": {"0", "py"}, "ruby": {"1", "rb"}, diff --git a/scale/pilipili.go b/scale/pilipili.go index 5fdc99a..fb28902 100644 --- a/scale/pilipili.go +++ b/scale/pilipili.go @@ -1,3 +1,4 @@ +// Package scale 叔叔的放大二次元图片模型 package scale import ( @@ -10,18 +11,27 @@ import ( ) const ( + // ModelConservative ... ModelConservative = "conservative" - ModelNoDenoise = "no-denoise" - ModelDenoise1x = "denoise1x" - ModelDenoise2x = "denoise2x" - ModelDenoise3x = "denoise3x" + // ModelNoDenoise ... + ModelNoDenoise = "no-denoise" + // ModelDenoise1x ... + ModelDenoise1x = "denoise1x" + // ModelDenoise2x ... + ModelDenoise2x = "denoise2x" + // ModelDenoise3x ... + ModelDenoise3x = "denoise3x" ) var ( - Models = [...]string{ModelConservative, ModelNoDenoise, ModelDenoise1x, ModelDenoise2x, ModelDenoise3x} + // Models ... + Models = [...]string{ModelConservative, ModelNoDenoise, ModelDenoise1x, ModelDenoise2x, ModelDenoise3x} + // ErrInvModel ... ErrInvModel = errors.New("invaild model") + // ErrInvScale ... ErrInvScale = errors.New("invaild scale") - ErrInvTile = errors.New("invaild tile") + // ErrInvTile ... + ErrInvTile = errors.New("invaild tile") ) // Get model 0-4, scale 2-4, tile 0-4 diff --git a/setu/default.go b/setu/default.go index 5a410ab..68cf492 100644 --- a/setu/default.go +++ b/setu/default.go @@ -8,8 +8,10 @@ import ( "github.com/FloatTech/floatbox/web" ) +// DefaultPoolDir ... const DefaultPoolDir = "data/setupool" +// DefaultPool ... var DefaultPool = func() *Pool { p, err := NewPool(DefaultPoolDir, func(s string) (string, error) { typ := DefaultPoolDir + "/" + s diff --git a/setu/pool.go b/setu/pool.go index bc7f2c7..3f79cd1 100644 --- a/setu/pool.go +++ b/setu/pool.go @@ -21,6 +21,7 @@ import ( "github.com/sirupsen/logrus" ) +// Pool ... type Pool struct { folder string rolimg func(string) (string, error) // (typ) path @@ -29,11 +30,15 @@ type Pool struct { } var ( - ErrNilFolder = errors.New("nil folder") + // ErrNilFolder ... + ErrNilFolder = errors.New("nil folder") + // ErrNoSuchType ... ErrNoSuchType = errors.New("no such type") - ErrEmptyType = errors.New("empty type") + // ErrEmptyType ... + ErrEmptyType = errors.New("empty type") ) +// NewPool 新的缓存池 func NewPool(folder string, rolimg func(string) (string, error), getdat func(string) ([]byte, error), timeout time.Duration) (*Pool, error) { if folder == "" { return nil, ErrNilFolder @@ -55,6 +60,7 @@ func NewPool(folder string, rolimg func(string) (string, error), getdat func(str }, nil } +// Roll 从缓存池随机挑一张 func (p *Pool) Roll(typ string) (string, error) { d := p.folder + typ if p.rolimg == nil { @@ -117,6 +123,7 @@ func (p *Pool) Roll(typ string) (string, error) { } } +// RollLocal ... func (p *Pool) RollLocal(typ string) (string, error) { d := p.folder + typ if file.IsNotExist(d) { diff --git a/shindanmaker/shindanmaker.go b/shindanmaker/shindanmaker.go index 7e8310e..14be069 100644 --- a/shindanmaker/shindanmaker.go +++ b/shindanmaker/shindanmaker.go @@ -1,3 +1,4 @@ +// Package shindanmaker 基于 https://shindanmaker.com 的 API package shindanmaker import ( @@ -25,7 +26,7 @@ func Shindanmaker(id int64, name string) (string, error) { // seed 使每一天的结果都不同 now := time.Now() seed := fmt.Sprintf("%d%d%d", now.Year(), now.Month(), now.Day()) - name = name + seed + name += seed // 刷新 token 和 cookie if token == "" || cookie == "" { @@ -66,16 +67,18 @@ func Shindanmaker(id int64, name string) (string, error) { } var output = []string{} for child := list[0].FirstChild; child != nil; child = child.NextSibling { - if text := xpath.InnerText(child); text != "" { + text := xpath.InnerText(child) + switch { + case text != "": output = append(output, text) - } else if child.Data == "img" { + case child.Data == "img": img := child.Attr[1].Val if strings.Contains(img, "http") { output = append(output, "[CQ:image,file="+img[strings.Index(img, ",")+1:]+"]") } else { output = append(output, "[CQ:image,file=base64://"+img[strings.Index(img, ",")+1:]+"]") } - } else { + default: output = append(output, "\n") } } @@ -94,10 +97,7 @@ func refresh() error { // 获取 cookie if temp := resp.Header.Values("Set-Cookie"); len(temp) == 0 { return errors.New("刷新 cookie 时发生错误") - } else { - cookie = temp[len(temp)-1] - } - if !strings.Contains(cookie, "_session") { + } else if !strings.Contains(temp[len(temp)-1], "_session") { return errors.New("刷新 cookie 时发生错误") } // 获取 token diff --git a/tl/tl.go b/tl/tl.go index eeba43d..6c2eb69 100644 --- a/tl/tl.go +++ b/tl/tl.go @@ -1,3 +1,4 @@ +// Package tl 翻译api package tl import ( @@ -6,6 +7,7 @@ import ( "github.com/tidwall/gjson" ) +// Translate ... func Translate(target string) (string, error) { data, err := web.GetData("http://api.cloolc.club/fanyi?data=" + target) if err != nil { diff --git a/tts/baidutts/baidutts.go b/tts/baidutts/baidutts.go index 6360fcf..fa3b654 100644 --- a/tts/baidutts/baidutts.go +++ b/tts/baidutts/baidutts.go @@ -30,6 +30,7 @@ const ( ) var ( + // BaiduttsModes ... BaiduttsModes = map[int]string{0: "女声", 1: "男声", 3: "度逍遥", 4: "度丫丫"} ) diff --git a/tts/genshin/api.go b/tts/genshin/api.go index 0043873..149a5bc 100644 --- a/tts/genshin/api.go +++ b/tts/genshin/api.go @@ -1,6 +1,7 @@ package genshin const ( + // CNAPI api地址 CNAPI = "https://genshin.azurewebsites.net/api/speak?format=ogg&id=%d&text=%s&code=%s" ) @@ -58,6 +59,7 @@ var TestRecord = map[string]string{ "鹿野院平藏": "我叫鹿野院平藏,是天领奉行里破案最多最快的侦探……", } +// SoundList ... var SoundList = [...]string{ "派蒙", "凯亚", "安柏", "丽莎", "琴", "香菱", "枫原万叶", "迪卢克", "温迪", "可莉", diff --git a/tts/genshin/vits.go b/tts/genshin/vits.go index fa1037e..9691a5b 100644 --- a/tts/genshin/vits.go +++ b/tts/genshin/vits.go @@ -1,3 +1,4 @@ +// Package genshin 原神vits语音api package genshin import ( diff --git a/tts/mockingbird/mocking_bird.go b/tts/mockingbird/mocking_bird.go index 00c878a..4023c31 100644 --- a/tts/mockingbird/mocking_bird.go +++ b/tts/mockingbird/mocking_bird.go @@ -36,8 +36,8 @@ var ( exampleFileMap = map[int]string{0: azfile, 1: wjfile, 2: ysgfile} ) -// MockingBirdTTS 类 -type MockingBirdTTS struct { +// TTS 类 +type TTS struct { vocoder int synt int name string @@ -45,11 +45,12 @@ type MockingBirdTTS struct { } // String 服务名 -func (tts *MockingBirdTTS) String() string { +func (tts *TTS) String() string { return modeName + tts.name } -func NewMockingBirdTTS(synt int) (*MockingBirdTTS, error) { +// NewMockingBirdTTS ... +func NewMockingBirdTTS(synt int) (*TTS, error) { if synt < 0 || synt < 1 { synt = 0 } @@ -70,11 +71,11 @@ func NewMockingBirdTTS(synt int) (*MockingBirdTTS, error) { return nil, err } } - return &MockingBirdTTS{1, synt, mockingbirdModes[synt], exampleFileMap[synt]}, nil + return &TTS{1, synt, mockingbirdModes[synt], exampleFileMap[synt]}, nil } // Speak 返回音频本地路径 -func (tts *MockingBirdTTS) Speak(uid int64, text func() string) (fileName string, err error) { +func (tts *TTS) Speak(uid int64, text func() string) (fileName string, err error) { // 异步 rch := make(chan string, 1) sch := make(chan string, 1) @@ -97,7 +98,7 @@ func (tts *MockingBirdTTS) Speak(uid int64, text func() string) (fileName string return } -func (tts *MockingBirdTTS) getSyntPath() (syntPath string, err error) { +func (tts *TTS) getSyntPath() (syntPath string, err error) { data, err := web.GetData(synthesizersURL) if err != nil { return @@ -106,7 +107,7 @@ func (tts *MockingBirdTTS) getSyntPath() (syntPath string, err error) { return } -func (tts *MockingBirdTTS) getWav(text, syntPath, vocoder string, uid int64) (fileName string, err error) { +func (tts *TTS) getWav(text, syntPath, vocoder string, uid int64) (fileName string, err error) { if syntPath == "" { err = errors.New("nil syntPath") return diff --git a/tts/tts.go b/tts/tts.go index d88d948..f4f5159 100644 --- a/tts/tts.go +++ b/tts/tts.go @@ -1,6 +1,7 @@ // Package tts 文字转语音库 package tts +// TTS ... type TTS interface { // Speak 返回音频本地路径 Speak(key int64, text func() string) (fileName string, err error) diff --git a/wallet/wallet.go b/wallet/wallet.go index ce0aed0..73e9ad0 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -54,7 +54,7 @@ func GetWalletOf(uid int64) (money int) { return sdb.getWalletOf(uid).Money } -// GetWalletInfoGroup 获取多人钱包数据 +// GetGroupWalletOf 获取多人钱包数据 // // if sort == true,由高到低排序; if sort == false,由低到高排序 func GetGroupWalletOf(sortable bool, uids ...int64) (wallets []Wallet, err error) { @@ -68,11 +68,11 @@ func InsertWalletOf(uid int64, money int) error { } // 获取钱包数据 -func (sql *Storage) getWalletOf(uid int64) (Wallet Wallet) { +func (sql *Storage) getWalletOf(uid int64) (wallet Wallet) { sql.RLock() defer sql.RUnlock() uidstr := strconv.FormatInt(uid, 10) - _ = sql.db.Find("storage", &Wallet, "where uid is "+uidstr) + _ = sql.db.Find("storage", &wallet, "where uid is "+uidstr) return } diff --git a/wenxinAI/erniemodle/erniemodle.go b/wenxinAI/erniemodle/erniemodle.go index 1417134..04b6f56 100644 --- a/wenxinAI/erniemodle/erniemodle.go +++ b/wenxinAI/erniemodle/erniemodle.go @@ -17,7 +17,7 @@ type tokendata struct { Data string `json:"data"` } -// 获取当天的token +// GetToken 获取当天的token // // 申请账号链接:https://wenxin.baidu.com/moduleApi/key // @@ -50,11 +50,11 @@ type parsed struct { Msg string `json:"msg"` Data struct { Result string `json:"result"` - RequestId string `json:"requestId"` + RequestID string `json:"requestId"` } `json:"data"` } -// 创建任务 +// GetResult 创建任务 // // token:GetToken函数获取, // @@ -62,27 +62,27 @@ type parsed struct { // // txt:用户输入文本 // -// min_dec_len:最小生成长度[1, seq_len] +// mindeclen:最小生成长度[1, seq_len] // -// seq_len:最大生成长度[1, 1000] +// seqlen:最大生成长度[1, 1000] // -// seq_len决定生成时间:生成512需要16.3s,生成256需要8.1s,生成128需要4.1s +// seqlen决定生成时间:生成512需要16.3s,生成256需要8.1s,生成128需要4.1s // -// task_prompt:任务类型(非必需) +// taskprompt:任务类型(非必需) // // model:写作文: 1; 写文案: 2; 写摘要: 3; 对对联: 4; 自由问答: 5; 写小说: 6; 补全文本: 7; 自定义: 8; // // task_prompt只支持以下: // PARAGRAPH:引导模型生成一段文章; SENT:引导模型生成一句话; ENTITY:引导模型生成词组; Summarization:摘要; MT:翻译; Text2Annotation:抽取; Correction:纠错; QA_MRC:阅读理解; Dialogue:对话; QA_Closed_book: 闭卷问答; QA_Multi_Choice:多选问答; QuestionGeneration:问题生成; Paraphrasing:复述; NLI:文本蕴含识别; SemanticMatching:匹配; Text2SQL:文本描述转SQL;TextClassification:文本分类; SentimentClassification:情感分析; zuowen:写作文; adtext:写文案; couplet:对对联; novel:写小说; cloze:文 -func GetResult(token string, model int, txt string, min_dec_len, seq_len int, task_prompt ...string) (result string, err error) { +func GetResult(token string, model int, txt string, mindeclen, seqlen int, taskprompt ...string) (result string, err error) { requestURL := "https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernie/3.0.2" + strconv.Itoa(model) + "/zeus?" + "access_token=" + url.QueryEscape(token) postData := url.Values{} postData.Add("text", txt) - postData.Add("min_dec_len", strconv.Itoa(min_dec_len)) - postData.Add("seq_len", strconv.Itoa(seq_len)) + postData.Add("min_dec_len", strconv.Itoa(mindeclen)) + postData.Add("seq_len", strconv.Itoa(seqlen)) postData.Add("topp", "1.0") - postData.Add("task_prompt", task_prompt[0]) + postData.Add("task_prompt", taskprompt[0]) data, err := web.PostData(requestURL, "application/x-www-form-urlencoded", strings.NewReader(postData.Encode())) if err != nil { return diff --git a/wenxinAI/ernievilg/ernievilg.go b/wenxinAI/ernievilg/ernievilg.go index 01f4da0..cd139f8 100644 --- a/wenxinAI/ernievilg/ernievilg.go +++ b/wenxinAI/ernievilg/ernievilg.go @@ -17,7 +17,7 @@ type tokendata struct { Data string `json:"data"` } -// 获取当天的token +// GetToken 获取当天的token // // 申请账号链接:https://wenxin.baidu.com/moduleApi/key // @@ -54,7 +54,7 @@ type workstate struct { } `json:"data"` } -// 创建画图任务 +// BuildWork 创建画图任务 // // token:GetToken函数获取, // @@ -92,36 +92,37 @@ type picdata struct { Code int `json:"code"` Msg string `json:"msg"` Data struct { - Img string `json:"img"` - Waiting string `json:"waiting"` - ImgUrls []picUrls `json:"imgUrls"` - CreateTime string `json:"createTime"` - RequestID string `json:"requestId"` - Style string `json:"style"` - Text string `json:"text"` - Resolution string `json:"resolution"` - TaskID int `json:"taskId"` - Status int `json:"status"` + Img string `json:"img"` + Waiting string `json:"waiting"` + ImgUrls []PicURL `json:"imgUrls"` + CreateTime string `json:"createTime"` + RequestID string `json:"requestId"` + Style string `json:"style"` + Text string `json:"text"` + Resolution string `json:"resolution"` + TaskID int `json:"taskId"` + Status int `json:"status"` } `json:"data"` } -type picUrls struct { +// PicURL ... +type PicURL struct { Image string `json:"image"` Score interface{} `json:"score"` } -// 获取图片内容 +// GetPic 获取图片内容 // // token由GetToken函数获取,taskID由BuildWork函数获取 // -// picurls:[x]struct{Image:图片链接,Score:评分} +// PicURL:[x]struct{Image:图片链接,Score:评分} // // API会返回x张图片,数量不确定的,随机的。 // // 评分目前都是null,我不知道有什么用,既然API预留了,我也预留吧 // // stauts:结果状态,"30s"代表还在排队生成,"0"表示结果OK -func GetPic(token string, taskID int) (picurls []picUrls, status string, err error) { +func GetPic(token string, taskID int) (picurls []PicURL, status string, err error) { requestURL := "https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernievilg/v1/getImg?access_token=" + url.QueryEscape(token) + "&taskId=" + strconv.Itoa(taskID) postData := url.Values{} diff --git a/yandex/yandex.go b/yandex/yandex.go index 1e6159d..879a451 100644 --- a/yandex/yandex.go +++ b/yandex/yandex.go @@ -1,7 +1,8 @@ +// Package yandex yandex搜图 package yandex import ( - "fmt" + "errors" "net/http" "net/url" "strconv" @@ -10,6 +11,7 @@ import ( xpath "github.com/antchfx/htmlquery" ) +// Yandex yandex搜图 func Yandex(image string) (*pixiv.Illust, error) { search, _ := url.Parse("https://yandex.com/images/search") search.RawQuery = url.Values{ @@ -40,18 +42,18 @@ func Yandex(image string) (*pixiv.Illust, error) { // 取出每个返回的结果 list := xpath.Find(doc, `/html/body/div[3]/div[2]/div[1]/div/div[1]/div[1]/div[2]/div[2]/div/section/div[2]/div[1]/div[1]/a`) if len(list) != 1 { - return nil, fmt.Errorf("Yandex not found") + return nil, errors.New("Yandex not found") } link := list[0].Attr[1].Val dest, _ := url.Parse(link) rawid := dest.Query().Get("illust_id") if rawid == "" { - return nil, fmt.Errorf("Yandex not found") + return nil, errors.New("Yandex not found") } // 链接取出PIXIV id id, _ := strconv.ParseInt(rawid, 10, 64) if id == 0 { - return nil, fmt.Errorf("convert to pid error") + return nil, errors.New("convert to pid error") } illust, err := pixiv.Works(id)