golang向微信应用发送消息

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/tidwall/gjson"
)

var (
	CORPID    = "xxxxxxxxx"
	APPSECRET = "xxxxxxxxxxxxxxxxxxxxxxxxx"
	AGENTID   = "xxxxxxx"
)

type token struct {
     
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type sentence struct {
     
	Content     string `json:"content"`
	Note        string `json:"note"`
	Translation string `json:"translation"`
}

func main() {
     
	msgHandler(getaccesstoken())
	// spec := "*/1 * * * * *"
	// c := cron.New()
	// c.AddFunc(spec, msgHandler)
	// c.Start()
	// fmt.Println("开启定时任务")
	// select {}
}

//获取微信accesstoken
func getaccesstoken() string {
     
	url := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%v&corpsecret=%v", CORPID, APPSECRET)
	resp, err := http.Get(url)
	if err != nil {
     
		fmt.Println("获取微信token失败", err)
		return ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
     
		fmt.Println("微信token读取失败", err)
		return ""
	}

	token := token{
     }
	err = json.Unmarshal(body, &token)
	if err != nil {
     
		fmt.Println("微信token解析json失败", err)
		return ""
	}

	return token.AccessToken
}

func msgHandler(access_token string) {
     
	note_json, _ := getsen()
	note := note_json.Note
	fmt.Println(note)
	msgsend_url := "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
	msg := fmt.Sprintf(`{"touser":"@all","toparty":1,"msgtype":"text","agentid":%v,"text":{"content":"%v"},"safe": 0}`, AGENTID, note)
	resp, err := http.Post(msgsend_url, "application/x-www-form-urlencoded", strings.NewReader(msg))
	if err != nil {
     
		fmt.Println(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
     
		fmt.Println("读取内容失败", err)
	}
	errcode := gjson.Get(string(body), "errcode").Num
	if errcode == 0 {
     
		fmt.Println("消息发送成功")
	}
}

//获取每日一句
func getsen() (sentence, string) {
     
	resp, err := http.Get("http://open.iciba.com/dsapi/?date")
	sent := sentence{
     }
	if err != nil {
     
		fmt.Println("获取每日一句失败", err)
		return sent, ""
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
     
		fmt.Println("读取内容失败", err)
		return sent, ""
	}

	err = json.Unmarshal(body, &sent)
	if err != nil {
     
		fmt.Println("每日一句解析json失败")
		return sent, ""
	}
	fenxiangurl := gjson.Get(string(body), "fenxiang_img").String()
	return sent, fenxiangurl
}

参考:
https://blog.csdn.net/u012140251/article/details/89529540

你可能感兴趣的:(编程人生)