spring 集成钉钉机器人

@Slf4j
@RefreshScope
@Component
public class DingUtil {
    @Value("${ding.token}")
    private String token;
    public  void sendMsg(String applicationName,String text,String reqPath){
        try {
            //钉钉机器人地址(配置机器人的webhook)
            String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token="+token;
            //是否通知所有人
            boolean isAtAll = true;
            //通知具体人的手机号码列表
            List<String> mobileList = Lists.newArrayList();
            //mobileList.add("可以填入具体@到某个人,填入手机号");
            //钉钉机器人消息内容
            String content = "【"+getHostAddress()+"服务器,"+applicationName+"模块,"+reqPath+" bug】"+text;
            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, mobileList);

            //推送消息(http请求)
            String result = HttpUtil.post(dingUrl,reqStr);
            log.warn(result);

        }catch (Exception e){
            e.printStackTrace();

        }
    }

    /**
     * 组装请求报文
     * @param content
     * @return
     */
    private String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("content", content);

        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return JSON.toJSONString(reqMap);
    }
    /**
     * 获取本机ip linux和windows通用
     * */
    public String getHostAddress() {
        try{
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()){
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress ip = addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址,IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":")==-1){
                        return ip.getHostAddress();
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
}

 

posted @ 2020-12-02 17:22  动力起点  阅读(230)  评论(0编辑  收藏  举报