實現思路,利用微信網頁版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來獲取用戶信息。
