给女朋友的浪漫微信消息推送,怎么能少Golang版本
本帖最后由 ITMN 于 2022-8-27 14:29 编辑好像最近挺火的,看到有各种语言,那我就来个golang版本,粗制滥造简单的完成
配合腾讯云函数定时发送,完美!
前期工作:
1、申请公众号
2、申请天行彩虹屁接口,https://www.tianapi.com/console/ 记录下key
3、申请天气接口,https://tianqiapi.com/index/doc 记录下appid和appsecret
初始化项目
go mod init love
新建一个main.go文件和core文件夹
core文件夹新增api.go、wechat.go、types.go三个文件
main.go
func main() {
config := viper.New()
config.AddConfigPath("./")
config.SetConfigName("config")
config.SetConfigType("json")
if err := config.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Println("找不到配置文件..")
} else {
fmt.Println("配置文件出错..")
}
}
wx := core.NewWeChat(config)
wx.Send()
fmt.Println("ok")
}
api.go
type Api struct {
Config *viper.Viper
}
func NewApi(config *viper.Viper) Api {
return Api{
config,
}
}
func (t Api) GetCaiHongPi() (string, error) {
var (
err error
url string
rspBody []byte
)
key := t.Config.GetString("TianXingKey")
url = fmt.Sprintf("http://api.tianapi.com/caihongpi/index?key=%s", key)
rspBody, err = t.Curl(url)
var result CaiHongPi
if err = json.Unmarshal(rspBody, &result); err != nil {
return "", err
}
if len(result.NewsList) > 0 {
return result.NewsList.Content, nil
}
return "", nil
}
func (t Api) TianQi() (result TianQi, err error) {
var rspBody []byte
appId := t.Config.GetString("tqAppId")
appSecret := t.Config.GetString("tqAppSecret")
city := t.Config.GetString("city")
url := fmt.Sprintf("https://v0.yiketianqi.com/api?unescape=1&version=v61&appid=%s&appsecret=%s&city=%s", appId, appSecret, city)
rspBody, err = t.Curl(url)
if err = json.Unmarshal(rspBody, &result); err != nil {
return
}
return
}
func (t Api) Curl(url string) (rspBody []byte, err error) {
var (
httpReq *http.Request
httpRsp *http.Response
)
httpReq, err = http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
httpRsp, err = http.DefaultClient.Do(httpReq)
if err != nil {
return nil, err
}
defer httpRsp.Body.Close()
rspBody, err = ioutil.ReadAll(httpRsp.Body)
if err != nil {
return nil, err
}
return rspBody, nil
}
微信代码块
type Wechat struct {
Config *viper.Viper
}
func NewWeChat(config *viper.Viper) Wechat {
return Wechat{
config,
}
}
func (w Wechat) Send() {
var err error
wc := wechat.NewWechat()
memory := cache.NewMemory()
cfg := &offConfig.Config{
AppID: w.Config.GetString("appId"),
AppSecret: w.Config.GetString("appSecret"),
Cache: memory,
}
oa := wc.GetOfficialAccount(cfg)
bd := oa.GetTemplate()
var msgTpl *message.TemplateMessage
msgTpl, err = w.GetTpl()
_, err = bd.Send(msgTpl)
if err != nil {
fmt.Printf("Unmarshal fail, err:%v", err)
}
}
func (w Wechat) GetTpl() (msgTpl *message.TemplateMessage, err error) {
msgTpl = new(message.TemplateMessage)
msgTpl.ToUser = w.Config.GetString("toUser")
msgTpl.TemplateID = w.Config.GetString("templateID")
msgTpl.Data = make(map*message.TemplateDataItem)
api := NewApi(w.Config)
var tq TianQi
tq, err = api.TianQi()
loveDate := w.Config.GetString("loveDate")
birthday := w.Config.GetString("birthday")
loveDay := carbon.Parse(loveDate).DiffInDays(carbon.Now())
date := carbon.Now().Format("Y年m月d") + " " + carbon.Now().ToWeekString()
md := carbon.Parse(birthday).Format("-m-d")
var nextBirthday string
var year string
var birthdayMsg string
thisYearBirthday := fmt.Sprint(carbon.Now().Year()) + md
if carbon.Now().Gt(carbon.Parse(thisYearBirthday)) {
year = fmt.Sprint(carbon.Now().Year() + 1)
nextBirthday = carbon.Parse(birthday).Format(year + md)
birthdayMsg = "距离你的生日还有" + fmt.Sprint(carbon.Now().DiffInDays(carbon.Parse(nextBirthday))) + "天"
} else if carbon.Now().Eq(carbon.Parse(thisYearBirthday)) {
birthdayMsg = "今天是你的生日"
} else {
year = fmt.Sprint(carbon.Now().Year())
nextBirthday = carbon.Parse(birthday).Format(year + md)
birthdayMsg = "距离你的生日还有" + fmt.Sprint(carbon.Now().DiffInDays(carbon.Parse(nextBirthday))) + "天"
} //
msgTpl.Data["date"] = &message.TemplateDataItem{
Value: date,
Color: "#434343",
}
msgTpl.Data["region"] = &message.TemplateDataItem{
Value: tq.City,
Color: "#ff00ff",
}
msgTpl.Data["weather"] = &message.TemplateDataItem{
Value: tq.Wea,
Color: "#3c78d8",
}
msgTpl.Data["maxTemp"] = &message.TemplateDataItem{
Value: tq.Tem1,
Color: "#dd7e6b",
}
msgTpl.Data["minTemp"] = &message.TemplateDataItem{
Value: tq.Tem2,
Color: "#dd7e6b",
}
msgTpl.Data["wind_dir"] = &message.TemplateDataItem{
Value: tq.Win + tq.WinSpeed,
Color: "#9900ff",
}
msgTpl.Data["love_day"] = &message.TemplateDataItem{
Value: fmt.Sprint(loveDay),
Color: "#6fa8dc",
}
msgTpl.Data["birthday"] = &message.TemplateDataItem{
Value: birthdayMsg,
Color: "#ea9999",
}
var chp string
chp, err = api.GetCaiHongPi()
if err != nil {
fmt.Printf("Unmarshal fail, err:%v", err)
}
msgTpl.Data["note_ch"] = &message.TemplateDataItem{
Value: chp,
Color: "#FF0000",
}
return msgTpl, nil
}
types结构体
type CaiHongPi struct {
Code int `json:"code"`
Msg string `json:"msg"`
NewsList []NewsList `json:"newslist"`
}
type NewsList struct {
Content string `json:"content"`
}
type TianQi struct {
Cityid string `json:"cityid"`
Date string `json:"date"`
Week string `json:"week"`
UpdateTime string `json:"update_time"`
City string `json:"city"`
CityEn string `json:"cityEn"`
Country string `json:"country"`
CountryEn string `json:"countryEn"`
Wea string `json:"wea"`
WeaImg string `json:"wea_img"`
Tem string `json:"tem"`
Tem1 string `json:"tem1"`
Tem2 string `json:"tem2"`
Win string `json:"win"`
WinSpeed string `json:"win_speed"`
WinMeter string `json:"win_meter"`
Humidity string `json:"humidity"`
Visibility string `json:"visibility"`
Pressure string `json:"pressure"`
Air string `json:"air"`
AirPm25 string `json:"air_pm25"`
AirLevel string `json:"air_level"`
AirTips string `json:"air_tips"`
Alarm Alarm`json:"alarm"`
WinSpeedDay string `json:"win_speed_day"`
WinSpeedNight string `json:"win_speed_night"`
Aqi Aqi `json:"aqi"`
}
type Alarm struct {
AlarmType string `json:"alarm_type"`
AlarmLevel string `json:"alarm_level"`
AlarmContent string `json:"alarm_content"`
}
type Aqi struct {
UpdateTime string `json:"update_time"`
Cityid string `json:"cityid"`
City string `json:"city"`
CityEn string `json:"cityEn"`
Country string `json:"country"`
CountryEnstring `json:"countryEn"`
Air string `json:"air"`
AirLevel string `json:"air_level"`
AirTips string `json:"air_tips"`
Pm25 string `json:"pm25"`
Pm25Desc string `json:"pm25_desc"`
Pm10 string `json:"pm10"`
Pm10Desc string `json:"pm10_desc"`
O3 string `json:"o3"`
O3Desc string `json:"o3_desc"`
No2 string `json:"no2"`
No2Desc string `json:"no2_desc"`
So2 string `json:"so2"`
So2Desc string `json:"so2_desc"`
Co string `json:"co"`
CoDesc string `json:"co_desc"`
Kouzhao string `json:"kouzhao"`
Yundong string `json:"yundong"`
Waichu string `json:"waichu"`
Kaichuangstring `json:"kaichuang"`
Jinghuaqistring `json:"jinghuaqi"`
}
微信模板消息:
{{date.DATA}}
地区:{{region.DATA}}
天气:{{weather.DATA}}
最高温度:{{maxTemp.DATA}}
最低温度:{{minTemp.DATA}}
风向:{{wind_dir.DATA}}
今天是我们恋爱的第{{love_day.DATA}}天
{{birthday.DATA}}
{{note_ch.DATA}}
本地测试:
go mod vendor
go run main
编译打包:
GOOS=linux GOARCH=amd64 go build -o main main.go
最终代码在GitHub
https://github.com/neonyo/weather-push
下载,编译即可 效果图
云函数直接上传
羡慕呀 不会搭建 不会弄,能出个详细教程吗? 有视频最好 skoy03 发表于 2022-8-28 19:03
不会弄,能出个详细教程吗?
电脑有golang环境吗 腾讯云函数不是收费了吗??
我要是没猜错,你一定是亲爱的小沐沐啦。 云函数8/31到期。。告辞。。T-T 过来和大神学习来了!
页:
[1]
2