当前位置:   article > 正文

Java 飞书机器人消息发送(简单demo)_java飞书机器人发消息

java飞书机器人发消息

w引入pom

  1. <dependency>
  2. <groupId>com.larksuite.oapi</groupId>
  3. <artifactId>oapi-sdk</artifactId>
  4. <version>2.1.3</version>
  5. </dependency>

controller

  1. public Result<?> sendTextByGroupRobots() {
  2. feiShuNotifyRequest.sendTextByGroupRobots(FeiShuConfig.WEB_HOOK_URL,"牛爷爷吃饭");
  3. return Result.OK();
  4. }
  5. public Result<?> sendTextAboutUserByGroupRobots() {
  6. feiShuNotifyRequest.sendTextAboutUserByGroupRobots(FeiShuConfig.WEB_HOOK_URL,"牛爷爷打游戏","ou_b406xxxxxxxxxxx221630");
  7. return Result.OK();
  8. }
  9. public Result<?> sendRichTextByGroupRobots() {
  10. feiShuNotifyRequest.sendRichTextByGroupRobots(FeiShuConfig.WEB_HOOK_URL,"牛爷爷看电影","https://xxxxxxxxxxxxxxxxxxC0nVg","ou_b4xxxxxxxxxxxxx30");
  11. return Result.OK();
  12. }
  13. public Result<?> sendMessageToUser() {
  14. feiShuNotifyRequest.sendMessageToUser("ou_bxxxxxxxxxxxxxxxxxxx30","强壮的牛爷爷下班啦");
  15. return Result.OK();
  16. }
  17. public Result<?> sendImage() {
  18. SendImageRequest request = new SendImageRequest();
  19. try {
  20. feiShuNotifyRequest.sendImage(request);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. return Result.OK();
  25. }
  26. public Result<?> sendFile() {
  27. SendFileRequest request = new SendFileRequest();
  28. request.setFileType("xlsx");
  29. request.setFileName("demo.xlsx");
  30. request.setFile(new File("D:\\demo.xlsx"));
  31. request.setReceiveIdType("open_id");
  32. request.setReceiveId("ou_b4xxxxxxxxxxxxxxxxxxxxx1630");
  33. try {
  34. feiShuNotifyRequest.sendFile(request);
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. }
  38. return Result.OK();
  39. }
  40. public Result<?> sendFilePdf() {
  41. SendFileRequest request = new SendFileRequest();
  42. request.setFileType("pdf");
  43. request.setFileName("高并发解决方案回答.pdf");
  44. request.setFile(new File("E:\\高并发解决方案回答.pdf"));
  45. request.setReceiveIdType("open_id");
  46. request.setReceiveId("ou_b4xxxxxxxxxxxxxxxxxxxx1630");
  47. try {
  48. feiShuNotifyRequest.sendFile(request);
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. return Result.OK();
  53. }
  1. /**
  2. * @author Sherry
  3. * @description 文本消息
  4. */
  5. @Data
  6. @Service
  7. public class FeiShuTextNotifyRequest implements FeiShuNotifyRequest {
  8. private static final Client client = Client.newBuilder(FeiShuConfig.APP_ID, FeiShuConfig.APP_SECRET).build();
  9. @Override
  10. public void sendTextByGroupRobots(String webhookUrl,String data) {
  11. //请求的JSON数据,这里用map在工具类里转成json格式
  12. JSONObject json=new JSONObject();
  13. JSONObject text=new JSONObject();
  14. json.put("msg_type", "text");
  15. text.put("text", "项目告警通知:" + data);
  16. json.put("content", text);
  17. String result = HttpRequest.post(webhookUrl).body(JSONObject.toJSONString(json), "application/json;charset=UTF-8").execute().body();
  18. System.out.println(result);
  19. }
  20. @Override
  21. public void sendTextAboutUserByGroupRobots(String webhookUrl, String data, String userOpenId) {
  22. JSONObject json=new JSONObject();
  23. json.put("msg_type", "text");
  24. json.put("content", "{\"text\":\"<at user_id=\\\""+ userOpenId +"\\\"></at> "+data+"\"}");
  25. String result = HttpRequest.post(webhookUrl).body(JSONObject.toJSONString(json), "application/json;charset=UTF-8").execute().body();
  26. }
  27. @Override
  28. public void sendRichTextByGroupRobots(String webhookUrl, String data, String href, String userOpenId) {
  29. RichText richText = new RichText();
  30. richText.setMsg_type("post");
  31. JSONObject postJson = new JSONObject();
  32. JSONArray content = new JSONArray();
  33. JSONArray contentArray = new JSONArray();
  34. JSONObject urlJson = new JSONObject();
  35. urlJson.put("tag", "a");
  36. urlJson.put("text","请查看");
  37. urlJson.put("href", href);
  38. contentArray.add(urlJson);
  39. JSONObject userJson = new JSONObject();
  40. userJson.put("tag", "at");
  41. userJson.put("user_id", userOpenId);
  42. contentArray.add(userJson);
  43. content.add(contentArray);
  44. HashMap<String, Object> title = new HashMap<>();
  45. JSONObject contentJson = new JSONObject();
  46. contentJson.put("title", data);
  47. contentJson.put("content", content);
  48. JSONObject zhCnJson = new JSONObject();
  49. zhCnJson.put("zh_cn", contentJson);
  50. postJson.put("post",zhCnJson);
  51. richText.setContent(postJson);
  52. String result = HttpRequest.post(webhookUrl).body(JSONObject.toJSONString(richText), "application/json;charset=UTF-8").execute().body();
  53. }
  54. @Override
  55. public void sendMessageToUser(String userOpenId,String message){
  56. // 创建请求对象
  57. CreateMessageReq req = CreateMessageReq.newBuilder()
  58. .receiveIdType("open_id")
  59. .createMessageReqBody(CreateMessageReqBody.newBuilder()
  60. .receiveId(userOpenId)
  61. .msgType("text")
  62. .content("{\"text\":\" "+message+"\"}")
  63. .uuid(UUIDGenerator.generate())
  64. .build())
  65. .build();
  66. // 发起请求
  67. CreateMessageResp resp = null;
  68. try {
  69. resp = client.im().message().create(req);
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. // 处理服务端错误
  74. if(!resp.success()) {
  75. System.out.println(String.format("code:%s,msg:%s,reqId:%s", resp.getCode(), resp.getMsg(), resp.getRequestId()));
  76. return;
  77. }
  78. // 业务数据处理
  79. System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
  80. }
  81. /**
  82. * 发送图片消息,使用到两个OpenAPI:
  83. * 1. [上传图片](<a href="https://open.feishu.cn/document/server-docs/im-v1/image/create">...</a>)
  84. * 2. [发送消息](<a href="https://open.feishu.cn/document/server-docs/im-v1/message/create">...</a>)
  85. */
  86. @Override
  87. public BaseResponse<?> sendImage(SendImageRequest request) throws Exception {
  88. request.setImage(new File("C:/Users/jhf/Pictures/Camera Roll/emo.jpg"));
  89. request.setReceiveIdType("open_id");
  90. request.setReceiveId("ou_b40xxxxxxxxxxxxxxxxxxxx21630");
  91. // 上传图片
  92. CreateImageReq req = CreateImageReq.newBuilder()
  93. .createImageReqBody(CreateImageReqBody.newBuilder()
  94. .imageType("message")
  95. .image(request.getImage())
  96. .build())
  97. .build();
  98. CreateImageResp createImageResp = client.im().image().create(req);
  99. System.out.println(createImageResp);
  100. if (!createImageResp.success()) {
  101. System.out.printf("client.im.image.create failed, code: %d, msg: %s, logId: %s%n",
  102. createImageResp.getCode(), createImageResp.getMsg(), createImageResp.getRequestId());
  103. return createImageResp;
  104. }
  105. // 发送消息
  106. CreateMessageReq createMessageReq = CreateMessageReq.newBuilder()
  107. .receiveIdType(request.getReceiveIdType())
  108. .createMessageReqBody(CreateMessageReqBody.newBuilder()
  109. .receiveId(request.getReceiveId())
  110. .msgType("image")
  111. .content(Jsons.DEFAULT.toJson(createImageResp.getData()))
  112. .uuid(request.getUuid())
  113. .build())
  114. .build();
  115. CreateMessageResp createMessageResp = client.im().message().create(createMessageReq);
  116. if (!createMessageResp.success()) {
  117. System.out.printf("client.im.message.create failed, code: %d, msg: %s, logId: %s%n",
  118. createMessageResp.getCode(), createMessageResp.getMsg(), createMessageResp.getRequestId());
  119. return createMessageResp;
  120. }
  121. // 返回结果
  122. SendImageResponse response = new SendImageResponse();
  123. response.setCode(0);
  124. response.setMsg("success");
  125. response.setCreateImageResponse(createImageResp.getData());
  126. response.setCreateMessageResponse(createMessageResp.getData());
  127. return response;
  128. }
  129. @Override
  130. public BaseResponse<?> sendFile(SendFileRequest request) throws Exception {
  131. // 上传文件
  132. CreateFileReq createFileReq = CreateFileReq.newBuilder()
  133. .createFileReqBody(CreateFileReqBody.newBuilder()
  134. .fileType(request.getFileType())
  135. .fileName(request.getFileName())
  136. .duration(request.getDuration())
  137. .file(request.getFile())
  138. .build())
  139. .build();
  140. CreateFileResp createFileResp = client.im().file().create(createFileReq);
  141. if (!createFileResp.success()) {
  142. System.out.printf("client.im.file.create failed, code: %d, msg: %s, logId: %s%n",
  143. createFileResp.getCode(), createFileResp.getMsg(), createFileResp.getRequestId());
  144. return createFileResp;
  145. }
  146. // 发送消息
  147. CreateMessageReq createMessageReq = CreateMessageReq.newBuilder()
  148. .receiveIdType(request.getReceiveIdType())
  149. .createMessageReqBody(CreateMessageReqBody.newBuilder()
  150. .receiveId(request.getReceiveId())
  151. .msgType("file")
  152. .content(Jsons.DEFAULT.toJson(createFileResp.getData()))
  153. .uuid(request.getUuid())
  154. .build())
  155. .build();
  156. CreateMessageResp createMessageResp = client.im().message().create(createMessageReq);
  157. if (!createMessageResp.success()) {
  158. System.out.printf("client.im.message.create failed, code: %d, msg: %s, logId: %s%n",
  159. createMessageResp.getCode(), createMessageResp.getMsg(), createMessageResp.getRequestId());
  160. return createMessageResp;
  161. }
  162. // 返回结果
  163. SendFileResponse response = new SendFileResponse();
  164. response.setCode(0);
  165. response.setMsg("success");
  166. response.setCreateFileResponse(createFileResp.getData());
  167. response.setCreateMessageResponse(createMessageResp.getData());
  168. return response;
  169. }
  170. @Override
  171. public void sendWarnMessage(String userOpenId, String msgType, String content) throws Exception {
  172. CreateMessageReq req = CreateMessageReq.newBuilder()
  173. .receiveIdType("open_id")
  174. .createMessageReqBody(CreateMessageReqBody.newBuilder()
  175. .receiveId(userOpenId)
  176. .msgType(msgType)
  177. .content(BuildCard())
  178. .build())
  179. .build();
  180. CreateMessageResp resp = client.im().message().create(req);
  181. if (!resp.success()) {
  182. throw new Exception(String.format("client.im.message.create failed, code: %d, msg: %s, logId: %s",
  183. resp.getCode(), resp.getMsg(), resp.getRequestId()));
  184. }
  185. }
  186. // 构建卡片
  187. public static String BuildCard() throws Exception {
  188. // 获取卡片结构
  189. File jsonFile = new File("E:\\Coding\\xxxxxxxxxxxxxxxxx\\card\\card.json");
  190. FileReader fileReader = new FileReader(jsonFile);
  191. Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
  192. int ch = 0;
  193. StringBuilder sb = new StringBuilder();
  194. while ((ch = reader.read()) != -1) {
  195. sb.append((char) ch);
  196. }
  197. fileReader.close();
  198. reader.close();
  199. String card = sb.toString();
  200. return card;
  201. }
  202. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/782288
推荐阅读
相关标签
  

闽ICP备14008679号