golang80行代碼DingTalk群機器人訂閱百度新聞
來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。## 1. 資料##### 1.1.第三方包* [github.com/PuerkitoBio/goquery](https://godoc.org/github.com/PuerkitoBio/goquery)* [github.com/go-redis/redis](https://godoc.org/github.com/PuerkitoBio/goquery)* [beego架構定時任務包](https://beego.me/docs/module/toolbox.md#task)##### 1.2 介面* [百度新聞:美劇關鍵字](http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=%E7%BE%8E%E5%89%A7)* [DingTalk群BOT文檔](https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.t8inXi&treeId=257&articleId=105735&docType=1#s6)## 2. 初始化項目變數```package mainimport ("fmt""log""github.com/PuerkitoBio/goquery""github.com/go-redis/redis""net/http""bytes""github.com/astaxie/beego/toolbox")var (redisClient *redis.Client //redis 緩衝 //DingTalk群機器人webhook地址dingdingURL = "https://oapi.dingtalk.com/robot/send?access_token=dingding_talk_group_bot_webhook_token" //百度新聞搜尋索引鍵URLbaiduNewsUrlWithSearchKeyword = "http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=%E7%89%A9%E8%81%94%E7%BD%91")const (newsFeed = "news_feed"//爬取到的百度新聞redis keynewsPost = "news_post"//已發送的百度新聞redis keynewsList = "iot_news" //儲存了的百度新聞redis key)//執行個體化redis緩衝func init() {redisClient = redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379",Password: "ddfrfgtre4353252", // redis passwordDB: 0, // redis 資料庫ID})}```在機器人管理頁面選擇“自訂”機器人,輸入機器人名字並選擇要發送訊息的群。如果需要的話,可以為機器人設定一個頭像。點擊“完成添加”。點擊“複製”按鈕,即可獲得這個機器人對應的Webhook地址,賦值給 `dingdingURl`## 3 `func newBot`##### 3.1 使用goquery和網頁元素選取器文法提取有用資訊```func newsBot() error {// 擷取html docdoc, err := goquery.NewDocument(baiduNewsUrlWithSearchKeyword)if err != nil {return nil} //使用redis pipelien 減少redis串連數pipe := redisClient.Pipeline()// 使用selector xpath 文法擷取有用資訊 // 儲存新聞到redis中 newsList // 儲存新聞ur到redis-set 建newfeed 為以後是用sdiff 找出沒有發送的新聞doc.Find("div.result").Each(func(i int, s *goquery.Selection) {// For each item found, get the band and titleURL, _ := s.Find("h3 > a").Attr("href")Source := s.Find("p.c-author").Text()Title := s.Find("h3 > a").Text()markdown := fmt.Sprintf("- [%s](%s) _%s_", Title, URL, Source)pipe.HSet(newsList, URL, markdown)pipe.SAdd(newsFeed, URL)}) //執行redis pipelinepipe.Exec()```##### 3.2 排除以發送的新聞,拼接markdown字串``` //使用redis sdiff找出沒有發送的新聞urlunSendNewsUrls := redisClient.SDiff(newsFeed, newsPost).Val() //新聞按dingding文檔markdonw 規範拼接 content := ""for _, url := range unSendNewsUrls {md := redisClient.HGet(newsList, url).Val()content = content + " \n " + md //記錄已發送新聞的url地址pipe.SAdd(newsPost, url)}pipe.Exec()```##### 3.3 調用DingTalk群機器人介面``` //如果有未發送新聞 請求DingTalkwebhookif content != "" {formt := `{"msgtype": "markdown","markdown": {"title":"IOT每日新聞","text": "%s"}}`body := fmt.Sprintf(formt, content)jsonValue := []byte(body) //發送訊息到DingTalk群使用webhook //xiang見DingTalk文檔 https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.karFPe&treeId=257&articleId=105735&docType=1resp, err := http.Post(dingdingURL, "application/json", bytes.NewBuffer(jsonValue))if (err != nil) {return err}log.Println(resp)}return nil}````func newBot`函數完成## 4. 設定定時任務```func main() { //銷毀redisClientdefer redisClient.Close()//建立定時任務 //每天 8點 13點 18點 自動執行爬蟲和機器人 // dingdingNewBot := toolbox.NewTask("dingding-news-bot", "0 0 8,13,18 * * *", newsBot)//dingdingNewBot := toolbox.NewTask("dingding-news-bot", "0 40 */1 * * *", newsBot)//err := dingdingNewBot.Run()//檢測定時任務// if err != nil {// log.Fatal(err)// }//添加定時任務toolbox.AddTask("dingding-news-bot", dingdingNewBot)//啟動定時任務toolbox.StartTask()defer toolbox.StopTask()select {}}```> [spec 格式是參照](https://beego.me/docs/module/toolbox.md#task)## 5 編譯運行[最終完整代碼`main.go`](https://gist.github.com/mojocn/43b47e8d97abb1e00fd19b2864f053c1)```bashgo build main.gonohup ./main &```最終效果## 6 最後* 歡迎star我的[golang-base64captcha開源項目](https://github.com/mojocn/base64Captcha)* 如有疑問歡迎email:dejavuzhou@qq.com * 或者 comment [github gist](https://gist.github.com/mojocn/43b47e8d97abb1e00fd19b2864f053c1)483 次點擊 ∙ 1 贊