Slack 作为一款办公类的 App,相对于其它办公软件来说,我对它提供的功能和用户体验还是比较认可的。今天简单介绍下如何使用 Slack 频道,实现对项目中重要消息的通知。
首先,需要在选择在某一工作空间上 添加 Apps(Slack 允许个人账号加入多个 workspace,类似多租户的概念)
实现 Slack 消息通知的方式主要有两种,分别是回调地址和访问令牌
一、回调地址
- 生成 webhook url
添加一个 webhook 到工作空间,这里选择了要将消息发送到哪个频道后,会生成一个专属于这个频道的 url
- 发送消息
@Slf4j
@Component
public class SlackService {
@Value("${spring.profiles.active}")
private String env;
@Value("${slack.webhook-url}")
private String webhookUrl;
@Resource
private RestTemplate restTemplate;
@Async
public void sendMsg(String content) {
String param = JsonUtil.object2Json(ImmutableMap.of("text", String.format("[%s] %s", env, content)));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(param, headers);
try {
restTemplate.postForEntity(webhookUrl, entity, String.class);
} catch (Exception e) {
log.error("Slack send message error", e);
}
}
}
二、访问令牌
-
设置 scopes 这里配置的是 “write.public”,所以可以往该工作空间下的任意频道发送。
如果只希望发送到某一频道则可以选择其它的 scope,另外在频道中添加该应用(实现方式很多种,过程随意)
-
生成 token 这里生成的 token,就是后边通过这个应用往频道发送消息的凭证
-
发送消息
跟方法一类似,一个是指定 url,一个是携带 token,不再赘述