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


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

1、安装lombok

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

       <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency> 

2、添加依赖

<dependency> <groupId>io.github.biezhi</groupId> <artifactId>wechat-api</artifactId> <version>1.0.6</version> </dependency> 

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

<dependency> <groupId>io.github.biezhi</groupId> <artifactId>wechat-api</artifactId> <version>1.0.6</version> <exclusions> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> </exclusions> </dependency> 

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来获取用户信息。




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM