钉钉自定义机器人-后台开发,我们通过配置就好了,方便操作!下面实例是22点22分发送不同的消息。
官方文档:https://open-doc.dingtalk.com/docs/doc.htm?treeId=257&articleId=106438&docType=1
后台界面
开发步骤
1) 先拿到机器人的webhock
2) 对消息封装,然后post请求发送
package io.renren.modules.job.task;
import io.renren.common.exception.BizException;
import io.renren.common.exception.RRException;
import io.renren.modules.robot.message.*;
import io.renren.modules.robot.service.DingtalkChatbotClient;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author lanxinghua
* @date 2018/08/04 14:15
* @description 钉钉机器人测试
*/
@Component("dDRobotTask")
public class DDRobotTask {
private Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private DingtalkChatbotClient dingtalkChatbotClient;
public void sendTextMessage(String param){
try {
JSONObject json = JSONObject.fromObject(param);
String webhock = json.getString("webhock");
Message message = new TextMessage(json.getString("message"));
JSONArray array = JSONArray.fromObject(json.getString("toUser"));
if (array.size()==0){
((TextMessage) message).setIsAtAll(true);
}else {
((TextMessage) message).setAtMobiles(JSONArray.toList(array,new String(),new JsonConfig()));
}
dingtalkChatbotClient.send(webhock,message);
logger.info("发送成功!sendTextMessage");
} catch (Exception e) {
throw new BizException("数据填写有误!",0);
}
}
public void sendLinkMessage(String param){
try {
LinkMessage message = new LinkMessage();
JSONObject json = JSONObject.fromObject(param);
message.setTitle(json.getString("title"));
message.setText(json.getString("text"));
if (param.contains("picUrl")){
message.setPicUrl(json.getString("picUrl"));
}
message.setMessageUrl(json.getString("messageUrl"));
String webhock = json.getString("webhock");
dingtalkChatbotClient.send(webhock,message);
logger.info("发送成功!sendLinkMessage");
} catch (Exception e) {
throw new BizException("数据填写有误!",1);
}
}
public void sendMarkdownMessage(String param){
try {
MarkdownMessage message = new MarkdownMessage();
JSONObject json = JSONObject.fromObject(param);
message.setTitle(json.getString("title"));
message.add(json.getString("text"));
String webhock = json.getString("webhock");
dingtalkChatbotClient.send(webhock,message);
logger.info("发送成功!sendMarkdownMessage");
} catch (Exception e) {
throw new BizException("数据填写有误!",1);
}
}
public void sendActionCardMessage(String param){
try {
SingleTargetActionCardMessage message = new SingleTargetActionCardMessage();
JSONObject json = JSONObject.fromObject(param);
String webhock = json.getString("webhock");
message.setTitle(json.getString("title"));
message.setHideAvatar(json.getString("hideAvatar").equals("0")?false:true);
message.setBriefText(json.getString("text"));
message.setSingleTitle(json.getString("singleTitle"));
message.setSingleURL(json.getString("singleURL"));
dingtalkChatbotClient.send(webhock,message);
logger.info("发送成功!sendActionCardMessage");
} catch (Exception e) {
throw new BizException("数据填写有误!",1);
}
}
public void sendFeedCardMessage(String param){
try {
FeedCardMessage message = new FeedCardMessage();
List<FeedCardMessageItem> items = new ArrayList<FeedCardMessageItem>();
JSONObject json = JSONObject.fromObject(param);
String webhock = json.getString("webhock");
JSONArray array = JSONArray.fromObject(json.getString("links"));
for (int i = 0; i <array.size() ; i++) {
FeedCardMessageItem item1 = new FeedCardMessageItem();
JSONObject jsonObject = array.getJSONObject(i);
item1.setTitle(jsonObject.getString("title"));
item1.setPicURL(jsonObject.getString("picURL"));
item1.setMessageURL(jsonObject.getString("messageURL"));
items.add(item1);
}
message.setFeedItems(items);
dingtalkChatbotClient.send(webhock,message);
logger.info("发送成功!sendFeedCardMessage");
} catch (Exception e) {
throw new BizException("数据填写有误!",1);
}
}
}
这段代码放在定时调度任务里面,在后台用cron表达式配置就好。
SendResult
package io.renren.modules.robot.entity;
import com.alibaba.fastjson.JSON;
import java.util.HashMap;
import java.util.Map;
/**
* @author lanxinghua
* @date 2018/08/04 14:40
* @description
*/
public class SendResult {
private boolean isSuccess;
private Integer errorCode;
private String errorMsg;
public SendResult(){
this.isSuccess=false;
this.errorCode=0;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
public Integer getErrorCode() {
return errorCode;
}
public void setErrorCode(Integer errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public String toString() {
Map<String,Object> items = new HashMap<>();
items.put("errorCode",errorCode);
items.put("errorMsg",errorMsg);
items.put("isSuccess",isSuccess);
return JSON.toJSONString(items);
}
}
消息类型
package io.renren.modules.robot.message;
/**
* Created by dustin on 2017/3/17.
*/
public interface Message {
/**
* 返回消息的Json格式字符串
*
* @return 消息的Json格式字符串
*/
String toJsonString();
}
package io.renren.modules.robot.message;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dustin on 2017/3/17.
*/
public class TextMessage implements Message {
private String text;
private List<String> atMobiles;
private boolean isAtAll;
public TextMessage(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<String> getAtMobiles() {
return atMobiles;
}
public void setAtMobiles(List<String> atMobiles) {
this.atMobiles = atMobiles;
}
public boolean isAtAll() {
return isAtAll;
}
public void setIsAtAll(boolean isAtAll) {
this.isAtAll = isAtAll;
}
public String toJsonString() {
Map<String, Object> items = new HashMap<String, Object>();
items.put("msgtype", "text");
Map<String, String> textContent = new HashMap<String, String>();
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException("text should not be blank");
}
textContent.put("content", text);
items.put("text", textContent);
Map<String, Object> atItems = new HashMap<String, Object>();
if (atMobiles != null && !atMobiles.isEmpty()) {
atItems.put("atMobiles", atMobiles);
}
if (isAtAll) {
atItems.put("isAtAll", isAtAll);
}
items.put("at", atItems);
return JSON.toJSONString(items);
}
}
package io.renren.modules.robot.message;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dustin on 2017/3/18.
*/
public class LinkMessage implements Message {
private String title;
private String text;
private String picUrl;
private String messageUrl;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getMessageUrl() {
return messageUrl;
}
public void setMessageUrl(String messageUrl) {
this.messageUrl = messageUrl;
}
public String toJsonString() {
Map<String, Object> items = new HashMap<String, Object>();
items.put("msgtype", "link");
Map<String, String> linkContent = new HashMap<String, String>();
if (StringUtils.isBlank(title)) {
throw new IllegalArgumentException("title should not be blank");
}
linkContent.put("title", title);
if (StringUtils.isBlank(messageUrl)){
throw new IllegalArgumentException("messageUrl should not be blank");
}
linkContent.put("messageUrl", messageUrl);
if (StringUtils.isBlank(text)){
throw new IllegalArgumentException("text should not be blank");
}
linkContent.put("text", text);
if (StringUtils.isNotBlank(picUrl)) {
linkContent.put("picUrl", picUrl);
}
items.put("link", linkContent);
return JSON.toJSONString(items);
}
}
等等等等….
DingtalkChatbotClient
package io.renren.modules.robot.service;
import io.renren.modules.robot.entity.SendResult;
import io.renren.modules.robot.message.Message;
/**
* @author lanxinghua
* @date 2018/08/04 14:48
* @description 钉钉机器人发送消息
*/
public interface DingtalkChatbotClient {
/**
* @param webhook 机器人url
* @param message 发送的消息
* @return
*/
public SendResult send(String webhook, Message message);
}
DingtalkChatbotClientImpl
package io.renren.modules.robot.service.impl;
import com.alibaba.fastjson.JSONObject;
import io.renren.modules.robot.entity.SendResult;
import io.renren.modules.robot.message.Message;
import io.renren.modules.robot.service.DingtalkChatbotClient;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
/**
* @author lanxinghua
* @date 2018/08/04 14:49
* @description
*/
@Service
public class DingtalkChatbotClientImpl implements DingtalkChatbotClient {
//获取httpclient
private HttpClient getHttpclient() {
return HttpClients.createDefault();
}
@Override
public SendResult send(String webhook, Message message) {
SendResult sendResult = new SendResult();
try {
HttpClient httpclient = getHttpclient();
HttpPost httppost = new HttpPost(webhook);
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = JSONObject.parseObject(result);
Integer errcode = obj.getInteger("errcode");
sendResult.setErrorCode(errcode);
sendResult.setSuccess(errcode.equals(0));
sendResult.setErrorMsg(obj.getString("errmsg"));
}
return sendResult;
} catch (Exception e) {
e.printStackTrace();
}
return sendResult;
}
}