From 6a2c7e8740bff4eae60dc32531d97ade16e9a86b Mon Sep 17 00:00:00 2001 From: vatebur <67186678+vatebur@users.noreply.github.com> Date: Wed, 27 Nov 2024 12:57:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=AD=BE=E5=88=B0=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E6=97=B6=E4=BD=BF=E7=94=A8=E6=9C=AC=E5=9C=B0=E5=9B=BE=E7=89=87?= =?UTF-8?q?#1067=20(#1068)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * update:签到失败时使用本地图片#1067 1. 修改score插件提示词,对用户更友好。 2. 图片下载失败时,会使用本地图片。 > 如果用户网络一直不通,可能会一直用某张图片作为背景 * update:修改score抽取本地图片逻辑 --- plugin/score/sign_in.go | 52 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/plugin/score/sign_in.go b/plugin/score/sign_in.go index 13fc9d42b6..64cb41a9d8 100644 --- a/plugin/score/sign_in.go +++ b/plugin/score/sign_in.go @@ -3,6 +3,7 @@ package score import ( "encoding/base64" + "errors" "io" "math" "math/rand" @@ -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. @@ -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) @@ -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 { @@ -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 +}