🎨 优化代码结构

This commit is contained in:
源文雨 2022-04-06 11:15:24 +08:00
parent a6bd717971
commit 4ab968d563
6 changed files with 148 additions and 85 deletions

View File

@ -146,19 +146,21 @@ func init() {
}
}
facePath := cachePath + id + "vupFace.png"
initFacePic(facePath, u.Face)
err = initFacePic(facePath, u.Face)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
var backX int
var backY int
back, err := gg.LoadImage(facePath)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
backX = 500
backY = 500
} else {
return
}
back = img.Limit(back, 500, 500)
backX = back.Bounds().Size().X
backY = back.Bounds().Size().Y
}
if len(vups) > 50 {
ctx.SendChain(message.Text(u.Name + "关注的up主太多了只展示前50个up"))
vups = vups[:50]
@ -264,22 +266,27 @@ func init() {
engine.OnFullMatch("更新vup", zero.SuperUserPermission).SetBlock(true).
Handle(func(ctx *zero.Ctx) {
ctx.SendChain(message.Text("少女祈祷中..."))
updateVup()
err := updateVup()
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
ctx.SendChain(message.Text("vup已更新"))
})
}
func initFacePic(filename, faceURL string) {
func initFacePic(filename, faceURL string) error {
if file.IsNotExist(filename) {
data, err := web.GetData(faceURL)
if err != nil {
log.Errorln("[bilibili]", err)
return err
}
err = os.WriteFile(filename, data, 0666)
if err != nil {
log.Errorln("[bilibili]", err)
return err
}
}
return nil
}
func int2rbg(t int64) (int64, int64, int64) {

View File

@ -7,7 +7,6 @@ import (
"github.com/FloatTech/zbputils/web"
_ "github.com/fumiama/sqlite3" // use sql
"github.com/jinzhu/gorm"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
@ -84,11 +83,11 @@ func (vdb *vupdb) filterVup(ids []int64) (vups []vup, err error) {
return
}
func updateVup() {
func updateVup() error {
for _, v := range vtbURLs {
data, err := web.GetData(v)
if err != nil {
log.Errorln("[bilibili]:", err)
return err
}
gjson.Get(binary.BytesToString(data), "@this").ForEach(func(key, value gjson.Result) bool {
mid := value.Get("mid").Int()
@ -96,11 +95,15 @@ func updateVup() {
roomid := value.Get("roomid").Int()
err = vdb.insertVupByMid(mid, uname, roomid)
if err != nil {
log.Errorln("[bilibili]:", err)
return false
}
return true
})
if err != nil {
return err
}
}
return nil
}
func (vdb *vupdb) setBilibiliCookie(cookie string) (err error) {

View File

@ -81,7 +81,12 @@ func init() {
var ok bool
if name, ok = upMap[buid]; !ok {
var status int
status, name = checkBuid(buid)
var err error
status, name, err = checkBuid(buid)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
if status != 0 {
msg, ok := uidErrorMsg[status]
if !ok {
@ -96,10 +101,10 @@ func init() {
gid = -ctx.Event.UserID
}
if err := subscribe(buid, gid); err != nil {
log.Errorln("[bilibilipush]:", err)
} else {
ctx.SendChain(message.Text("已添加" + name + "的订阅"))
ctx.SendChain(message.Text("ERROR:", err))
return
}
ctx.SendChain(message.Text("已添加" + name + "的订阅"))
})
en.OnRegex(`^取消b站订阅\s?(\d+)$`, zero.UserOrGrpAdmin).SetBlock(true).Handle(func(ctx *zero.Ctx) {
buid, _ := strconv.ParseInt(ctx.State["regex_matched"].([]string)[1], 10, 64)
@ -107,7 +112,12 @@ func init() {
var ok bool
if name, ok = upMap[buid]; !ok {
var status int
status, name = checkBuid(buid)
var err error
status, name, err = checkBuid(buid)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
if status != 0 {
msg, ok := uidErrorMsg[status]
if !ok {
@ -122,10 +132,10 @@ func init() {
gid = -ctx.Event.UserID
}
if err := unsubscribe(buid, gid); err != nil {
log.Errorln("[bilibilipush]:", err)
} else {
ctx.SendChain(message.Text("已取消" + name + "的订阅"))
ctx.SendChain(message.Text("ERROR:", err))
return
}
ctx.SendChain(message.Text("已取消" + name + "的订阅"))
})
en.OnRegex(`^取消b站动态订阅\s?(\d+)$`, zero.UserOrGrpAdmin).SetBlock(true).Handle(func(ctx *zero.Ctx) {
buid, _ := strconv.ParseInt(ctx.State["regex_matched"].([]string)[1], 10, 64)
@ -133,7 +143,12 @@ func init() {
var ok bool
if name, ok = upMap[buid]; !ok {
var status int
status, name = checkBuid(buid)
var err error
status, name, err = checkBuid(buid)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
if status != 0 {
msg, ok := uidErrorMsg[status]
if !ok {
@ -148,10 +163,10 @@ func init() {
gid = -ctx.Event.UserID
}
if err := unsubscribeDynamic(buid, gid); err != nil {
log.Errorln("[bilibilipush]:", err)
} else {
ctx.SendChain(message.Text("已取消" + name + "的动态订阅"))
ctx.SendChain(message.Text("ERROR:", err))
return
}
ctx.SendChain(message.Text("已取消" + name + "的动态订阅"))
})
en.OnRegex(`^取消b站直播订阅\s?(\d+)$`, zero.UserOrGrpAdmin).SetBlock(true).Handle(func(ctx *zero.Ctx) {
buid, _ := strconv.ParseInt(ctx.State["regex_matched"].([]string)[1], 10, 64)
@ -159,7 +174,12 @@ func init() {
var ok bool
if name, ok = upMap[buid]; !ok {
var status int
status, name = checkBuid(buid)
var err error
status, name, err = checkBuid(buid)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
if status != 0 {
msg, ok := uidErrorMsg[status]
if !ok {
@ -174,10 +194,10 @@ func init() {
gid = -ctx.Event.UserID
}
if err := unsubscribeLive(buid, gid); err != nil {
log.Errorln("[bilibilipush]:", err)
} else {
ctx.SendChain(message.Text("已取消" + name + "的直播订阅"))
ctx.SendChain(message.Text("ERROR:", err))
return
}
ctx.SendChain(message.Text("已取消" + name + "的直播订阅"))
})
en.OnFullMatch("b站推送列表", zero.UserOrGrpAdmin).SetBlock(true).Handle(func(ctx *zero.Ctx) {
gid := ctx.Event.GroupID
@ -208,7 +228,8 @@ func init() {
}
data, err := text.RenderToBase64(msg, text.FontFile, 600, 20)
if err != nil {
log.Errorln("[bilibilipush]:", err)
ctx.SendChain(message.Text("ERROR:", err))
return
}
if id := ctx.SendChain(message.Image("base64://" + binary.BytesToString(data))); id.ID() == 0 {
ctx.SendChain(message.Text("ERROR:可能被风控了"))
@ -221,15 +242,15 @@ func bilibiliPushDaily() {
defer t.Stop()
for range t.C {
log.Debugln("-----bilibilipush拉取推送信息-----")
sendDynamic()
sendLive()
_ = sendDynamic()
_ = sendLive()
}
}
func checkBuid(buid int64) (status int, name string) {
func checkBuid(buid int64) (status int, name string, err error) {
data, err := web.RequestDataWith(web.NewDefaultClient(), fmt.Sprintf(infoURL, buid), "GET", referer, ua)
if err != nil {
log.Errorln("[bilibilipush]:", err)
return
}
status = int(gjson.Get(binary.BytesToString(data), "code").Int())
name = gjson.Get(binary.BytesToString(data), "data.name").String()
@ -284,37 +305,37 @@ func unsubscribeLive(buid, groupid int64) (err error) {
return
}
func getUserDynamicCard(buid int64) (cardList []gjson.Result) {
func getUserDynamicCard(buid int64) (cardList []gjson.Result, err error) {
data, err := web.RequestDataWith(web.NewDefaultClient(), fmt.Sprintf(userDynamicURL, buid), "GET", referer, ua)
if err != nil {
log.Errorln("[bilibilipush]:", err)
return
}
cardList = gjson.Get(binary.BytesToString(data), "data.cards").Array()
return
}
func getLiveList(uids ...int64) string {
func getLiveList(uids ...int64) (string, error) {
m := make(map[string]interface{})
m["uids"] = uids
b, _ := json.Marshal(m)
data, err := web.PostData(liveListURL, "application/json", bytes.NewReader(b))
if err != nil {
log.Errorln("[bilibilipush]:", err)
return "", err
}
return binary.BytesToString(data)
return binary.BytesToString(data), nil
}
func sendDynamic() {
func sendDynamic() error {
uids := bdb.getAllBuidByDynamic()
for _, buid := range uids {
cardList := getUserDynamicCard(buid)
if len(cardList) == 0 {
return
cardList, err := getUserDynamicCard(buid)
if err != nil {
return err
}
t, ok := lastTime[buid]
if !ok {
lastTime[buid] = cardList[0].Get("desc.timestamp").Int()
return
return nil
}
for i := len(cardList) - 1; i >= 0; i-- {
ct := cardList[i].Get("desc.timestamp").Int()
@ -502,8 +523,6 @@ func sendDynamic() {
ctx.SendGroupMessage(gid, msg)
case gid < 0:
ctx.SendPrivateMessage(-gid, msg)
default:
log.Errorln("[bilibilipush]:gid为0")
}
}
}
@ -513,11 +532,16 @@ func sendDynamic() {
}
}
}
return nil
}
func sendLive() {
func sendLive() error {
uids := bdb.getAllBuidByLive()
gjson.Get(getLiveList(uids...), "data").ForEach(func(key, value gjson.Result) bool {
ll, err := getLiveList(uids...)
if err != nil {
return err
}
gjson.Get(ll, "data").ForEach(func(key, value gjson.Result) bool {
newStatus := int(value.Get("live_status").Int())
if newStatus == 2 {
newStatus = 0
@ -556,8 +580,6 @@ func sendLive() {
ctx.SendGroupMessage(gid, msg)
case gid < 0:
ctx.SendPrivateMessage(-gid, msg)
default:
log.Errorln("[bilibilipush]:gid为0")
}
}
}
@ -569,4 +591,5 @@ func sendLive() {
}
return true
})
return nil
}

View File

@ -95,23 +95,22 @@ func (ThirdCategory) TableName() string {
}
// GetAllFirstCategoryMessage 取出所有vtb
func (vdb *VtbDB) GetAllFirstCategoryMessage() string {
func (vdb *VtbDB) GetAllFirstCategoryMessage() (string, error) {
db := (*gorm.DB)(vdb)
firstStepMessage := "请选择一个vtb并发送序号:\n"
var fcl []FirstCategory
err := db.Debug().Model(&FirstCategory{}).Find(&fcl).Error
if err != nil {
log.Errorln("[vtb/model]数据库读取错误", err)
return ""
return "", err
}
for _, v := range fcl {
firstStepMessage += strconv.FormatInt(v.FirstCategoryIndex, 10) + ". " + v.FirstCategoryName + "\n"
}
return firstStepMessage
return firstStepMessage, nil
}
// GetAllSecondCategoryMessageByFirstIndex 取得同一个vtb所有语录类别
func (vdb *VtbDB) GetAllSecondCategoryMessageByFirstIndex(firstIndex int) string {
func (vdb *VtbDB) GetAllSecondCategoryMessageByFirstIndex(firstIndex int) (string, error) {
db := (*gorm.DB)(vdb)
secondStepMessage := "请选择一个语录类别并发送序号:\n"
var scl []SecondCategory
@ -119,17 +118,16 @@ func (vdb *VtbDB) GetAllSecondCategoryMessageByFirstIndex(firstIndex int) string
db.Model(FirstCategory{}).Where("first_category_index = ?", firstIndex).First(&fc)
err := db.Debug().Model(&SecondCategory{}).Find(&scl, "first_category_uid = ?", fc.FirstCategoryUID).Error
if err != nil || len(scl) == 0 {
log.Errorln("[vtb/model]数据库读取错误", err)
return ""
return "", err
}
for _, v := range scl {
secondStepMessage += strconv.FormatInt(v.SecondCategoryIndex, 10) + ". " + v.SecondCategoryName + "\n"
}
return secondStepMessage
return secondStepMessage, nil
}
// GetAllThirdCategoryMessageByFirstIndexAndSecondIndex 取得同一个vtb同个类别的所有语录
func (vdb *VtbDB) GetAllThirdCategoryMessageByFirstIndexAndSecondIndex(firstIndex, secondIndex int) string {
func (vdb *VtbDB) GetAllThirdCategoryMessageByFirstIndexAndSecondIndex(firstIndex, secondIndex int) (string, error) {
db := (*gorm.DB)(vdb)
thirdStepMessage := "请选择一个语录并发送序号:\n"
var fc FirstCategory
@ -137,13 +135,12 @@ func (vdb *VtbDB) GetAllThirdCategoryMessageByFirstIndexAndSecondIndex(firstInde
var tcl []ThirdCategory
err := db.Debug().Model(&ThirdCategory{}).Find(&tcl, "first_category_uid = ? and second_category_index = ?", fc.FirstCategoryUID, secondIndex).Error
if err != nil || len(tcl) == 0 {
log.Errorln("[vtb/model]数据库读取错误", err)
return ""
return "", err
}
for _, v := range tcl {
thirdStepMessage = thirdStepMessage + strconv.FormatInt(v.ThirdCategoryIndex, 10) + ". " + v.ThirdCategoryName + "\n"
}
return thirdStepMessage
return thirdStepMessage, nil
}
// GetThirdCategory ...
@ -182,32 +179,28 @@ func (vdb *VtbDB) Close() error {
const vtbURL = "https://vtbkeyboard.moe/api/get_vtb_list"
// GetVtbList ...
func (vdb *VtbDB) GetVtbList() (uidList []string) {
func (vdb *VtbDB) GetVtbList() (uidList []string, err error) {
db := (*gorm.DB)(vdb)
client := &http.Client{}
req, err := http.NewRequest("GET", vtbURL, nil)
if err != nil {
log.Errorln(err)
return
}
// 自定义Header
req.Header.Set("User-Agent", web.RandUA())
resp, err := client.Do(req)
if err != nil {
log.Errorln(err)
return
}
defer resp.Body.Close()
bytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
return
}
vtbListStr, err := strconv.Unquote(strings.ReplaceAll(strconv.Quote(string(bytes)), `\\u`, `\u`))
if err != nil {
log.Errorln(err)
return
}
@ -240,37 +233,33 @@ func (vdb *VtbDB) GetVtbList() (uidList []string) {
uidList = append(uidList, fc.FirstCategoryUID)
}
return uidList
return
}
// StoreVtb ...
func (vdb *VtbDB) StoreVtb(uid string) {
func (vdb *VtbDB) StoreVtb(uid string) (err error) {
db := (*gorm.DB)(vdb)
vtbURL := "https://vtbkeyboard.moe/api/get_vtb_page?uid=" + uid
client := &http.Client{}
req, err := http.NewRequest("GET", vtbURL, nil)
if err != nil {
log.Errorln(err)
return
}
// 自定义Header
req.Header.Set("User-Agent", web.RandUA())
resp, err := client.Do(req)
if err != nil {
log.Errorln(err)
return
}
defer resp.Body.Close()
bytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorln(err)
return
}
vtbStr, err := strconv.Unquote(strings.ReplaceAll(strconv.Quote(string(bytes)), `\\u`, `\u`))
if err != nil {
log.Errorln(err)
return
}
@ -333,4 +322,5 @@ func (vdb *VtbDB) StoreVtb(uid string) {
}
}
}
return
}

View File

@ -62,7 +62,12 @@ func init() {
}
defer db.Close()
defer cancel()
firstStepImageBytes, err := text.RenderToBase64(db.GetAllFirstCategoryMessage(), text.FontFile, 400, 20)
r, err := db.GetAllFirstCategoryMessage()
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
firstStepImageBytes, err := text.RenderToBase64(r, text.FontFile, 400, 20)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
@ -91,11 +96,20 @@ func init() {
ctx.SendChain(message.Reply(c.Event.MessageID), message.Text("请输入正确的序号,三次输入错误,指令可退出重输"))
errorCount++
} else {
secondStepMessage := db.GetAllSecondCategoryMessageByFirstIndex(firstIndex)
secondStepMessage, err := db.GetAllSecondCategoryMessageByFirstIndex(firstIndex)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
// log.Debugln(secondStepMessage)
if secondStepMessage == "" {
ctx.SendChain(message.Reply(c.Event.MessageID), message.Text("你选择的序号没有内容,请重新选择,三次输入错误,指令可退出重输"))
firstStepImageBytes, err := text.RenderToBase64(db.GetAllFirstCategoryMessage(), text.FontFile, 400, 20)
r, err := db.GetAllFirstCategoryMessage()
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
firstStepImageBytes, err := text.RenderToBase64(r, text.FontFile, 400, 20)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
@ -124,11 +138,20 @@ func init() {
ctx.SendChain(message.Reply(c.Event.MessageID), message.Text("请输入正确的序号,三次输入错误,指令可退出重输"))
errorCount++
} else {
thirdStepMessage := db.GetAllThirdCategoryMessageByFirstIndexAndSecondIndex(firstIndex, secondIndex)
thirdStepMessage, err := db.GetAllThirdCategoryMessageByFirstIndexAndSecondIndex(firstIndex, secondIndex)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
// log.Debugln(thirdStepMessage)
if thirdStepMessage == "" {
ctx.SendChain(message.Reply(c.Event.MessageID), message.Text("你选择的序号没有内容,请重新选择,三次输入错误,指令可退出重输"))
secondStepMessageBytes, err := text.RenderToBase64(db.GetAllSecondCategoryMessageByFirstIndex(firstIndex), text.FontFile, 400, 20)
r, err := db.GetAllSecondCategoryMessageByFirstIndex(firstIndex)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
secondStepMessageBytes, err := text.RenderToBase64(r, text.FontFile, 400, 20)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
@ -162,7 +185,12 @@ func init() {
recURL := tc.ThirdCategoryPath
if recURL == "" {
ctx.SendChain(message.Reply(c.Event.MessageID), message.Text("没有内容请重新选择,三次输入错误,指令可退出重输"))
firstStepImageBytes, err := text.RenderToBase64(db.GetAllFirstCategoryMessage(), text.FontFile, 400, 20)
r, err := db.GetAllFirstCategoryMessage()
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
firstStepImageBytes, err := text.RenderToBase64(r, text.FontFile, 400, 20)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
@ -251,10 +279,19 @@ func init() {
ctx.Send("少女祈祷中......")
db := model.Initialize(dbfile)
if db != nil {
for _, v := range db.GetVtbList() {
db.StoreVtb(v)
vl, err := db.GetVtbList()
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
err := db.Close()
for _, v := range vl {
err = db.StoreVtb(v)
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return
}
}
err = db.Close()
if err != nil {
ctx.SendChain(message.Text("ERROR:", err))
return

View File

@ -211,8 +211,11 @@ EMOTICONLOOP:
mu.RUnlock()
if y.PictureList == "" {
mu.Lock()
storeEmoticonPic(emoticonIDList[i])
err = storeEmoticonPic(emoticonIDList[i])
mu.Unlock()
if err != nil {
return err
}
} else {
break EMOTICONLOOP
}