Java开发企业微信群机器人发送markdown消息
Java开发企业微信群机器人发送markdown消息
- 企业微信群机器人配置
- 使用Java发送markdown消息
- 消息应答结果实体
- 核心代码
- 完整Java工具类
- 完整Java工具类
- Demo01
- Demo02
- sendMarkdown 简化
企业微信群机器人配置
参考网址
- 群机器人配置说明
- 发送应用消息
使用Java发送markdown消息
注意: 本代码仅依赖 com.google.gson.Gson , 其他均JDK1.8原生类.
消息应答结果实体
/*** 企业微信群机器人发送消息应答结果.<br>*/
public final class WeComRobotResponse {private int errcode;private String errmsg;public int getErrcode() {return errcode;}public void setErrcode(int errcode) {this.errcode = errcode;}public String getErrmsg() {return errmsg;}public void setErrmsg(String errmsg) {this.errmsg = errmsg;}
}
核心代码
/*** 发送相应的Markdown内容到对应key的机器人.* * @param key 机器人key* @param markdown Markdown内容* @return*/
public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {if (markdown.isEmpty()) {return null;}/** 拼接数据, 格式: {'msgtype': 'markdown', 'markdown': {'content': 'Markdown实际内容.'}} */Map<String, String> data = new HashMap<>();data.put("content", markdown);Map<String, Object> json = new HashMap<>();json.put("msgtype", "markdown");json.put("markdown", data);byte[] bytes = new Gson().toJson(json).getBytes(StandardCharsets.UTF_8);// 创建链接HttpURLConnection httpConnection = null;try {URL url = new URL(String.format(TARGET_URL, Optional.ofNullable(key).orElseGet(() -> defaultKey)));httpConnection = HttpURLConnection.class.cast(url.openConnection());httpConnection.setRequestMethod("POST");httpConnection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");httpConnection.setRequestProperty("Accept", "application/json");httpConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));httpConnection.setDoInput(true);httpConnection.setDoOutput(true);httpConnection.setUseCaches(false);httpConnection.connect();} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 推送数据try (OutputStream out = httpConnection.getOutputStream();) {out.write(bytes);out.flush();} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 请求失败try {if (200 != httpConnection.getResponseCode()) {return null;}} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 接收数据String response = null;try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1 << 5); InputStream isr = httpConnection.getInputStream();) {byte[] buffer = new byte[512];int n = 0;while ((n = isr.read(buffer)) >= 0) {baos.write(buffer, 0, n);}response = new String(baos.toByteArray(), StandardCharsets.UTF_8);} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 断开连接httpConnection.disconnect();LOGGER.info("We Com Send Message State :: {}", response);return new Gson().fromJson(response, WeComRobotResponse.class);
}
完整Java工具类
完整Java工具类
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;import javax.annotation.Nonnull;
import javax.annotation.Nullable;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;import com.google.gson.Gson;/*** 企业微信群机器人发送消息.<br>* * demo01:<br>* <blockquote>* * <pre>* @org.springframework.beans.factory.annotation.Autowired* private WeComRobotUtils wecomRobot;* ......* String markdown = WeComRobotUtils.Markdown.of("运维中心告警预告")* .addProp("名称", "主机阈值越界", "red")* .addProp("主机", "localhost-01.local")* .addProp("时间", LocalDateTime.now().toString(), "#027e7e")* .setFooter("请尽快处理.")* .toString();* wecomRobot.sendMarkdown(markdown); 或 wecomRobot.sendMarkdownAndCheck(markdown);* 或者* String key = "......";* wecomRobot.sendMarkdown(key, markdown); 或 wecomRobot.sendMarkdownAndCheck(key, markdown);* ......* </pre>* * </blockquote>* <p>* demo02:<br>* <blockquote>* * <pre>* @org.springframework.beans.factory.annotation.Autowired* private WeComRobotUtils wecomRobot;* ......* String markdown = "运维中心告警预告:\n\n>名称: 主机阈值越界\n主机: <font color='red'>localhost-01.local</font>\n\n请尽快处理.";* wecomRobot.sendMarkdown(markdown); 或 wecomRobot.sendMarkdownAndCheck(markdown);* 或者* String key = "......";* wecomRobot.sendMarkdown(key, markdown); 或 wecomRobot.sendMarkdownAndCheck(key, markdown);* ......* </pre>* * </blockquote>*/
@Order(value = Integer.MIN_VALUE)
@Component
public class WeComRobotUtils {private static final Logger LOGGER = LoggerFactory.getLogger(WeComRobotUtils.class);private static final String TARGET_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s";@Value(value = "${wecom.robot.key:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}")private String defaultKey;/*** 企业微信群机器人发送消息构造工具.<br>* 格式如下:<br>* <code>* ${title}:<br>* > props[0].label: <font color='props[0].color'>props[0].value</font><br>* > props[1].label: <font color='props[1].color'>props[1].value</font><br>* > props[2].label: <font color='props[2].color'>props[2].value</font><br>* > ......<br>* ${footer}:<br>* </code>*/public static final class Markdown {private static final String PROPS_FORMAT = "> %s: <font color='%s'>%s</font>\n";private String title;private List<ColorValue> props = new ArrayList<>(1 << 5);private String footer;private static final class ColorValue {private String label;private String value;private String color;public static final ColorValue of(final String label, final String value) {return new ColorValue(label, value, "#747474");}public static final ColorValue of(final String label, final String value, final String color) {return new ColorValue(label, value, color);}private ColorValue(String label, String value, String color) {this.label = label;this.value = value;this.color = color;}public String getLabel() {return label;}public String getValue() {return value;}public String getColor() {return color;}}public static final Markdown of(final String title) {return new Markdown(title);}public Markdown(String title) {this.title = title;}public String getTitle() {return title;}public List<ColorValue> getProps() {return props;}public String getFooter() {return footer;}public Markdown setFooter(final String footer) {this.footer = footer;return this;}public Markdown addProp(final String label, final String value) {this.getProps().add(ColorValue.of(label, value));return this;}public Markdown addProp(final String label, final String value, final String color) {this.getProps().add(ColorValue.of(label, value, color));return this;}@Overridepublic String toString() {StringBuilder out = new StringBuilder(1 << 8);out.append(this.getTitle()).append(":").append("\n\n"); // 标题this.getProps().forEach(item -> out.append(String.format(PROPS_FORMAT, item.getLabel(), item.getColor(), item.getValue())));out.append("\n").append(Optional.ofNullable(this.getFooter()).orElseGet(() -> "")); // 结尾return out.toString();}}/*** 企业微信群机器人发送消息应答结果.<br>*/public final class WeComRobotResponse {private int errcode;private String errmsg;public int getErrcode() {return errcode;}public void setErrcode(int errcode) {this.errcode = errcode;}public String getErrmsg() {return errmsg;}public void setErrmsg(String errmsg) {this.errmsg = errmsg;}}/*** 发送相应的Markdown内容到默认key的机器人, 并做校验.* * @param markdown Markdown内容* @return*/public final boolean sendMarkdownAndCheck(@Nonnull final String markdown) {return WeComRobotUtils.isOk(this.sendMarkdown(defaultKey, markdown));}/*** 发送相应的Markdown内容到对应key的机器人, 并做校验.* * @param key 机器人key* @param markdown Markdown内容* @return*/public final boolean sendMarkdownAndCheck(@Nullable final String key, @Nonnull final String markdown) {return WeComRobotUtils.isOk(this.sendMarkdown(key, markdown));}/*** 发送相应的Markdown内容到默认key的机器人.* * @param markdown Markdown内容* @return*/public final WeComRobotResponse sendMarkdown(@Nonnull final String markdown) {return this.sendMarkdown(defaultKey, markdown);}/*** 发送相应的Markdown内容到对应key的机器人.* * @param key 机器人key* @param markdown Markdown内容* @return*/public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {if (markdown.isEmpty()) {return null;}/** 拼接数据, 格式: {'msgtype': 'markdown', 'markdown': {'content': 'Markdown实际内容.'}} */Map<String, String> data = new HashMap<>();data.put("content", markdown);Map<String, Object> json = new HashMap<>();json.put("msgtype", "markdown");json.put("markdown", data);byte[] bytes = new Gson().toJson(json).getBytes(StandardCharsets.UTF_8);// 创建链接HttpURLConnection httpConnection = null;try {URL url = new URL(String.format(TARGET_URL, Optional.ofNullable(key).orElseGet(() -> defaultKey)));httpConnection = HttpURLConnection.class.cast(url.openConnection());httpConnection.setRequestMethod("POST");httpConnection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");httpConnection.setRequestProperty("Accept", "application/json");httpConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));httpConnection.setDoInput(true);httpConnection.setDoOutput(true);httpConnection.setUseCaches(false);httpConnection.connect();} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 推送数据try (OutputStream out = httpConnection.getOutputStream();) {out.write(bytes);out.flush();} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 请求失败try {if (200 != httpConnection.getResponseCode()) {return null;}} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 接收数据String response = null;try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1 << 5); InputStream isr = httpConnection.getInputStream();) {byte[] buffer = new byte[512];int n = 0;while ((n = isr.read(buffer)) >= 0) {baos.write(buffer, 0, n);}response = new String(baos.toByteArray(), StandardCharsets.UTF_8);} catch (IOException e) {LOGGER.error(e.getClass().getName(), e);return null;}// 断开连接httpConnection.disconnect();LOGGER.info("We Com Send Message State :: {}", response);return new Gson().fromJson(response, WeComRobotResponse.class);}/*** 判断发送是否成功.<br>* 成功 :: true<br>* 失败 :: false<br>* * @param res 发送结果* @return*/public static final boolean isOk(WeComRobotResponse res) {return Objects.nonNull(res) && 0 == res.getErrcode();}
}
Demo01
@org.springframework.beans.factory.annotation.Autowired
private WeComRobotUtils wecomRobot;
......
String markdown = WeComRobotUtils.Markdown.of("Markdown标题").addProp("Label01", "Label01-Value", "red").addProp("Label02", "Label02-Value").addProp("时间", LocalDateTime.now().toString(), "#027e7e").setFooter("请尽快处理.").toString();
wecomRobot.sendMarkdown(markdown); 或 wecomRobot.sendMarkdownAndCheck(markdown);
或者
String key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
wecomRobot.sendMarkdown(key, markdown); 或 wecomRobot.sendMarkdownAndCheck(key, markdown);
Demo02
@org.springframework.beans.factory.annotation.Autowired
private WeComRobotUtils wecomRobot;
......
String markdown = "Markdown标题:\n\n>Label01: Label01-Value\nLabel02: <font color='red'>Label02-Value</font>\n\n请尽快处理.";
wecomRobot.sendMarkdown(markdown); 或 wecomRobot.sendMarkdownAndCheck(markdown);
或者
String key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
wecomRobot.sendMarkdown(key, markdown); 或 wecomRobot.sendMarkdownAndCheck(key, markdown);
......
sendMarkdown 简化
import org.springframework.web.client.RestTemplate;public final WeComRobotResponse sendMarkdown(@Nullable final String key, @Nonnull final String markdown) {/** 拼接数据, 格式: {'msgtype': 'markdown', 'markdown': {'content': 'Markdown实际内容.'}} */Map<String, String> data = new HashMap<>();data.put("content", markdown);Map<String, Object> json = new HashMap<>();json.put("msgtype", "markdown");json.put("markdown", data);String url = String.format(TARGET_URL, Optional.ofNullable(key).orElseGet(() -> defaultKey));return new RestTemplate().postForEntity(url, json, WeComRobotResponse.class).getBody();
}
请多多指教
Java开发企业微信群机器人发送markdown消息相关推荐
- (Java)微信公众号发送模板消息
模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等.不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息. 1.模板消息调用时主要 ...
- JAVA连接微信服务号发送模板消息
最近因为业务需要使用微信服务号推送模板消息,所以就研究了下,在这也回顾和总结下开发流程和注意事项. 1. 微信公众号推送模板消息,需要开通服务号并且需要进行微信认证(这点就不过多记录了).申请到服务号 ...
- Python企业微信群机器人推送消息,定时提醒。
import time import schedule import datetime from WorkWeixinRobot.work_weixin_robot import WWXRobotww ...
- 企业微信群机器人是什么?企微机器人如何自动发消息?
经常有很多用户会问我们,企业微信群机器人是什么,有什么用,有什么限制?企业微信群机器人提供的是一个webhook消息,如何可以通过这个来自动发消息呢?之前写过一些关于企业微信群机器人如何发消息的教程, ...
- 企业微信机器人脚本python_Python 操控企业微信群机器人
目标 企业微信群机器人常用来作为通知工具,群发消息给群内成员,充当小助手的角色.但若按照官方 API 文档来构建请求,也确实不太方便.本文通过 Python 第三方库来控制企业微信群机器人发送消息. ...
- 工作随记-Java利用企业微信群机器人定时发送消息
hi,大家好,我是恰恰 阅读本文需要2分钟~ 最近利用企业微信群机器人做的需求主要有 1.返奖率通知与告警:抽奖箱能抽出垃圾也能抽出大货,每隔5分钟查询一下这个返奖率,如果用户频繁抽出大货,这个抽奖箱 ...
- 【AIO】使用ORACLE数据库存储过程发送企业微信群机器人消息
前言 为了对标阿里系的钉钉,腾讯于2016年4月18日推出了企业微信 专注企业内部通讯(目前已加入客户管理及客户通讯功能),替代原有的RTX腾讯通 企业微信由于微信的生态及其易用性,已被很多企业使用, ...
- java实现如何定时给微信群中发送消息
大家好,我是雄雄. 前言 前几天,发了一个系列这样的文章,如下所示: java实现每日给女友微信发送早安等微信信息 java实现给微信群中定时推送消息 如何将每日新闻添加到自己博客中,发送到微信群中 ...
- python 在企业微信通过群机器人发送消息
1.在企业微信新建一个群,最开始最好只加入自己,方便测试,以免影响他人 在企业微信群昵称处右键鼠标,选择添加群机器人-添加群机器人-新创建一个机器人,如下图所示: 2.添加完群机器人之后,在群的联系人 ...
- MeterSphere实现“机器人定时在企业微信群中发送消息”功能
背景 之前有过用PowerShell实现"机器人定时在企业微信群中发送消息"功能,并有输出相关教程. 但发现有一些问题:比如电脑关机了导致任务不能如期启动,于是在摸索中找到可替代P ...
最新文章
- spring aop代码的增强
- 利用Proceesson在线绘制流程图实例演练!流程图的要点和注意事项说明
- zookeeper设置临时节点失效时间_ZooKeeper 相关概念以及使用小结
- python面向对象(part1)--类和对象
- leetcode力扣338. 比特位计数
- python捕捉warning_python – 如何格式化logging.captureWarnings捕获的警告?
- winform调用websocket_C#基于websocket的前台及后台实时推送
- linux 清除mysql relay_MySQL 小版本升级
- 帆软超级链接使用(根据内容跳转不同页面、超级链接使用js并传参、超级链接参数传递)
- iis设置开启GZIP网页压缩功能
- 全闪存存储的VDI场景应用
- MT8735芯片技术资料解析,MT8735处理器简介
- 穿山甲广告切后台点Icon进入后广告消失或游戏重启的解决方法
- 【2022年对话机器人chatbot】SaleSmartly如何解决客服难题
- 用户来了留不住? 5个方法,帮你提高产品黏性和用户“回头率”
- Vue状态管理--Pinia使用详解
- netty-Android-RN等博文收藏
- AJAX的教程(一)
- MOS管和电机驱动(一):MOS管的栅极电阻和GS电阻 米勒效应与米勒平台
- 哈佛梅森学者:数字加密货币的泡沫与机遇|万字长文干货
热门文章
- 使用fisheye4.8(crucible4.8)添加仓库时出现的问题
- Python获取逐浪小说内容
- 张开翅膀,放飞梦想,让光彩无限绽放!
- 从一杯果汁浅谈点点医生充值提现模块设计
- 接口测试用例设计:常见问题和风险
- 计算机系统引导失败怎么办,win7系统引导选择失败怎么办|win7系统引导选择失败的解决方法...
- 软路由Linux7,CentOS 7 NAT软路由
- 用Python实现中文编程
- 2017-07-07 2,3,5,7倍数
- window无法访问此文件夹,请确保输入的文件名是正确的,并且您有权访问此文件夹