SpringBoot对接钉钉群机器人

1.获取到机器人的webhook以及密钥

2.在springboot中添加相应的依赖

<dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.15</version> <!-- 请根据需要使用最新的版本 -->
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibaba-dingtalk-service-sdk</artifactId>
            <version>1.0.1</version>
        </dependency>

3.编写钉钉客户端工具类(这里要写你的机器人的webhook 和 密钥)

@Component
public class DingDing {
    public void sendMessage(String message) throws ApiException {
        String getKey = getKey();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=webhook" + getKey + "");
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        //发送消息的类型
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(message);
        request.setText(text);
        //通过手机号@群员
//        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//        at.setAtMobiles(Collections.singletonList("***"));

        client.execute(request);

    }

    @SneakyThrows
    public static String getKey() {

        Long timestamp = System.currentTimeMillis();
        String secret = "密钥";
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        System.out.println(sign);
        return "&timestamp=" + timestamp + "&sign=" + sign + "";
    }
}

4.controller层

@RestController
@RequestMapping("/dingding")
public class DingDingController {

    @Resource
    private TestService testService;

    @GetMapping("/test")
    public String test() throws ApiException {
        return testService.test();
    }

}

5.service层

public interface TestService {

    public String test() throws ApiException;

}

6.业务实现层

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private DingDing dingDing;

    @Override
    public String test() throws ApiException {
        String message="helloword";
        try {
            dingDing.sendMessage(message);
        }catch (Exception e){
            return "发送失败";
        }
        return "发送成功!";
    }
    
}

最后运行成功!

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值