🎨 改进代码结构

This commit is contained in:
Yiwen-Chan 2021-04-16 19:18:43 +08:00
parent 66ff92e064
commit 1cf005a394
2 changed files with 21 additions and 25 deletions

View File

@ -1,19 +1,19 @@
package utils
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
xpath "github.com/antchfx/htmlquery"
"github.com/wdvxdr1123/ZeroBot/message"
)
// Ascii2dSearch Ascii2d 以图搜图
// 第一个参数 返回错误
// 第二个参数 返回的信息
func Ascii2dSearch(pic string) (text string, err error) {
func Ascii2dSearch(pic string) (message.Message, error) {
var (
api = "https://ascii2d.net/search/uri"
)
@ -35,7 +35,7 @@ func Ascii2dSearch(pic string) (text string, err error) {
req.Header.Set("Accept", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0")
resp, err := client.Do(req)
if err != nil {
return "", err
return nil, err
}
// 色合检索改变到特征检索
var bovwUrl = strings.ReplaceAll(resp.Request.URL.String(), "color", "bovw")
@ -44,13 +44,13 @@ func Ascii2dSearch(pic string) (text string, err error) {
bovwReq.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36")
bovwResp, err := client.Do(bovwReq)
if err != nil {
return "", err
return nil, err
}
defer bovwResp.Body.Close()
// 解析XPATH
doc, err := xpath.Parse(resp.Body)
if err != nil {
return "", err
return nil, err
}
// 取出每个返回的结果
list := xpath.Find(doc, `//div[@class="row item-box"]`)
@ -69,32 +69,29 @@ func Ascii2dSearch(pic string) (text string, err error) {
// 链接取出PIXIV id
var index = strings.LastIndex(link, "/")
if link == "" || index == -1 {
return "", errors.New("Ascii2d not found")
return nil, fmt.Errorf("Ascii2d not found")
}
var id = Str2Int(link[index+1:])
if id == 0 {
return "", errors.New("convert to pid error")
return nil, fmt.Errorf("convert to pid error")
}
// 根据PID查询插图信息
var illust = &Illust{}
if err := illust.IllustInfo(id); err != nil {
return "", err
return nil, err
}
if illust.AgeLimit != "all-age" {
return "", errors.New("Ascii2d not found")
return nil, fmt.Errorf("Ascii2d not found")
}
// 返回插图信息文本
return fmt.Sprintf(
`[SetuTime] emmm大概是这个
标题%s
插画ID%d
画师%s
画师ID%d
直链https://pixivel.moe/detail?id=%d`,
illust.Title,
illust.Pid,
illust.UserName,
illust.UserId,
illust.Pid,
), nil
return message.Message{
message.Text(
"[SetuTime] emmm大概是这个", "\n",
"标题:", illust.Title, "\n",
"插画ID", illust.Pid, "\n",
"画师:", illust.UserName, "\n",
"画师ID", illust.UserId, "\n",
"直链:", "https://pixivel.moe/detail?id=", illust.Pid,
),
}, nil
}

View File

@ -50,9 +50,8 @@ func (this *Illust) PixivPicDown(path string) (savePath string, err error) {
if err != nil {
return "", err
}
fmt.Println(resp.StatusCode)
if code := resp.StatusCode; code != 200 {
return "", errors.New(fmt.Sprintf("Download failed, code %d", code))
if resp.StatusCode != 200 {
return "", errors.New(fmt.Sprintf("Download failed, code %d", resp.StatusCode))
}
defer resp.Body.Close()
// 写入文件