package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/eatmoreapple/openwechat"
"github.com/robfig/cron/v3"
"github.com/skip2/go-qrcode"
)
//计划任务函数
func crontab(self *openwechat.Self, groups openwechat.Groups) {
//每天上午7点30分10秒
spec := "10 30 7 * * ?"
c := cron.New(cron.WithSeconds())
c.AddFunc(spec, func() {
qrImg, err := os.Open("qr.jpg")
if err != nil {
log.Println(err)
}
defer qrImg.Close()
self.SendImageToGroup(groups.GetByNickName("xxx软件组"), qrImg)
self.SendTextToGroup(groups.GetByNickName("xxx软件组"), getWeather())
})
c.Start()
select {}
}
//获取当天实时的天气情况函数
func getWeather() (weatherText string) {
weatherUrl := "https://api.seniverse.com/v3/weather/daily.json?key=xxxxx&location=city&language=zh-Hans&unit=c&start=0&days=1"
response, err := http.Get(weatherUrl)
if err != nil {
fmt.Println(err)
}
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
if err != nil {
log.Println(err)
}
// fmt.Printf("%s",data)
weatherMap := make(map[string][]map[string][]map[string]string)
json.Unmarshal(data, &weatherMap)
weather := weatherMap["results"][0]["daily"]
//日期
weatherDate := weather[0]["date"]
//当天最高气温
weatherHigh := weather[0]["high"]
//当天最低所温
weatherLow := weather[0]["low"]
//天气
weatherDay := weather[0]["text_day"]
weatherText = fmt.Sprintf("我是精灵萌萌今天%s日,天气%s今日最高气温%s度最低气温%s度,大家不要忘记填写流调呦~~", weatherDate, weatherDay, weatherHigh, weatherLow)
return weatherText
}
//生成二维码,主要是配置控制台使用的一个函数
func ConsoleQrCode(uuid string) {
q, _ := qrcode.New("https://login.weixin.qq.com/l/"+uuid, qrcode.Low)
fmt.Println(q.ToString(true))
}
func main() {
// bot := openwechat.DefaultBot()
bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式,上面登录不上的可以尝试切换这种模式
// 注册消息处理函数
bot.MessageHandler = func(msg *openwechat.Message) {
if msg.IsText() && msg.Content == "ping" {
msg.ReplyText("pong")
}
}
// 注册登陆二维码回调
bot.UUIDCallback = openwechat.PrintlnQrcodeUrl
// 注册登陆二维码在终端下回调
bot.UUIDCallback = ConsoleQrCode
// 登陆
if err := bot.Login(); err != nil {
fmt.Println(err)
return
}
// 获取登陆的用户
self, err := bot.GetCurrentUser()
if err != nil {
fmt.Println(err)
return
}
// 获取所有的群组
groups, err := self.Groups()
if err != nil {
log.Println(err)
}
// fmt.Println(groups, err)
//按时间计划发送信息
go crontab(self, groups)
// 阻塞主goroutine, 直到发生异常或者用户主动退出
bot.Block()
}