diff --git a/plugin/zaobao/zaobao.go b/plugin/zaobao/zaobao.go index d1624052..6ceded13 100644 --- a/plugin/zaobao/zaobao.go +++ b/plugin/zaobao/zaobao.go @@ -2,15 +2,14 @@ package zaobao import ( - "os" - "time" + "sync" "github.com/tidwall/gjson" zero "github.com/wdvxdr1123/ZeroBot" "github.com/wdvxdr1123/ZeroBot/message" + "github.com/FloatTech/zbputils/binary" control "github.com/FloatTech/zbputils/control" - "github.com/FloatTech/zbputils/file" "github.com/FloatTech/zbputils/web" "github.com/FloatTech/zbputils/control/order" @@ -22,6 +21,11 @@ const ( ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66" ) +var ( + picdata []byte + mu sync.Mutex +) + func init() { // 插件主体 engine := control.Register("zaobao", order.AcquirePrio(), &control.Options{ DisableOnDefault: true, @@ -32,41 +36,34 @@ func init() { // 插件主体 "每天早上九点定时发送\n" + "记录在'00 9 * * *'触发的指令\n" + "今日早报", - PrivateDataFolder: "zaobao", }) - cachePath := engine.DataFolder() - os.RemoveAll(cachePath) - err := os.MkdirAll(cachePath, 0755) - if err != nil { - panic(err) - } - zaobaoFile := cachePath + "zaobao_" + time.Now().Format("2006-01-02") + ".jpg" engine.OnFullMatch("今日早报", zero.OnlyGroup).SetBlock(false). Handle(func(ctx *zero.Ctx) { - err := download(zaobaoFile) + err := getdata() if err != nil { ctx.SendChain(message.Text("ERROR:", err)) return } - ctx.SendChain(message.Image("file:///" + file.BOTPATH + "/" + zaobaoFile)) + ctx.SendChain(message.ImageBytes(picdata)) }) } -func download(zaobaoFile string) error { // 获取图片链接并且下载 - if file.IsNotExist(zaobaoFile) { - data, err := web.GetDataWith(web.NewDefaultClient(), api, "GET", "", ua) - if err != nil { - return err - } - zaobaoURL := gjson.Get(string(data), "url").String() - data, err = web.GetDataWith(web.NewDefaultClient(), zaobaoURL, "GET", referer, ua) - if err != nil { - return err - } - err = os.WriteFile(zaobaoFile, data, 0666) - if err != nil { - return err - } +func getdata() error { // 获取图片链接并且下载 + if picdata != nil { + return nil + } + mu.Lock() + defer mu.Unlock() + if picdata != nil { + return nil + } + data, err := web.GetDataWith(web.NewDefaultClient(), api, "GET", "", ua) + if err != nil { + return err + } + picdata, err = web.GetDataWith(web.NewDefaultClient(), gjson.Get(binary.BytesToString(data), "url").String(), "GET", referer, ua) + if err != nil { + return err } return nil }