Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update:签到失败时使用本地图片#1067 #1068

Merged
merged 2 commits into from
Nov 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions plugin/score/sign_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package score

import (
"encoding/base64"
"errors"
"io"
"math"
"math/rand"
Expand Down Expand Up @@ -156,7 +157,7 @@ func init() {
}
drawimage, err := styles[k](alldata)
if err != nil {
ctx.SendChain(message.Text("ERROR: ", err))
ctx.SendChain(message.Text("签到成功,但签到图生成失败,请勿重复签到:\n", err))
return
}
// done.
Expand Down Expand Up @@ -190,7 +191,7 @@ func init() {
}
picFile := cachePath + uidStr + time.Now().Format("20060102") + ".png"
if file.IsNotExist(picFile) {
ctx.SendChain(message.Reply(ctx.Event.MessageID), message.Text("请先签到!"))
ctx.SendChain(message.Reply(ctx.Event.MessageID), message.Text("签到背景加载失败"))
return
}
trySendImage(picFile, ctx)
Expand Down Expand Up @@ -332,7 +333,8 @@ func initPic(picFile string, uid int64) (avatar []byte, err error) {
}
url, err := bilibili.GetRealURL(backgroundURL)
if err != nil {
return
// 使用本地已有的图片
return avatar, copyImage(picFile)
}
data, err := web.RequestDataWith(web.NewDefaultClient(), url, "", referer, "", nil)
if err != nil {
Expand Down Expand Up @@ -369,3 +371,47 @@ func trySendImage(filePath string, ctx *zero.Ctx) {
return
}
}

// 从已有签到背景中,复制出一张图片
func copyImage(picFile string) (err error) {
// 读取目录中的文件列表,并随机挑选出一张图片
cachePath := engine.DataFolder() + "cache/"
files, err := os.ReadDir(cachePath)
if err != nil {
return err
}

// 随机取10次图片,取到图片就break退出
imgNum := len(files)
var validFile string
for i := 0; i < len(files) && i < 10; i++ {
imgFile := files[rand.Intn(imgNum)]
if !imgFile.IsDir() && strings.HasSuffix(imgFile.Name(), ".png") && !strings.HasSuffix(imgFile.Name(), "signin.png") {
validFile = imgFile.Name()
break
}
}
if len(validFile) == 0 {
return errors.New("copyImage: no local image")
}
selectedFile := cachePath + validFile

// 使用 io.Copy 复制签到背景
srcFile, err := os.Open(selectedFile)
if err != nil {
return err
}
defer srcFile.Close()

dstFile, err := os.Create(picFile)
if err != nil {
return err
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return err
}

return err
}
Loading