Springboot整合飞书向群组/指定个人发送消息/飞书登录
在Spring Boot中整合飞书发送消息,你需要使用飞书开放平台提供的API。以下是一个简化的例子,展示如何使用Spring Boot发送消息到群组或指定人。
- 首先,需要在飞书开放平台注册应用,获取
access_token
。 - 使用
access_token
调用飞书提供的API发送消息。
以下是Spring Boot整合飞书发送消息的示例代码:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class FeishuService {
@Value("${feishu.bot.url}")
private String botUrl;
private final RestTemplate restTemplate;
public FeishuService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void sendMessageToGroup(String groupId, String message) {
String url = String.format("%s/message/v4/send-group", botUrl);
// 构建消息体
Map<String, Object> body = new HashMap<>();
body.put("group_id", groupId);
body.put("msg_type", "text");
body.put("content", Collections.singletonMap("text", message));
// 发送POST请求
restTemplate.postForObject(url, body, Void.class);
}
public void sendMessageToPerson(String userId, String message) {
String url = String.format("%s/message/v4/send-user", botUrl);
// 构建消息体
Map<String, Object> body = new HashMap<>();
body.put("user_id", userId);
body.put("msg_type", "text");
body.put("content", Collections.singletonMap("text", message));
// 发送POST请求
restTemplate.postForObject(url, body, Void.class);
}
}
在这个例子中,sendMessageToGroup
方法用于向群组发送文本消息,而sendMessageToPerson
方法用于向个人发送文本消息。你需要替换feishu.bot.url
为你的飞书机器人URL,并确保你已经获取了有效的access_token
。
注意:实际使用时,需要处理API的返回值和异常,并确保正确处理access token的更新。
在Spring Boot的配置文件中,你需要配置好RestTemplate
以及相关的URL和access token:
feishu:
bot:
url: https://open.feishu.cn/open-apis/bot/v1
access-token: your_access_token_here
并配置RestTemplate
的Bean:
@Configuration
public class FeishuConfig {
@Value("${feishu.bot.access-token}")
private String accessToken;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
// 可以添加拦截器以在请求时自动添加access token
}
使用FeishuService
发送消息:
@RestController
public class MessageController {
private final FeishuService feishuService;
pu
评论已关闭