Skip to content

Commit

Permalink
feat: 签到失败时使用本地图片#1067 (#1068)
Browse files Browse the repository at this point in the history
* update:签到失败时使用本地图片#1067

1. 修改score插件提示词,对用户更友好。
2. 图片下载失败时,会使用本地图片。

> 如果用户网络一直不通,可能会一直用某张图片作为背景

* update:修改score抽取本地图片逻辑
  • Loading branch information
vatebur authored Nov 27, 2024
1 parent 9e8ae43 commit 6a2c7e8
Showing 1 changed file with 49 additions and 3 deletions.
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
}

0 comments on commit 6a2c7e8

Please sign in to comment.