我是靠谱客的博主 勤恳招牌,最近开发中收集的这篇文章主要介绍企业微信机器人实现自动推送天气预报,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

start~

因为要用到天气信息,在网上找了很多免费的api,不是有调用限制要不就是返回的结果不满意,最终看了百度的比较合适,决定用爬虫抓下来。

在百度上搜索"长春天气",将浏览器的地址复制,作为请求地址
因为我是吉林长春的所以就举例长春了可以换成自己想要的城市-.-
在这里插入图片描述

这里采用jsoup爬取数据

导入坐标↓

<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.3</version>
</dependency>

抓取程序代码

package com.gosingapore.cp.module.system.controller;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author conghua
 * @date 2021-09-27 下午 05:09
 */
@Component
public class Weather {
    //从浏览器复制的地址
    private static String weatherUrl = "https://www.baidu.com/s?ie=UTF-8&wd=%E9%95%BF%E6%98%A5%E5%A4%A9%E6%B0%94";
    public List<Map<String,Object>> getWeather() {
        List<Map<String,Object>> list = new ArrayList();
        String userAgent = UserAgentUtil.getUserAgents();
        try {
            Document doc = Jsoup.connect(weatherUrl).userAgent(userAgent).timeout(5000).get();
            Elements elements = doc.getElementsByClass("op_weather4_twoicon").get(0).getElementsByTag("a");
            for (Element element : elements) {
                String quality = "";
                String current = "";
                String today = "";
                //只有当天才有实时温度
                if (!element.getElementsByClass("op_weather4_twoicon_shishi_title").isEmpty()) {
                    current = element.getElementsByClass("op_weather4_twoicon_shishi_title").text();
                }
                //空气质量
                if (!element.getElementsByClass("op_weather4_twoicon_aqi_text_today").isEmpty()) {
                    quality = element.getElementsByClass("op_weather4_twoicon_aqi_text_today").text();
                } else {
                    quality = element.getElementsByClass("op_weather4_twoicon_aqi_text").text();
                }
                //日期
                if (!element.getElementsByClass("op_weather4_twoicon_date").isEmpty()) {
                    today = element.getElementsByClass("op_weather4_twoicon_date").text();
                } else {
                    today = element.getElementsByClass("op_weather4_twoicon_date_day").text();
                }
                //风向
                String wind = element.getElementsByClass("op_weather4_twoicon_wind").text();
                //天气
                String weath = element.getElementsByClass("op_weather4_twoicon_weath").text();
                //气温
                String temp = element.getElementsByClass("op_weather4_twoicon_temp").text();
                Map<String,Object> data = new HashMap<>(2);
                data.put("quality",quality);
                data.put("current",current);
                data.put("today",today);
                data.put("wind",wind);
                data.put("weath",weath);
                data.put("temp",temp);
                list.add(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}

设置浏览器版本,每次抓取的时候随机取一个浏览器版本,模拟不同浏览器访问

package com.gosingapore.cp.module.system.controller;

import java.util.Random;

/**
 * @author conghua
 * @date 2021-09-27 下午 05:10
 */
public class UserAgentUtil {
    private static final String[] USER_AGENTS = {
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
            "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
            "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
            "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
            "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
            "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52"
    };

    //随机
    public static String getUserAgents() {
        Random random = new Random();
        int index = random.nextInt(USER_AGENTS.length);
        return USER_AGENTS[index];
    }

    //选择第几个
    public static String getUserAgents(int index) {
        if (index == USER_AGENTS.length) {
            return getUserAgents();
        }
        return USER_AGENTS[index];
    }
}


Controller

这里设置每天7点自动调用接口自己可更改参数,RobotVo类 在我上一篇文章有需要的可以去copy

注:要想定时任务生效需在启动类加上@EnableScheduling注解

    @Scheduled(cron="0 0 7 * * ?")
    @GetMapping(value = "weatherRobot")
    public void testRobot() throws IOException {
        RobotVo vo = new RobotVo();
        //机器人地址
        vo.setWebhookAddress("机器人地址");
        List<Map<String, Object>> weathers = weather.getWeather();
        Map<String, Object> map = weathers.get(0);
        Object current = map.get("current");
        Object temp = map.get("temp");
        Object weath = map.get("weath");
        Object today = map.get("today");
        Object wind = map.get("wind");
        Object quality = map.get("quality");
        System.out.println(map);
        vo.setContent("长春市今日天气" + "n" + "空气质量:" + quality + "n" + "当前温度:" + current + "℃" + "n" + "全天温度:" + temp + "n" + "天气:" + weath + "n" + "日期:" + today + "n" + "风向:" + wind);
        System.out.println(vo.getContent());
        List<String> memberList = new ArrayList<>();
        vo.setMemberList(memberList);
        //指明类型
        vo.setMsgType("text");
        settingService.run(vo);
    }

Service接口

/**
 * 天气机器人
 * @param vo
 * @throws IOException
 */
void run(RobotVo vo)throws IOException;

Service实现

@Override
public void run(RobotVo vo) throws IOException {
    List<String> memberList = vo.getMemberList();
    String jsonData = "";
    String mobileList = "";
    String strMember = "";
    if (vo.getMsgType().equals("text")) {
        if (!Strings.isNullOrEmpty(vo.getMobileList())) {
            mobileList = vo.getMobileList();
        } else {
            mobileList = "";
        }
        for (int i = 0; i < memberList.size(); i++) {
            if (i == memberList.size() - 1) {
                strMember += """ + memberList.get(i) + """;
            } else {
                strMember += """ + memberList.get(i) + """ + ",";
            }
        }
        String[] members = new String[memberList.size()];
        for (int i = 0; i < memberList.size(); i++) {
            members[i] = memberList.get(i);
        }
        jsonData = "{n" +
                "t"msgtype": "" + vo.getMsgType() + "",n" +
                "    "text": {n" +
                "        "content": "" + vo.getContent() + "",n" +
                "        "mentioned_list":[" + strMember + "],n" +
                "        "mentioned_mobile_list":["" + mobileList + ""]n" +
                "    }n" +
                "}";

    } else if (vo.getMsgType().equals("image")) {
        //图片base64加密的值
        vo.setImageBase64Value(getImageStr(vo.getSavePath()));
        //图片md5加密的值
        vo.setImageMd5Value(DigestUtils.md5Hex(new FileInputStream(vo.getSavePath())));
        jsonData = "{n" +
                "    "msgtype": "" + vo.getMsgType() + "",n" +
                "    "image": {n" +
                "        "base64": "" + vo.getImageBase64Value() + "",n" +
                "        "md5": "" + vo.getImageMd5Value() + ""n" +
                "    }n" +
                "}";
    } else if (vo.getMsgType().equals("news")) {
        //图片+文字消息
        vo.setTitle(!Strings.isNullOrEmpty(vo.getTitle()) ? vo.getTitle() : "");
        jsonData = "{n" +
                "    "msgtype": "" + vo.getMsgType() + "",n" +
                "    "news": {n" +
                "       "articles" : [n" +
                "           {n" +
                "               "title" : "" + vo.getTitle() + "",n" +
                "               "description" : "" + vo.getDescription() + "",n" +
                "               "url" : "" + vo.getUrl() + "",n" +
                "               "picurl" : "" + vo.getImageUrl() + ""n" +
                "           }n" +
                "        ]n" +
                "    }n" +
                "}";
    }
    send(vo.getWebhookAddress(), jsonData);
}
   /**
     * 根据图片地址转换为base64编码字符串
     * @param imgFile
     * @return
     */
    public static String getImageStr(String imgFile) {
        //要想发送图片内容需要将图片加密转化成base64编码
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片加密
        Base64.Encoder er= Base64.getEncoder();
        return er.encodeToString(data);
    }
/**
 * 发送
 * @param url
 * @param param
 * @return
 */
public static JSONObject send(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    JSONObject jsonObject = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
        out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 获取请求返回数据(设置返回数据编码为UTF-8)
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        jsonObject = JSONObject.parseObject(result);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return jsonObject;
}

控制台效果

在这里插入图片描述

机器人通知群效果

在这里插入图片描述

end~

最后

以上就是勤恳招牌为你收集整理的企业微信机器人实现自动推送天气预报的全部内容,希望文章能够帮你解决企业微信机器人实现自动推送天气预报所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部