Dingtalk机器人发送群内消息

public class DingTalkNotifierTest {

	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();

		String atMobile = "138xxxxxxxx";
		String text = "滴滴滴~\n\n换行了么?";

		HttpEntity> request = createMessage("markdown", "服务告警", text, atMobile);

		restTemplate.postForEntity(
				"https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxx",
				request, Void.class);
		
	}

	private static HttpEntity> createMessage(String msgtype, String title, String text,
			String atMobiles) {
		Map params = new HashMap(2);
		params.put("text", text + getAtMobilesString(atMobiles));
		params.put("title", title);

		Map at = new HashMap(2);
		at.put("atMobiles", getAtMobilesList(atMobiles));
		at.put("isAtAll", false);

		Map messageJson = new HashMap(3);
		messageJson.put("msgtype", msgtype);
		messageJson.put(msgtype, params);
		messageJson.put("at", at);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		return new HttpEntity<>(messageJson, headers);
	}

	private static String getAtMobilesString(String s) {
		StringBuilder atMobiles = new StringBuilder();
		String[] mobiles = s.split(",");
		for (String mobile : mobiles) {
			atMobiles.append("@").append(mobile);
		}
		return atMobiles.toString();
	}

	private static List getAtMobilesList(String s) {
		String[] mobiles = s.split(",");
		List atMobilesList = new ArrayList();
		for (String mobile : mobiles) {
			atMobilesList.add(mobile);
		}
		return atMobilesList;
	}

}

参考链接:

钉钉开发文档:https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq

你可能感兴趣的:(Java)