package main import ( "fmt" "log" "github.com/PuerkitoBio/goquery" "github.com/go-redis/redis" "net/http" "bytes" "github.com/astaxie/beego/toolbox" ) var ( redisClient *redis.Client //redis 緩存 //釘釘羣機器人webhook地址 dingdingURL = "https://oapi.dingtalk.com/robot/send?access_token=dingding_talk_group_bot_webhook_token" //百度新聞搜索關鍵字URL baiduNewsUrlWithSearchKeyword = "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 key newsPost = "news_post"//已發送的百度新聞redis key newsList = "iot_news" //儲存了的百度新聞redis key ) //實例化redis緩存 func init() { redisClient = redis.NewClient(&redis.Options{ Addr: "127.0.0.1:6379", Password: "ddfrfgtre4353252", // redis password DB: 0, // redis 數據庫ID }) }
在機器人管理頁面選擇「自定義」機器人,輸入機器人名字並選擇要發送消息的羣。若是須要的話,能夠爲機器人設置一個頭像。點擊「完成添加」。
html
點擊「複製」按鈕,便可得到這個機器人對應的Webhook地址,賦值給 dingdingURl
git
func newsBot
func newsBot() error { // 獲取html doc doc, err := goquery.NewDocument(baiduNewsUrlWithSearchKeyword) if err != nil { return nil } //使用redis pipeline 減小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 title URL, _ := 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 pipeline pipe.Exec()
//使用redis sdiff找出沒有發送的新聞url unSendNewsUrls := 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()
//若是有未發送新聞 請求釘釘webhook if content != "" { formt := ` { "msgtype": "markdown", "markdown": { "title":"IOT每日新聞", "text": "%s" } }` body := fmt.Sprintf(formt, content) jsonValue := []byte(body) //發送消息到釘釘羣使用webhook //釘釘文檔 https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.karFPe&treeId=257&articleId=105735&docType=1 resp, err := http.Post(dingdingURL, "application/json", bytes.NewBuffer(jsonValue)) if (err != nil) { return err } log.Println(resp) } return nil }
func newsBot
函數完成github
func main() { //銷燬redisClient defer redisClient.Close() //建立定時任務 //天天 8點 13點 18點 自動執行爬蟲和機器人 // dingdingNewsBot := toolbox.NewTask("dingding-news-bot", "0 0 8,13,18 * * *", newsBot) //dingdingNewsBot := toolbox.NewTask("dingding-news-bot", "0 40 */1 * * *", newsBot) //err := dingdingNewsBot.Run() //檢測定時任務 // if err != nil { // log.Fatal(err) // } //添加定時任務 toolbox.AddTask("dingding-news-bot", dingdingNewsBot) //啓動定時任務 toolbox.StartTask() defer toolbox.StopTask() select {} }
spec 格式是參照
go build main.go nohup ./main &
最終效果
golang