(WeChat sends messages regularly) A java file to complete the configurable task of sending messages on WeChat regularly

source of demand

In our daily work, we need to send group messages regularly every day. If the time is too early, we don’t want to wake up, thinking that we can use java to display the task of sending messages regularly. Let the program help us send messages regularly in our sleep.

Features

定时生日祝福、每日早安、晚安问候

  1. Check if WeChat is running in the background again
  2. Specify multiple times per day to send configurable messages
  3. send pictures
  4. Send multiple messages to multiple people per time period
  5. Set the interval time (eg: once every two days, once a day, once a second)

code show as below

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.KeyEvent;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.*;

/**
 * @Author: xu
 * @Description: 开启定时任务,指定时间,间隔给微信好友发送文本或图片
 * @Date: 2021/12/20 20:28
 */
public class TimerTask {
    
    
//    设置定时任务区间,每隔一天发一次
    private static final Long SECTION = (long) (24 * 60 * 60 * 1000);

    public static void main(String[] args) throws Exception {
    
    
        System.out.println("任务执行时间,请保证微信在登录状态并为最小化...");
        int weChat = queryProcessCount("WeChat");
        if (weChat<=0){
    
    
            System.err.println("请登陆微信后再尝试运行");
            return;
        }
        int year = LocalDateTime.now().getYear();
        int month = LocalDateTime.now().getMonthValue();
        int day = LocalDateTime.now().getDayOfMonth();     //任务默认从今天开始
        List<String> resource = getResouce();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        遍历某个时间段需要做的事情
        for (String todo : resource) {
    
    
            String[] item = todo.split(" ");
            String formatData = year+"-"+month+"-"+day+" "+item[0]+":00";
            Date firstData = simpleDateFormat.parse(formatData);
            List<Map<String,String>> sendData = new ArrayList<>();
            String[] sends = todo.split(";");
            int i = 0;
            for (String send : sends) {
    
    
                Map<String,String> map = new HashMap<>();
                List<String> strings = Arrays.asList(send.split(" "));
                if (i==0){
    
    
                    map.put("receive",strings.get(1));
                    map.put("content",strings.get(2));
                }else {
    
    
                    map.put("receive",strings.get(0));
                    map.put("content",strings.get(1));
                }
                sendData.add(map);
                i++;
            }
            createTask(firstData,sendData);
        }
    }

    private static int queryProcessCount(String processName) throws IOException {
    
    
        int count = 0;
        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<>();
        Process process = runtime.exec("tasklist");
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s;
        while ((s = br.readLine()) != null) {
    
    
            if ("".equals(s)) {
    
    
                continue;
            }
            tasklist.add(s);
        }
        for (String taskName : tasklist) {
    
    
            if (taskName.contains(processName)){
    
    
                count++;
            }
        }
        return count;
    }
    private static void createTask(Date firstData,List<Map<String,String>> sendData){
    
    
        if (firstData.getTime()-System.currentTimeMillis()<0){
    
    
            //        让错过的时间延后配置的间隔时间执行
            firstData = new Date(firstData.getTime()+SECTION);
        }
        new Timer().scheduleAtFixedRate(new java.util.TimerTask() {
    
    
            @Override
            public synchronized void run() {
    
    
                try {
    
    
                    openWeChat();
                    for (Map<String, String> sendDatum : sendData) {
    
    
                        sendMsg(sendDatum.get("receive"),sendDatum.get("content"));
                        Thread.sleep(500);
                    }
                    closeWeChat();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        },firstData.getTime() - System.currentTimeMillis(),SECTION);
    }

    public static void setSysClipboardFile(String imageUrl) throws IOException {
    
    
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        if (imageUrl.contains("\\")){
    
    
            imageUrl = imageUrl.replace("\\","/");
        }
        imageUrl = imageUrl.replace("img(","");
        imageUrl = imageUrl.substring(0, imageUrl.length() - 1);
        Image image = ImageIO.read(new File(imageUrl));
        Transferable trans = new Transferable() {
    
    
            @Override
            public Object getTransferData(DataFlavor flavor)
                    throws UnsupportedFlavorException {
    
    
                if (isDataFlavorSupported(flavor)) {
    
    
                    return image;
                }
                throw new UnsupportedFlavorException(flavor);
            }

            @Override
            public DataFlavor[] getTransferDataFlavors() {
    
    
                return new DataFlavor[] {
    
     DataFlavor.imageFlavor };
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor) {
    
    
                return DataFlavor.imageFlavor.equals(flavor);
            }
        };
        clip.setContents(trans, null);
    }

    public static void setSysClipboardText(String writeMe) {
    
    
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(writeMe);
        clip.setContents(tText, null);
    }

    private static void openWeChat() throws AWTException {
    
    
        Robot robot = RobotManager.getInstance();
//        robot.keyPress(KeyEvent.VK_WINDOWS);
//        robot.keyPress(KeyEvent.VK_D);
//        robot.keyRelease(KeyEvent.VK_WINDOWS);
//        robot.keyRelease(KeyEvent.VK_D);
//        先使用win+D快捷键保证微信为最小化状态,再使用微信默认快捷键打开微信nihao2
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_ALT);
        robot.keyRelease(KeyEvent.VK_W);
        robot.delay(100);
    }

    /**
     * 发送消息
     * @param receive 接收消息者
     * @param msg 消息内容
     */
    private static void sendMsg(String receive,String msg) throws Exception {
    
    
        Robot robot = RobotManager.getInstance();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_F);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_F);
        inputEnter(receive);
        inputEnter(msg);
    }

    private static void closeWeChat() throws AWTException {
    
    
        Robot robot = RobotManager.getInstance();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_W);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_ALT);
        robot.keyRelease(KeyEvent.VK_W);
    }

    private static void inputEnter(String msg) throws Exception {
    
    
        Robot robot = RobotManager.getInstance();
        if (msg.contains("img(")){
    
    
            setSysClipboardFile(msg);
        }else {
    
    
            setSysClipboardText(msg);
        }
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);
        robot.delay(500);
    }

    public static class RobotManager{
    
    
        private static Robot robot;

        public static Robot getInstance() throws AWTException {
    
    
            if (robot==null){
    
    
                robot = new Robot();
            }
            return robot;
        }
    }

    public static List<String> getResouce() throws Exception {
    
    
        StringBuilder result = new StringBuilder();
        //读取桌面Txt文件,桌面路径与文件名根据需要修改
        FileReader reader = new FileReader("C:\\Users\\xjt\\Desktop\\sendmag.txt", StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(reader);
        String temp;
        while((temp = br.readLine())!=null){
    
    //使用readLine方法,一次读一行
            result.append(temp);
        }
        br.close();
        reader.close();
        return Arrays.asList(result.toString().split("\\*"));
    }
}

configuration information

Required desktop text file configuration information content

11:14 接收者名称 发送内容;xjt(接收者名称) img(C:\Users\Hasee\Desktop\checkcode.jpg);文件传输助手 内容*
11:15 xjt nihao2*
11:16 xjt nihao3

Profile Analysis

配置符号由代码中定义。可根据需要进行修改优化

*: The end character of the running task at the current time, the last task does not need the end character
;: the interval character of each task
空格: the separator between the time and the recipient name and the content
img(): the local absolute address of the picture specified when the content is a picture

How to use

  1. Copy the content of the above code into a TimerTask.javafile named
  2. In the modification file, the current environment configuration file specifies the address

insert image description here

Execute compile and run command

compile

javac -encoding UTF-8 TimerTask.java

start operation

java TimerTask

Or run directly in IDE development tools

Guess you like

Origin blog.csdn.net/languageStudent/article/details/122123484