Golang -- openwechat WeChat send message, auto reply

opening

The Lunar New Year is coming soon, you might as well write a piece of code to send blessings to your friends on time.
This Demo uses the open source project openwechat to realize the functions of obtaining friend list, sending messages, pictures or files for friends, receiving messages from friends or groups and setting automatic reply, etc.
openwechat Github address
openwechat document address

code structure

insert image description here

Project entry

The code is very simple, just call the start method of WeChat

Start WeChat

package bootstrap

import (
	"os"

	wechat "wechatbot/handler"
	"wechatbot/task"

	"github.com/eatmoreapple/openwechat"
	log "github.com/sirupsen/logrus"
)

func StartWebChat() {
    
    
	//清除旧的token文件
	os.Remove("token.json")
	//初始化桌面微信
	bot := openwechat.DefaultBot(openwechat.Desktop)
	//设置微信消息处理模块,自动回复
	bot.MessageHandler = wechat.Handler
	//显示登陆二维码
	bot.UUIDCallback = openwechat.PrintlnQrcodeUrl

	reloadStorage := openwechat.NewJsonFileHotReloadStorage("token.json")
	err := bot.HotLogin(reloadStorage)
	if err != nil {
    
    
		if err = bot.Login(); err != nil {
    
    
			log.Fatal(err)
			return
		}
	}

	// 获取登陆用户信息
	self, err := bot.GetCurrentUser()
	if err != nil {
    
    
		log.Fatal(err)
		return
	}
	// 获取好友列表
	friends, err := self.Friends()
	if err != nil {
    
    
		log.Fatal(err)
		return
	} else {
    
    
		// 初始化定时任务 
		nytask := task.NewYearMessageDomain{
    
    
			Content:   "零时的钟声响彻天涯,新年的列车准时出发.它驮去难忘的岁月,迎来了又一轮火红的年华.祝你新年快乐,鹏程万里!",
			Imguris:   []string{
    
    "E:\\新年快乐.jpg"},
			Receivers: []string{
    
    "xxxxx1","xxxxx2"},
			Blacklist: []string{
    
    "xxxxx3"},
			Friends:   friends}
		nytask.InitTask()
	}

	//阻塞进程 等待桌面微信退出
	err = bot.Block()
	if err != nil {
    
    
		log.Fatal(err)
		return
	}
}

WeChat message processing module

When we started WeChat, we set up a WeChat message processing function.
insert image description here
We checked the MessageHandler and found that it is actually a custom func type that receives the Message pointer type and processes it . Therefore, the wechat.Handler
insert image description here
we need to create must be a method with the same parameters and return value as MessageHandler .

package wechat

import (
	"strings"

	"github.com/eatmoreapple/openwechat"
	log "github.com/sirupsen/logrus"
)

func Handler(msg *openwechat.Message) {
    
    
	err := handle(msg)
	if err != nil {
    
    
		log.Errorf("handle error: %s\n", err.Error())
		return
	}
}

func handle(msg *openwechat.Message) error {
    
    
	if !msg.IsText() {
    
    //只处理回复文本消息
		return nil
	}
	return ReplyText(msg)
}

func ReplyText(msg *openwechat.Message) error {
    
    

	sender, err := msg.Sender()
	if err == nil {
    
    
		if sender.IsFriend() {
    
     //判断如果是好友发来的消息,则处理
			msgContent := msg.Content
			//如果好友发来了新年好 或者 新年快乐,回复新年好
			if strings.Contains(msgContent, "新年") && (strings.Contains(msgContent, "好") || strings.Contains(msgContent, "快乐")) {
    
    
				msg.ReplyText("新年好呀")
			}
		}
	} else {
    
    
		log.Fatal(err)
	}

	return nil
}

timed task

Timing tasks use the framework of robfig/cron ,
robfig/cron document address

Create a NewYearMessageDomain structure, which contains the following attributes:
1. The text message to be sent
2. The address of the picture to be sent
3. The set recipient list, if it is empty, it will be sent to all friends
4. The set blacklist list
5. Openwechat friend information list

package task

import (
	"fmt"
	"os"
	"time"

	"github.com/eatmoreapple/openwechat"
	"github.com/robfig/cron/v3"
)

type NewYearMessageDomain struct {
    
    
	Content   string             //文本消息
	Imguris   []string           //图片地址
	Receivers []string           //接收人
	Blacklist []string           //黑名单
	Friends   openwechat.Friends //好友列表
}

// 判断切片中是否存在某个元素
func (nymd *NewYearMessageDomain) find(slice []string, val string) bool {
    
    
	for i := range slice {
    
    
		if slice[i] == val {
    
    
			return true
		}
	}
	return false
}

//初始化定时任务的方法
func (nymd *NewYearMessageDomain) InitTask() {
    
    

	//设置定时任务
	crontab := cron.New(cron.WithSeconds()) //精确到秒
	//定义定时器调用的任务函数
	task := func() {
    
    
		for i := range nymd.Friends {
    
    
			friend := nymd.Friends[i]
 			//好友在黑名单里 不发送消息
			if nymd.find(nymd.Blacklist, friend.NickName) {
    
    
				continue
			}

			//如果设置了发送好友列表 则判断是否在列表中,否则直接发送
			if (len(nymd.Receivers) > 0 && nymd.find(nymd.Receivers, friend.NickName)) || len(nymd.Receivers) == 0 {
    
    
				if len(nymd.Content) > 0 {
    
    
					//发送祝福语
					friend.SendText(nymd.Content)
				}
				if len(nymd.Imguris) > 0 {
    
    
					//设置了图片路径 发送图片
					for i := range nymd.Imguris {
    
    
						fileInfos, err := os.Open(nymd.Imguris[i])
						defer fileInfos.Close()
						if err == nil {
    
    
							time.Sleep(time.Millisecond * 50) //频繁发送可能会被微信限制
							friend.SendImage(fileInfos)
						} else {
    
    
							fmt.Println(err)
						}
					}
				}
			}

		}
	}
	//设置cron表达式  指定时间
	spec := "0 0 0 21 1 2023"
	// 添加定时任务
	crontab.AddFunc(spec, task)
	// 启动定时器
	crontab.Start()
}

Effect

After starting the program, a QR code will pop up, and the WeChat on the mobile phone will scan it to log in to the WeChat on the desktop.
insert image description here
Send messages automatically.
insert image description here
Automatic reply function.
insert image description here

Guess you like

Origin blog.csdn.net/qq_40096897/article/details/128701148