Skip to content

Commit 6a2c7e8

Browse files
authored
feat: 签到失败时使用本地图片#1067 (#1068)
* update:签到失败时使用本地图片#1067 1. 修改score插件提示词,对用户更友好。 2. 图片下载失败时,会使用本地图片。 > 如果用户网络一直不通,可能会一直用某张图片作为背景 * update:修改score抽取本地图片逻辑
1 parent 9e8ae43 commit 6a2c7e8

File tree

1 file changed

+49
-3
lines changed

1 file changed

+49
-3
lines changed

plugin/score/sign_in.go

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package score
33

44
import (
55
"encoding/base64"
6+
"errors"
67
"io"
78
"math"
89
"math/rand"
@@ -156,7 +157,7 @@ func init() {
156157
}
157158
drawimage, err := styles[k](alldata)
158159
if err != nil {
159-
ctx.SendChain(message.Text("ERROR: ", err))
160+
ctx.SendChain(message.Text("签到成功,但签到图生成失败,请勿重复签到:\n", err))
160161
return
161162
}
162163
// done.
@@ -190,7 +191,7 @@ func init() {
190191
}
191192
picFile := cachePath + uidStr + time.Now().Format("20060102") + ".png"
192193
if file.IsNotExist(picFile) {
193-
ctx.SendChain(message.Reply(ctx.Event.MessageID), message.Text("请先签到!"))
194+
ctx.SendChain(message.Reply(ctx.Event.MessageID), message.Text("签到背景加载失败"))
194195
return
195196
}
196197
trySendImage(picFile, ctx)
@@ -332,7 +333,8 @@ func initPic(picFile string, uid int64) (avatar []byte, err error) {
332333
}
333334
url, err := bilibili.GetRealURL(backgroundURL)
334335
if err != nil {
335-
return
336+
// 使用本地已有的图片
337+
return avatar, copyImage(picFile)
336338
}
337339
data, err := web.RequestDataWith(web.NewDefaultClient(), url, "", referer, "", nil)
338340
if err != nil {
@@ -369,3 +371,47 @@ func trySendImage(filePath string, ctx *zero.Ctx) {
369371
return
370372
}
371373
}
374+
375+
// 从已有签到背景中,复制出一张图片
376+
func copyImage(picFile string) (err error) {
377+
// 读取目录中的文件列表,并随机挑选出一张图片
378+
cachePath := engine.DataFolder() + "cache/"
379+
files, err := os.ReadDir(cachePath)
380+
if err != nil {
381+
return err
382+
}
383+
384+
// 随机取10次图片,取到图片就break退出
385+
imgNum := len(files)
386+
var validFile string
387+
for i := 0; i < len(files) && i < 10; i++ {
388+
imgFile := files[rand.Intn(imgNum)]
389+
if !imgFile.IsDir() && strings.HasSuffix(imgFile.Name(), ".png") && !strings.HasSuffix(imgFile.Name(), "signin.png") {
390+
validFile = imgFile.Name()
391+
break
392+
}
393+
}
394+
if len(validFile) == 0 {
395+
return errors.New("copyImage: no local image")
396+
}
397+
selectedFile := cachePath + validFile
398+
399+
// 使用 io.Copy 复制签到背景
400+
srcFile, err := os.Open(selectedFile)
401+
if err != nil {
402+
return err
403+
}
404+
defer srcFile.Close()
405+
406+
dstFile, err := os.Create(picFile)
407+
if err != nil {
408+
return err
409+
}
410+
defer dstFile.Close()
411+
_, err = io.Copy(dstFile, srcFile)
412+
if err != nil {
413+
return err
414+
}
415+
416+
return err
417+
}

0 commit comments

Comments
 (0)