微信个人号实现微信好友和微信群自动发送消息

实现思路,利用微信网页版API,登陆微信,获取好友和群组信息,调用微信web端API发送消息

1、安装lombok

在本地开发环境安装 lombok 插件并确保你的 Java 环境是 1.7+

       
            org.projectlombok
            lombok
            1.16.18
            provided
        

2、添加依赖


    io.github.biezhi
    wechat-api
    1.0.6

该依赖中包含了日志组件,默认是 logback,如果你的系统中需要其他的日志组件,请先排除 logback


    io.github.biezhi
    wechat-api
    1.0.6
    
        
            ch.qos.logback
            logback-classic
        
    

3 创建微信机器人

机器人 WeChatBot 对象可被理解为一个 Web 微信客户端。创建一个 Java 类作为我们的机器人,比如 HelloBot

package com.topcom.cms.spider.weixin;

import io.github.biezhi.wechat.WeChatBot;
import io.github.biezhi.wechat.api.constant.Config;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HelloBot extends WeChatBot {

//登陆二维保存路径
    private static String assetsDir = "C:/QRCodePath/";

    private volatile static HelloBot helloBot;

    public static void setAssetsDir(String assetsDir) {
        HelloBot.assetsDir = assetsDir;
    }

    public static HelloBot getInstance(){
        if(helloBot == null){
            synchronized (HelloBot.class){
               if(helloBot ==null){
                   helloBot = new HelloBot(Config.me().autoLogin(true).assetsDir(assetsDir).showTerminal(true));
               }
            }
        }
        return helloBot;
    }
    private HelloBot(Config config) {
        super(config);
    }

    public static void main(String[] args) {
        getInstance().start();
    }
}

其他WeChatBot操作可以参考微信个人号API
https://biezhi.github.io/wechat-api/#/

package com.topcom.cms.spider.weixin;

import com.topcom.cms.spider.core.config.SpiderConfigAware;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @Author shaol
 * @Date 2019年1月24日
 */
@Component
public class WeixinBoot implements CommandLineRunner, SpiderConfigAware {
    @Override
    public void run(String... args) throws Exception {
        HelloBot.setAssetsDir(spiderConfig.getWechatCode());
        HelloBot.getInstance().start();
    }

/**
     * 根据好友的昵称
     * @param nickName 好友昵称
     * @param msg 发送消息
     */
    public Boolean sendMsg(String nickName, String msg) {
        HelloBot helloBot = HelloBot.getInstance();
        if (null != helloBot) {
            String fromUserName = helloBot.api().getAccountByName(nickName).getUserName();
            return helloBot.sendMsg(fromUserName, msg);
        }
        return false;
    }
}

注:用户的nickname可以重复,UserName不会重复,但是每次登陆后UserName会变化,可以用在每次登陆后保存UserName,调用helloBot.api().getAccountById来获取用户信息。

参考文档:

https://biezhi.github.io/wechat-api/
https://github.com/biezhi/wechat-api
感谢好友LI木水推荐的微信个人API
https://www.jianshu.com/u/14313cc03bd0

你可能感兴趣的:(微信个人号实现微信好友和微信群自动发送消息)