Java自动化浪漫:每日定时发送微信消息的实现方案

一、技术方案选型

1.1 微信消息发送方式分析

微信官方未提供直接的消息发送API,实现自动化消息主要有三种技术路径:

  • 模拟操作方案:通过UI自动化工具模拟微信客户端操作
  • 协议破解方案:逆向分析微信通信协议
  • 第三方服务方案:使用合规的微信机器人服务

推荐方案:基于企业微信API+个人微信关联的合规方案,结合Selenium WebDriver实现模拟操作作为备选方案。

1.2 核心组件架构

  1. graph TD
  2. A[定时任务调度] --> B[消息内容生成]
  3. B --> C[消息发送模块]
  4. C --> D[微信客户端接口]
  5. D --> E[企业微信API/模拟操作]

二、基于企业微信API的实现方案

2.1 准备工作

  1. 注册企业微信开发者账号
  2. 创建自建应用获取:
    • CorpID
    • AgentID
    • Secret
  3. 配置接收方微信关联:
    • 需将女友微信加入企业通讯录
    • 或通过微信插件实现个人微信接收

2.2 核心代码实现

  1. import com.alibaba.fastjson.JSONObject;
  2. import org.apache.http.client.methods.HttpPost;
  3. import org.apache.http.entity.StringEntity;
  4. import org.apache.http.impl.client.CloseableHttpClient;
  5. import org.apache.http.impl.client.HttpClients;
  6. import org.apache.http.util.EntityUtils;
  7. import java.nio.charset.StandardCharsets;
  8. import java.time.LocalDateTime;
  9. import java.time.format.DateTimeFormatter;
  10. public class WeChatMessageSender {
  11. private static final String CORP_ID = "your_corp_id";
  12. private static final String SECRET = "your_secret";
  13. private static final String AGENT_ID = "your_agent_id";
  14. private static final String USER_ID = "女友微信ID或手机号";
  15. // 获取AccessToken
  16. public static String getAccessToken() throws Exception {
  17. String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +
  18. CORP_ID + "&corpsecret=" + SECRET;
  19. CloseableHttpClient httpClient = HttpClients.createDefault();
  20. HttpPost httpPost = new HttpPost(url);
  21. String response = httpClient.execute(httpPost, httpResponse ->
  22. EntityUtils.toString(httpResponse.getEntity()));
  23. JSONObject json = JSONObject.parseObject(response);
  24. return json.getString("access_token");
  25. }
  26. // 发送文本消息
  27. public static void sendTextMessage(String accessToken, String content) throws Exception {
  28. String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" +
  29. accessToken;
  30. JSONObject message = new JSONObject();
  31. message.put("touser", USER_ID);
  32. message.put("msgtype", "text");
  33. message.put("agentid", AGENT_ID);
  34. JSONObject text = new JSONObject();
  35. text.put("content", content);
  36. message.put("text", text);
  37. message.put("safe", 0);
  38. CloseableHttpClient httpClient = HttpClients.createDefault();
  39. HttpPost httpPost = new HttpPost(url);
  40. httpPost.setEntity(new StringEntity(message.toJSONString(), StandardCharsets.UTF_8));
  41. httpClient.execute(httpPost, httpResponse ->
  42. System.out.println(EntityUtils.toString(httpResponse.getEntity())));
  43. }
  44. // 生成每日消息
  45. public static String generateDailyMessage() {
  46. LocalDateTime now = LocalDateTime.now();
  47. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE");
  48. String dateStr = now.format(formatter);
  49. String[] greetings = {
  50. "早安宝贝!新的一天开始啦~",
  51. "清晨的阳光因你而温暖,早安!",
  52. "新的一天,愿你拥有好心情~"
  53. };
  54. int index = now.getHour() % greetings.length;
  55. return dateStr + "\n" + greetings[index] +
  56. "\n今天也要元气满满哦!";
  57. }
  58. public static void main(String[] args) {
  59. try {
  60. String accessToken = getAccessToken();
  61. String message = generateDailyMessage();
  62. sendTextMessage(accessToken, message);
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }

2.3 定时任务配置

使用Spring Boot的@Scheduled注解实现定时:

  1. import org.springframework.scheduling.annotation.Scheduled;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. public class ScheduledTasks {
  5. @Scheduled(cron = "0 30 7 * * ?") // 每天7:30执行
  6. public void sendMorningGreeting() {
  7. WeChatMessageSender.main(null);
  8. }
  9. }

三、备选方案:Selenium模拟操作

3.1 实现原理

通过ChromeDriver控制浏览器自动:

  1. 打开微信网页版
  2. 扫描登录二维码
  3. 定位联系人并发送消息

3.2 关键代码片段

  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. import org.openqa.selenium.chrome.ChromeOptions;
  5. public class WeChatWebAutomation {
  6. public static void sendMessage() {
  7. System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
  8. ChromeOptions options = new ChromeOptions();
  9. options.addArguments("--user-data-dir=/path/to/profile"); // 保持登录状态
  10. WebDriver driver = new ChromeDriver(options);
  11. try {
  12. driver.get("https://wx.qq.com/");
  13. // 等待用户手动扫码登录
  14. Thread.sleep(30000);
  15. // 定位联系人(需根据实际页面结构调整)
  16. driver.findElement(By.xpath("//div[contains(@class,'contact')]"))
  17. .click();
  18. // 输入消息并发送
  19. driver.findElement(By.id("chat_input"))
  20. .sendKeys("早安宝贝!");
  21. driver.findElement(By.id("send_btn"))
  22. .click();
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. } finally {
  26. driver.quit();
  27. }
  28. }
  29. }

四、安全与合规注意事项

  1. 隐私保护

    • 确保消息内容不包含敏感信息
    • 避免存储女友微信账号等隐私数据
    • 建议使用加密方式存储配置信息
  2. 合规性要求

    • 企业微信方案需遵守《企业微信开发者协议》
    • 模拟操作方案仅限个人学习使用
    • 避免高频发送导致账号被封禁
  3. 异常处理机制

    • 实现消息发送失败重试
    • 添加日志记录功能
    • 设置发送频率限制

五、功能扩展建议

  1. 消息内容多样化

    • 集成天气API添加天气信息
    • 添加每日一句情话功能
    • 实现纪念日提醒
  2. 交互功能增强

    • 接收女友回复并自动应答
    • 实现消息模板自定义
    • 添加语音消息发送功能
  3. 部署方案优化

    • 使用Docker容器化部署
    • 配置服务器定时任务
    • 实现多账号管理

六、完整实现步骤

  1. 注册企业微信开发者账号(约10分钟)
  2. 创建自建应用并获取凭证(5分钟)
  3. 配置Spring Boot项目(15分钟)
  4. 编写消息生成逻辑(10分钟)
  5. 设置定时任务(5分钟)
  6. 测试部署(10分钟)

总耗时:约1小时完成基础功能实现

七、常见问题解决方案

  1. 获取AccessToken失败

    • 检查CorpID和Secret是否正确
    • 确认应用权限是否开启
    • 检查网络连接是否正常
  2. 消息发送失败

    • 确认接收方是否在企业通讯录
    • 检查AgentID是否正确
    • 查看企业微信管理后台的发送限制
  3. 定时任务不执行

    • 确认是否添加了@EnableScheduling注解
    • 检查cron表达式是否正确
    • 查看Spring Boot日志是否有错误

本文提供的方案兼顾了合规性与实用性,开发者可根据实际需求选择企业微信API方案或模拟操作方案。建议优先采用企业微信方案,其稳定性更高且符合微信平台规则。通过简单的配置和代码编写,即可实现每日自动发送温馨消息的功能,为亲密关系增添科技温度。