3年前写了个 使用 feilong 发企业微信机器人, 现在姐妹篇 钉钉机器人来了
钉钉和企业微信,不同公司根据自身需求,会做出不同的选择, 并且可能会出现同一家公司, 今年选择了钉钉,可能后年根据战略需求换成了企业微信
钉钉机器人在日常的使用场景中越来越多, 比如服务器关键任务告警,定时发通知提醒等等, 和短信相比即免费又不像短信逐渐只有接收验证码的功能, 那么问题来了,如何使用feilong来发送钉钉机器人呢?
同样简单 3 步
1. 第1步: 依赖jar
依赖 feilong (注意检查不要和项目已有的依赖重复了) 参见 https://www.oschina.net/p/feilong
<dependency>
<groupId>com.github.ifeilong</groupId>
<artifactId>feilong</artifactId>
<version>3.4.1</version>
</dependency>
其他必要依赖 (注意检查不要和项目已有的依赖重复了)
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
<exclusions>
<exclusion>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
2. 第2步: springboot类型的项目,配置bean 机器人
@Configuration
public class DingTalkLogBotConfig{
@Bean("dingTalkLogBot")
public DingTalkBot init(){
return DingTalkBotBuilder.newAsyncCatchExceptionDingTalkBot(
"15096d9da**********2ae19dfedcf23ff", // 此处是 钉钉机器人 accessToken
"SECfcf65c9de********c1cc66c49f",// 此处是 钉钉机器人 安全码 secret
"图书馆小程序"); // 这个是配置的默认机器人标题
}
}
该bean 异步发送消息, 并且如果出现异常自动捕获,不会影响主线程
3. 第3步: 使用
简单小示例:
public class DingTalkBotTest extends AbstractJUnit4SpringContextTests{
@Autowired(required = false)
@Qualifier("dingTalkLogBot")
private DingTalkBot dingTalkBot;
//---------------------------------------------
@Test
public void test(){
dingTalkBot.sendMessage("hello world");
}
}
使用 @Qualifier("dingTalkLogBot") 来指明bean 名字, 支持一个项目配置多个钉钉机器人,做不同的用途
执行这个单元测试, 你将会收到钉钉机器人发的消息
4. 关于 DingTalkBot
com.feilong.net.bot.dingtalk.DingTalkBot 提供了2个易用的方法
-
sendMessage(String) 发送普通消息,以及Markdown格式的消息
-
sendMessage(String, String, String…) 支持@ 指定的人员
4.1. sendMessage(String) 发送普通消息,以及Markdown格式的消息
在上述 hello world示例中, 你可以看到发送简单消息, 也支持markdown格式的消息, 比如
@Test
public void test(){
String content = "## 今晚去喝酒吗😁 \n" + //
"![](https://img.alicdn.com/tfs/TB1bB9QKpzqK1RjSZFoXXbfcXXa-576-96.png) \n" + //
"> 曾经有一段真挚的爱情 \n" + //
"1. 美女 \n" + //
"2. 帅哥 \n" + //
"- **喝酒** \n" + //
"- [百度](http://baidu.com) \n" + //
"- *唱歌* \n";
dingTalkBot.sendMessage(content);
}
效果:
4.2. sendMessage(String, String, String…) 支持@ 指定的人员
content 写法请参考钉钉官方文档
5. Q&A
5.1. Q: 我公司去年是使用钉钉,今年换成了企业微信, 那么项目代码能否不需要大幅度修改?
A: 很好的问题, 下期写个文档回复你 _
--完