一、技术方案选型
1.1 微信消息发送方式分析
微信官方未提供直接的消息发送API,实现自动化消息主要有三种技术路径:
- 模拟操作方案:通过UI自动化工具模拟微信客户端操作
- 协议破解方案:逆向分析微信通信协议
- 第三方服务方案:使用合规的微信机器人服务
推荐方案:基于企业微信API+个人微信关联的合规方案,结合Selenium WebDriver实现模拟操作作为备选方案。
1.2 核心组件架构
graph TDA[定时任务调度] --> B[消息内容生成]B --> C[消息发送模块]C --> D[微信客户端接口]D --> E[企业微信API/模拟操作]
二、基于企业微信API的实现方案
2.1 准备工作
- 注册企业微信开发者账号
- 创建自建应用获取:
- CorpID
- AgentID
- Secret
- 配置接收方微信关联:
- 需将女友微信加入企业通讯录
- 或通过微信插件实现个人微信接收
2.2 核心代码实现
import com.alibaba.fastjson.JSONObject;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.nio.charset.StandardCharsets;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;public class WeChatMessageSender {private static final String CORP_ID = "your_corp_id";private static final String SECRET = "your_secret";private static final String AGENT_ID = "your_agent_id";private static final String USER_ID = "女友微信ID或手机号";// 获取AccessTokenpublic static String getAccessToken() throws Exception {String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +CORP_ID + "&corpsecret=" + SECRET;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);String response = httpClient.execute(httpPost, httpResponse ->EntityUtils.toString(httpResponse.getEntity()));JSONObject json = JSONObject.parseObject(response);return json.getString("access_token");}// 发送文本消息public static void sendTextMessage(String accessToken, String content) throws Exception {String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" +accessToken;JSONObject message = new JSONObject();message.put("touser", USER_ID);message.put("msgtype", "text");message.put("agentid", AGENT_ID);JSONObject text = new JSONObject();text.put("content", content);message.put("text", text);message.put("safe", 0);CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);httpPost.setEntity(new StringEntity(message.toJSONString(), StandardCharsets.UTF_8));httpClient.execute(httpPost, httpResponse ->System.out.println(EntityUtils.toString(httpResponse.getEntity())));}// 生成每日消息public static String generateDailyMessage() {LocalDateTime now = LocalDateTime.now();DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE");String dateStr = now.format(formatter);String[] greetings = {"早安宝贝!新的一天开始啦~","清晨的阳光因你而温暖,早安!","新的一天,愿你拥有好心情~"};int index = now.getHour() % greetings.length;return dateStr + "\n" + greetings[index] +"\n今天也要元气满满哦!";}public static void main(String[] args) {try {String accessToken = getAccessToken();String message = generateDailyMessage();sendTextMessage(accessToken, message);} catch (Exception e) {e.printStackTrace();}}}
2.3 定时任务配置
使用Spring Boot的@Scheduled注解实现定时:
import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class ScheduledTasks {@Scheduled(cron = "0 30 7 * * ?") // 每天7:30执行public void sendMorningGreeting() {WeChatMessageSender.main(null);}}
三、备选方案:Selenium模拟操作
3.1 实现原理
通过ChromeDriver控制浏览器自动:
- 打开微信网页版
- 扫描登录二维码
- 定位联系人并发送消息
3.2 关键代码片段
import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.chrome.ChromeOptions;public class WeChatWebAutomation {public static void sendMessage() {System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");ChromeOptions options = new ChromeOptions();options.addArguments("--user-data-dir=/path/to/profile"); // 保持登录状态WebDriver driver = new ChromeDriver(options);try {driver.get("https://wx.qq.com/");// 等待用户手动扫码登录Thread.sleep(30000);// 定位联系人(需根据实际页面结构调整)driver.findElement(By.xpath("//div[contains(@class,'contact')]")).click();// 输入消息并发送driver.findElement(By.id("chat_input")).sendKeys("早安宝贝!");driver.findElement(By.id("send_btn")).click();} catch (Exception e) {e.printStackTrace();} finally {driver.quit();}}}
四、安全与合规注意事项
-
隐私保护:
- 确保消息内容不包含敏感信息
- 避免存储女友微信账号等隐私数据
- 建议使用加密方式存储配置信息
-
合规性要求:
- 企业微信方案需遵守《企业微信开发者协议》
- 模拟操作方案仅限个人学习使用
- 避免高频发送导致账号被封禁
-
异常处理机制:
- 实现消息发送失败重试
- 添加日志记录功能
- 设置发送频率限制
五、功能扩展建议
-
消息内容多样化:
- 集成天气API添加天气信息
- 添加每日一句情话功能
- 实现纪念日提醒
-
交互功能增强:
- 接收女友回复并自动应答
- 实现消息模板自定义
- 添加语音消息发送功能
-
部署方案优化:
- 使用Docker容器化部署
- 配置服务器定时任务
- 实现多账号管理
六、完整实现步骤
- 注册企业微信开发者账号(约10分钟)
- 创建自建应用并获取凭证(5分钟)
- 配置Spring Boot项目(15分钟)
- 编写消息生成逻辑(10分钟)
- 设置定时任务(5分钟)
- 测试部署(10分钟)
总耗时:约1小时完成基础功能实现
七、常见问题解决方案
-
获取AccessToken失败:
- 检查CorpID和Secret是否正确
- 确认应用权限是否开启
- 检查网络连接是否正常
-
消息发送失败:
- 确认接收方是否在企业通讯录
- 检查AgentID是否正确
- 查看企业微信管理后台的发送限制
-
定时任务不执行:
- 确认是否添加了
@EnableScheduling注解 - 检查cron表达式是否正确
- 查看Spring Boot日志是否有错误
- 确认是否添加了
本文提供的方案兼顾了合规性与实用性,开发者可根据实际需求选择企业微信API方案或模拟操作方案。建议优先采用企业微信方案,其稳定性更高且符合微信平台规则。通过简单的配置和代码编写,即可实现每日自动发送温馨消息的功能,为亲密关系增添科技温度。