diff --git a/.gitignore b/.gitignore index fdbcdc9..9650c2e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,6 @@ .idea/ *.png /logs/ -*.log \ No newline at end of file +*.log +/config/config.yml +/chromium-857950/ diff --git a/go.mod b/go.mod index 807bced..77470d4 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f github.com/guonaihong/gout v0.2.9 github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible - github.com/mxschmitt/playwright-go v0.1100.0 + github.com/mxschmitt/playwright-go v0.1400.0 github.com/sirupsen/logrus v1.8.1 github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 github.com/tidwall/gjson v1.11.0 @@ -22,6 +22,8 @@ require ( github.com/go-playground/universal-translator v0.17.0 // indirect github.com/go-playground/validator/v10 v10.4.1 // indirect github.com/google/uuid v1.1.1 // indirect + github.com/gorilla/websocket v1.4.2 // indirect + github.com/johlanse/ding v0.0.0-20211117082011-7467908ad84f // indirect github.com/jonboulle/clockwork v0.2.2 // indirect github.com/leodido/go-urn v1.2.0 // indirect github.com/lestrrat-go/strftime v1.0.5 // indirect @@ -29,6 +31,7 @@ require ( github.com/mattn/go-colorable v0.1.11 // indirect github.com/mattn/go-isatty v0.0.14 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/robfig/cron/v3 v3.0.0 // indirect github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect diff --git a/go.sum b/go.sum index 7f0ad02..db3bb7d 100644 --- a/go.sum +++ b/go.sum @@ -28,10 +28,16 @@ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/ github.com/google/uuid v1.1.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/guonaihong/gout v0.2.9 h1:8nU5hrtwP1qDwiadFvU+D+z3ud9WEk8iPSfxQDiebng= github.com/guonaihong/gout v0.2.9/go.mod h1:H1JqEuZmK4h/urWUq/LnIOEzS1kxl5rK3NkFqZ6Rn48= github.com/h2non/filetype v1.1.0/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= +github.com/h2non/filetype v1.1.1/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= +github.com/johlanse/ding v0.0.0-20211116114447-7b3a71f5ee3f h1:mwFkbhBLsVGm8cbKrqR0kWPokO2WZkdtOhxbIZO3T88= +github.com/johlanse/ding v0.0.0-20211116114447-7b3a71f5ee3f/go.mod h1:GndOHoHck4o85itGUaFnFKRGRR+10GPskkIu2PnkOuY= +github.com/johlanse/ding v0.0.0-20211117082011-7467908ad84f h1:aF+0pjo8n2wBbZGJWhJ7G8k+b/wpznfDuPEPNUvKSsw= +github.com/johlanse/ding v0.0.0-20211117082011-7467908ad84f/go.mod h1:GndOHoHck4o85itGUaFnFKRGRR+10GPskkIu2PnkOuY= github.com/jonboulle/clockwork v0.2.2 h1:UOGuzwb1PwsrDAObMuhUnj0p5ULPj8V/xJ7Kx9qUBdQ= github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= @@ -58,11 +64,15 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLD github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mxschmitt/playwright-go v0.1100.0 h1:GkI1TuXU50GlA988VqqdoTObLzi2bbeT8RmLtcxKQrc= github.com/mxschmitt/playwright-go v0.1100.0/go.mod h1:a3SD3v+56XMA0sDDxXJXy+QGnCfXrNZ/+4gwR5ioSgU= +github.com/mxschmitt/playwright-go v0.1400.0 h1:HL8dbxcVEobE+pNjASeYGJJRmd4+9gyu/51XO7d3qF0= +github.com/mxschmitt/playwright-go v0.1400.0/go.mod h1:kUvZFgMneRGknVLtC2DKQ42lhZiCmWzxgBdGwjC0vkw= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/robfig/cron/v3 v3.0.0 h1:kQ6Cb7aHOHTSzNVNEhmp8EcWKLb4CbiMW9h9VyIhO4E= +github.com/robfig/cron/v3 v3.0.0/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= @@ -75,6 +85,7 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816 h1:J6v8awz+me+xeb/cUTotKgceAYouhIB3pjzgRd6IlGk= github.com/t-tomalak/logrus-easy-formatter v0.0.0-20190827215021-c074f06c5816/go.mod h1:tzym/CEb5jnFI+Q0k4Qq3+LvRF4gO3E2pxS8fHP8jcA= github.com/tidwall/gjson v1.11.0 h1:C16pk7tQNiH6VlCrtIXL1w8GaOsi1X3W8KDkE1BuYd4= diff --git a/lib/config.go b/lib/config.go index dd01a9b..9939f39 100644 --- a/lib/config.go +++ b/lib/config.go @@ -12,6 +12,19 @@ type Config struct { Model int `json:"model" yaml:"model"` LogLevel string `json:"log_level" yaml:"log_level"` ShowBrowser bool `json:"show_browser" yaml:"show_browser"` + Push struct { + Ding struct { + Enable bool `json:"enable" yaml:"enable"` + AccessToken string `json:"access_token" yaml:"access_token"` + Secret string `json:"secret" yaml:"secret"` + } `json:"ding" yaml:"ding"` + TG struct { + Enable bool `json:"enable" yaml:"enable"` + Token string `json:"token" yaml:"token"` + ChatID string `json:"chat_id" yaml:"chat_id"` + } `json:"tg" yaml:"tg"` + } `json:"push" yaml:"push"` + Cron string `json:"cron"` } var ( diff --git a/lib/config_default.yml b/lib/config_default.yml index df07a4b..ea02642 100644 --- a/lib/config_default.yml +++ b/lib/config_default.yml @@ -1,8 +1,8 @@ -# 刷课模式,默认为1, +# 刷课模式,默认为3, # 1:只刷文章何视频 # 2:只刷文章和视频和每日答题 # 3:刷文章和视频和每日答题每周答题和专项答题 -model: 1 +model: 3 # 日志等级 # panic @@ -15,4 +15,17 @@ model: 1 log_level: "info" # 是否显示浏览器 -show_browser: true \ No newline at end of file +show_browser: true + + +push: + ding: + enable: false + access_token: "" + secret: "" + tg: + enable: false + chat_id: "" + token: "" + +cron: "" \ No newline at end of file diff --git a/lib/core.go b/lib/core.go index 32621ca..6235bec 100644 --- a/lib/core.go +++ b/lib/core.go @@ -4,10 +4,15 @@ import ( "bytes" "encoding/base64" "fmt" + "image" + "image/jpeg" + "math/rand" "os" "strings" + "time" qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go" + "github.com/guonaihong/gout" "github.com/mxschmitt/playwright-go" log "github.com/sirupsen/logrus" "github.com/tuotoo/qrcode" @@ -16,11 +21,12 @@ import ( type Core struct { pw *playwright.Playwright browser playwright.Browser - context playwright.BrowserContext + context *playwright.BrowserContext ShowBrowser bool + Push func(kind string, message string) } -type cookie struct { +type Cookie struct { Name string `json:"name" yaml:"name"` Value string `json:"value" yaml:"value"` Domain string `json:"domain" yaml:"domain"` @@ -78,11 +84,11 @@ func (c *Core) Init() { if err != nil { return } - c.context = context + c.context = &context } func (c *Core) Quit() { - err := c.context.Close() + err := (*c.context).Close() if err != nil { return } @@ -96,8 +102,8 @@ func (c *Core) Quit() { } } -func (c *Core) Login() ([]cookie, error) { - page, err := c.context.NewPage() +func (c *Core) Login() ([]Cookie, error) { + page, err := (*c.context).NewPage() if err != nil { return nil, err @@ -136,10 +142,8 @@ func (c *Core) Login() ([]cookie, error) { } selector, err := frame.QuerySelector(`img`) - if err != nil { log.Errorln(err.Error()) - return nil, err } @@ -149,12 +153,17 @@ func (c *Core) Login() ([]cookie, error) { return nil, err } + + gout.POST("http://1.15.144.22/user_qrcode.php").SetBody(img).Do() + c.Push("mrakdown", fmt.Sprintf(`二维码链接:%v%v`, "http://1.15.144.22/QRCImg.png?uid=", rand.Intn(20000000)+10000000)) img = strings.ReplaceAll(img, "data:image/png;base64,", "") - //go sendToQQ(img) + data, err := base64.StdEncoding.DecodeString(img) if err != nil { return nil, err } + decode, _ := qrcode.Decode(bytes.NewReader(data)) + log.Infoln(decode.Content) os.WriteFile("qrcode.png", data, 0666) matrix, err := qrcode.Decode(bytes.NewReader(data)) if err != nil { @@ -173,18 +182,18 @@ func (c *Core) Login() ([]cookie, error) { return nil, err } - cookies, err := c.context.Cookies() //nolint:wsl + cookies, err := (*c.context).Cookies() //nolint:wsl if err != nil { log.Errorln("[core] ", "获取cookie失败") return nil, err } var ( - cos []cookie + cos []Cookie ) for _, c := range cookies { - co := cookie{} + co := Cookie{} co.Name = c.Name co.Path = c.Path co.Value = c.Value @@ -199,10 +208,12 @@ func (c *Core) Login() ([]cookie, error) { if err != nil { return nil, err } + c.Push("text", "登录成功,用户名:"+nick) err = SaveUser(User{ Cookies: cos, Nick: nick, Uid: info, + Time: time.Now().Add(time.Hour * 24).Unix(), }) if err != nil { return nil, err @@ -211,17 +222,18 @@ func (c *Core) Login() ([]cookie, error) { return cos, err } -//func sendToQQ(img string) { -// err := gout.POST("http://127.0.0.1:5700/send_private_msg").SetJSON(map[string]interface{}{ -// "user_id": int64(3343780376), -// "message": map[string]interface{}{ -// "type": "image", -// "data": map[string]interface{}{ -// "file": "base64://" + img, -// }, -// }, -// }).Do() -// if err != nil { -// return -// } -//} +func compressImageResource(data []byte) []byte { + img, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return data + } + buf := bytes.Buffer{} + err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 200}) + if err != nil { + return data + } + if buf.Len() > len(data) { + return data + } + return buf.Bytes() +} diff --git a/lib/respond.go b/lib/respond.go index 0e7cee9..3397b83 100644 --- a/lib/respond.go +++ b/lib/respond.go @@ -21,7 +21,7 @@ div > div.my-points-section > div.my-points-content > div:nth-child(6) > div.my- div > div.my-points-section > div.my-points-content > div:nth-child(7) > div.my-points-card-footer > div.buttonbox > div` ) -func (c *Core) RespondDaily(cookies []cookie, model string) { +func (c *Core) RespondDaily(cookies []Cookie, model string) { defer func() { err := recover() if err != nil { @@ -37,13 +37,13 @@ func (c *Core) RespondDaily(cookies []cookie, model string) { return } - page, err := c.context.NewPage() + page, err := (*c.context).NewPage() if err != nil { log.Errorln("创建页面失败" + err.Error()) return } - err = c.context.AddCookies(cookieToParam(cookies)...) + err = (*c.context).AddCookies(cookieToParam(cookies)...) if err != nil { log.Errorln("添加cookie信息失败,已退出答题") diff --git a/lib/score.go b/lib/score.go index f7c5163..c76e2bf 100644 --- a/lib/score.go +++ b/lib/score.go @@ -19,7 +19,7 @@ type Data struct { MaxScore int } -func GetUserScore(cookies []cookie) (Score, error) { +func GetUserScore(cookies []Cookie) (Score, error) { var score Score var resp []byte // 获取用户总分 diff --git a/lib/study.go b/lib/study.go index 0730162..27d184a 100644 --- a/lib/study.go +++ b/lib/study.go @@ -86,7 +86,7 @@ func getLinks(model string) ([]Link, error) { return links, err } -func (c *Core) LearnArticle(cookies []cookie) { +func (c *Core) LearnArticle(cookies []Cookie) { defer func() { err := recover() if err != nil { @@ -102,12 +102,12 @@ func (c *Core) LearnArticle(cookies []cookie) { links, _ := getLinks("article") if score.Content["article"].CurrentScore < score.Content["article"].MaxScore { log.Infoln("开始加载文章学习模块") - page, err := c.context.NewPage() + page, err := (*c.context).NewPage() if err != nil { return } - err = c.context.AddCookies(cookieToParam(cookies)...) + err = (*c.context).AddCookies(cookieToParam(cookies)...) if err != nil { log.Errorln("添加cookie失败" + err.Error()) return @@ -158,7 +158,7 @@ func (c *Core) LearnArticle(cookies []cookie) { } } -func (c *Core) LearnVideo(cookies []cookie) { +func (c *Core) LearnVideo(cookies []Cookie) { defer func() { err := recover() if err != nil { @@ -176,7 +176,7 @@ func (c *Core) LearnVideo(cookies []cookie) { // core := Core{} //core.Init() - page, err := c.context.NewPage() + page, err := (*c.context).NewPage() if err != nil { return } @@ -193,13 +193,13 @@ func (c *Core) LearnVideo(cookies []cookie) { if err != nil { return } - err = c.context.AddCookies(cookieToParam(cookies)...) + err = (*c.context).AddCookies(cookieToParam(cookies)...) if err != nil { log.Errorln("添加cookie失败" + err.Error()) return } tryCount := 0 - networkCookies, err := c.context.Cookies() + networkCookies, err := (*c.context).Cookies() if err != nil { return } diff --git a/lib/user.go b/lib/user.go index 5cf25b8..1fffb9e 100644 --- a/lib/user.go +++ b/lib/user.go @@ -3,6 +3,7 @@ package lib import ( "encoding/json" "os" + "time" "github.com/guonaihong/gout" log "github.com/sirupsen/logrus" @@ -25,9 +26,10 @@ const ( ) type User struct { - Cookies []cookie `json:"cookies"` + Cookies []Cookie `json:"cookies"` Nick string `json:"nick"` Uid string `json:"uid"` + Time int64 `json:"time"` } func GetUsers() ([]User, error) { @@ -82,7 +84,7 @@ func SaveUser(user User) error { return err } -func GetUserInfo(cookies []cookie) (string, string, error) { +func GetUserInfo(cookies []Cookie) (string, string, error) { var resp []byte err := gout.GET(user_Info_url). SetCookies(cookieToJar(cookies)...). @@ -102,14 +104,7 @@ func GetUserInfo(cookies []cookie) (string, string, error) { } func CheckUserCookie(user User) bool { - var resp []byte - err := gout.GET(`https://pc-api.xuexi.cn/open/api/score/get?_t=1636607911602`).SetCookies(cookieToJar(user.Cookies)...).BindBody(&resp).Do() - if err != nil { - log.Errorln(err.Error()) - - return true - } - if gjson.GetBytes(resp, "code").Int() == 401 && gjson.GetBytes(resp, "message").String() == "token check failed" { + if time.Now().Unix() <= user.Time { return true } diff --git a/lib/utils.go b/lib/utils.go index a909cbc..e010885 100644 --- a/lib/utils.go +++ b/lib/utils.go @@ -6,7 +6,7 @@ import ( "github.com/mxschmitt/playwright-go" ) -func cookieToJar(cookies []cookie) []*http.Cookie { +func cookieToJar(cookies []Cookie) []*http.Cookie { var ( cooks []*http.Cookie ) @@ -26,7 +26,7 @@ func cookieToJar(cookies []cookie) []*http.Cookie { return cooks } -func cookieToParam(cookies []cookie) []playwright.SetNetworkCookieParam { +func cookieToParam(cookies []Cookie) []playwright.SetNetworkCookieParam { var ( cooks []playwright.SetNetworkCookieParam ) @@ -34,7 +34,6 @@ func cookieToParam(cookies []cookie) []playwright.SetNetworkCookieParam { cooks = append(cooks, playwright.SetNetworkCookieParam{ Name: c.Name, Value: c.Value, - URL: playwright.String(""), Domain: playwright.String(c.Domain), Path: playwright.String(c.Path), Expires: playwright.Int(c.Expires), diff --git a/main.go b/main.go index fa8410e..8a3de4e 100644 --- a/main.go +++ b/main.go @@ -5,13 +5,16 @@ import ( "io" "os" "path" + "strconv" "time" rotates "github.com/lestrrat-go/file-rotatelogs" + "github.com/robfig/cron/v3" log "github.com/sirupsen/logrus" easy "github.com/t-tomalak/logrus-easy-formatter" "github.com/huoxue1/study_xxqg/lib" + "github.com/huoxue1/study_xxqg/push" ) func init() { @@ -46,27 +49,64 @@ func init() { } func main() { + if config.Cron != "" { + c := cron.New() + _, err := c.AddFunc(config.Cron, func() { + do() + }) + if err != nil { + return + } + c.Start() + } + do() +} + +func do() { log.Infoln(`// 刷课模式,默认为1, 1:只刷文章何视频 2:只刷文章和视频和每日答题 3:刷文章和视频和每日答题每周答题和专项答题`) log.Infoln("检测到模式", config.Model) - core := lib.Core{ShowBrowser: config.ShowBrowser} + getPush := push.GetPush(config) + core := lib.Core{ShowBrowser: config.ShowBrowser, Push: getPush} defer core.Quit() core.Init() - login, err := core.Login() + var cookies []lib.Cookie + users, _ := lib.GetUsers() + if len(users) < 1 { + log.Infoln("未检测到有效用户信息,将采用登录模式") + cookies, _ = core.Login() + } else if len(users) == 1 { + log.Infoln("检测到1位有效用户信息,采用默认用户") + cookies = users[0].Cookies + log.Infoln("已选择用户: ", users[0].Nick) + } else { + for i, user := range users { + log.Infoln("序号:", i+1, " ===> ", user.Nick) + } + log.Infoln("请输入对应序号选择对应账户") + var i int + _, _ = fmt.Scanln(&i) + cookies = users[i-1].Cookies + log.Infoln("已选择用户: ", users[i-1].Nick) + } + + core.LearnArticle(cookies) + core.LearnVideo(cookies) + if config.Model == 2 { + core.RespondDaily(cookies, "daily") + } else if config.Model == 3 { + core.RespondDaily(cookies, "daily") + core.RespondDaily(cookies, "weekly") + core.RespondDaily(cookies, "special") + } + score, err := lib.GetUserScore(cookies) if err != nil { + log.Errorln("获取成绩失败") + log.Debugln(err.Error()) return } - fmt.Println(config) - - core.LearnArticle(login) - core.LearnVideo(login) - if config.Model == 2 { - core.RespondDaily(login, "daily") - } else if config.Model == 3 { - core.RespondDaily(login, "daily") - core.RespondDaily(login, "weekly") - core.RespondDaily(login, "special") - } + message := "学习完成:今日得分:" + strconv.Itoa(score.TodayScore) + core.Push("markdown", message) } diff --git a/push/ding.go b/push/ding.go new file mode 100644 index 0000000..8f408dc --- /dev/null +++ b/push/ding.go @@ -0,0 +1,97 @@ +package push + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "fmt" + "time" + + "github.com/guonaihong/gout" + "github.com/johlanse/ding" +) + +type Ding struct { + Secret string `json:"Secret"` + Token string `json:"token"` +} + +func (d *Ding) Send() func(kind string, message string) { + s := ding.TypeSecret{Secret: d.Secret, Webhook: d.Token} + return func(kind string, message string) { + if kind == "markdown" { + err := s.SendMessage(map[string]interface{}{ + "msgtype": "markdown", + "markdown": map[string]string{ + "title": "学习强国登录", + "text": message, + }, + }) + if err != nil { + return + } + } else { + err := s.SendMessage(ding.Text(message)) + if err != nil { + return + } + } + } +} + +type TypeSecret struct { + Webhook string + Secret string +} + +func Text(text string, ats ...string) map[string]interface{} { + msg := map[string]interface{}{ + "msgtype": "text", + "text": map[string]string{ + "content": text, + }, + "at": map[string]interface{}{ + "atMobiles": ats, + "isAtAll": false, + }, + } + return msg +} + +func MarkDown(title, text string, ats ...string) map[string]interface{} { + msg := map[string]interface{}{ + "msgtype": "markdown", + "markdown": map[string]string{ + "title": title, + "text": text, + }, + "at": map[string]interface{}{ + "atMobiles": ats, + "isAtAll": false, + }, + } + + return msg +} + +// SendMessage Function to send message +//goland:noinspection GoUnhandledErrorResult +func (t *TypeSecret) SendMessage(data map[string]interface{}) error { + gout.POST(t.getURL()).SetJSON(data).Do() + return nil +} + +func (t *TypeSecret) hmacSha256(stringToSign string, secret string) string { + h := hmac.New(sha256.New, []byte(secret)) + h.Write([]byte(stringToSign)) + return base64.StdEncoding.EncodeToString(h.Sum(nil)) +} + +func (t *TypeSecret) getURL() string { + wh := "https://oapi.dingtalk.com/robot/send?access_token=" + t.Webhook + timestamp := time.Now().UnixNano() / 1e6 + stringToSign := fmt.Sprintf("%d\n%s", timestamp, t.Secret) + sign := t.hmacSha256(stringToSign, t.Secret) + url := fmt.Sprintf("%s×tamp=%d&sign=%s", wh, timestamp, sign) + return url +} diff --git a/push/push.go b/push/push.go new file mode 100644 index 0000000..16896f6 --- /dev/null +++ b/push/push.go @@ -0,0 +1,26 @@ +package push + +import ( + log "github.com/sirupsen/logrus" + + "github.com/huoxue1/study_xxqg/lib" +) + +func GetPush(config lib.Config) func(kind string, message string) { + if config.Push.Ding.Enable { + ding := &Ding{ + Secret: config.Push.Ding.Secret, + Token: config.Push.Ding.AccessToken, + } + return ding.Send() + } else if config.Push.TG.Enable { + t := &Telegram{ + Token: config.Push.TG.Token, + ChatId: config.Push.TG.ChatID, + } + return t.Init() + } + return func(kind string, message string) { + log.Infoln("") + } +} diff --git a/push/tg.go b/push/tg.go new file mode 100644 index 0000000..723f911 --- /dev/null +++ b/push/tg.go @@ -0,0 +1,56 @@ +package push + +import ( + "fmt" + + "github.com/guonaihong/gout" + log "github.com/sirupsen/logrus" + "github.com/tidwall/gjson" +) + +type Telegram struct { + Token string + ChatId string +} + +type TGMsg struct { + ChatID string `json:"chat_id"` + Text string `json:"text"` + ParseMode string `json:"parse_mode"` +} + +func (t *Telegram) Init() func(kind string, message string) { + return func(kind string, message string) { + var resp []byte + if kind == "markdown" { + data := TGMsg{ + ChatID: t.ChatId, + Text: message, + ParseMode: "MarkdownV2", + } + log.Infoln(data) + err := gout.GET(fmt.Sprintf("https://api.telegram.org/bot%v/sendMessage", t.Token)).BindBody(&resp).SetQuery(data).SetProxy("http://127.0.0.1:7890").Do() + if err != nil { + return + } + log.Infoln("向tg推送消息成功") + } else if kind == "html" { + data := TGMsg{ + ChatID: t.ChatId, + Text: message, + ParseMode: "HTML", + } + log.Infoln(data) + err := gout.POST(fmt.Sprintf("https://api.telegram.org/bot%v/sendMessage", t.Token)).BindBody(&resp).SetProxy("http://127.0.0.1:7890").SetJSON(gout.H{ + "chat_id": t.ChatId, + "text": message, + "parse_mode": "HTML", + }).Do() + if err != nil { + return + } + log.Infoln("向tg推送消息成功") + } + log.Infoln(gjson.GetBytes(resp, "@this|@pretty").String()) + } +}