四、JAVA使用企业微信机器人发送群消息

x33g5p2x  于2022-03-08 转载在 Java  
字(7.6k)|赞(0)|评价(0)|浏览(1053)

1.如何在企业微信群中创建一个机器人


  

2.企业微信机器人发送群消息

2.1相关的api文档

群机器人配置说明 - 接口文档 - 企业微信开发者中心

2.2java需要引入的jar包

      通过文档,可以知道,只是调用一个http请求。我这边使用的是httpclient进行调用。需要添加的依赖有:

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.32</version>
        </dependency>

2.3相关代码实现

package com.test.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    public static String doGet(String url, String proxyUrl, Map<String, String> header, Map<String, String> param) {
        log.info("request doGet, url:{}, proxyUrl:{}, header:{}, param:{}", url, proxyUrl, header, param);

        // 创建Httpclient对象
        CloseableHttpClient httpclient = null;

        // 走代理请求
        if (StringUtils.isNotEmpty(proxyUrl)) {
            //设置代理IP、端口、协议
            HttpHost proxy = HttpHost.create(proxyUrl);
            //把代理设置到请求配置
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();
            httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        } else {
            httpclient = HttpClients.createDefault();
        }

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // header
            if (header != null) {
                Header[] allHeader = new BasicHeader[header.size()];
                int i = 0;
                for (Map.Entry<String, String> entry: header.entrySet()){
                    allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
                    i++;
                }
                httpGet.setHeaders(allHeader);
            }

            // 执行请求
            response = httpclient.execute(httpGet);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 判断返回状态是否为200
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("doGet response error, url:{}, statusCode:{}, msg:{}", url, statusCode, resultString);
                throw new RuntimeException(resultString);
            }
        } catch (Exception e) {
            log.error("doGet request error:", e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error("doGet closeableHttpResponse close error:", e);
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null, null, null);
    }

    public static String doGet(String url, String proxyUrl) {
        return doGet(url, proxyUrl, null, null);
    }

    public static String doPost(String url, String proxyUrl, Map<String, String> header, String param) {
        if (header == null) {
            header = new HashMap<>();
        }
        header.put("Content-type", "application/json;charset=UTF-8");
        log.info("request doPost, url:{}, proxyUrl:{}, header:{}, param:{}", url, proxyUrl, header, param);

        // 创建Httpclient对象
        CloseableHttpClient httpClient = null;

        // 走代理请求
        if (StringUtils.isNotEmpty(proxyUrl)) {
            //设置代理IP、端口、协议
            HttpHost proxy = HttpHost.create(proxyUrl);
            //把代理设置到请求配置
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // header
            Header[] allHeader = new BasicHeader[header.size()];
            int i = 0;
            for (Map.Entry<String, String> entry: header.entrySet()){
                allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
                i++;
            }
            httpPost.setHeaders(allHeader);
            // 创建参数列表
            if (param != null) {
                StringEntity stringEntity = new StringEntity(param, "UTF-8");
                stringEntity.setContentEncoding("UTF-8");
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 判断返回状态是否为200
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("doPost response error, url:{}, statusCode:{}, msg:{}", url, statusCode, resultString);
                throw new RuntimeException(resultString);
            }
        } catch (Exception e) {
            log.error("doPost request error:", e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("doPost closeableHttpResponse close error:", e);
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null, null, null);
    }

    public static String doPost(String url, String proxyUrl) {
        return doPost(url, proxyUrl, null, null);
    }

}
@Test
    public void test1() {
        String key = "9d1efcff-c62e-4c93-bb7c-21d947c53cbc";// 从建群的机器人那里获取
        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s", key);
        Map<String, Object> param = new HashMap<>();
        String msgType = "markdown";
        param.put("msgtype", msgType);
        Map<String, Object> msg = new HashMap<>();
        String content = "实时新增用户反馈<font color=\"warning\">132例</font>,请相关同事注意。\n" +
                ">类型:<font color=\"comment\">用户反馈</font> \n" +
                ">普通用户反馈:<font color=\"comment\">117例</font> \n" +
                ">VIP用户反馈:<font color=\"comment\">15例</font> \n";
        msg.put("content", content);

        param.put(msgType, msg);
        String jsonParam = JSONObject.toJSONString(param);
        String result = HttpClientUtil.doPost(url, null, null, jsonParam);
        log.info("result:{}", result);
    }

2.4遇到的问题

      当我想将发送的消息抽成一个模板,放到nacos配置文件的时候。遇到了一个问题:yml转行问题。

@Configuration
@RefreshScope
@Data
@ConfigurationProperties(prefix = "activity")
public class ActivityCreateConfig {

    private String wxGroupKey;
    private String createActivityTemplate;

    private String approveSkuTemplate;

    private String saveLinksTemplate;

    private String importSkuTemplate;

    private List<TenantKeyMap> tenantKeyMapping;

}
@Data
public class TenantKeyMap {
    private Long tenantId;
    private String key;
}

对应的template配置如下:

activity:
  wxGroupKey: 9d1efcff-c62e-4c93-bb7c-21d947c53cbc
  createActivityTemplate: "有新的活动创建,请即使处理。\n
  >团长名称:<font color='warning'>%s</font>\n
  >活动:<font color='warning'>%s</font>\n
  >创建时间:<font color='#666666'>%s</font>\n
  >报名时间:<font color='#666666'>%s</font>\n
  >推广时间:<font color='#666666'>%s</font>\n"
  saveLinksTemplate: "抖音活动已创建。\n
  >活动名称:<font color='warning'>%s</font>\n
  >报名链接:<font color='warning'>[报名链接](%s)</font>\n"
  importSkuTemplate: "抖音活动商品已更新。\n
  >活动名称:<font color='warning'>%s</font>\n
  >待审核:<font color='info'>%s</font>\n
  >已审核:<font color='info'>%s</font>\n"
  approveSkuTemplate: "有新的商品审核通过,请及时处理\n
  >团长名称:<font color='warning'>%s</font>\n
  >活动:<font color='warning'>%s</font>\n
  >审批时间:<font color='warning'>%s</font>\n"
  tenantKeyMapping:
  - tenantId: 100240
    key: 9d1efcff-c62e-4c93-bb7c-21d947c53cbc
  - tenantId: 100240
    key: 9d1efcff-c62e-4c93-bb7c-21d947c53cbc

相关文章