如何使用釘釘群機器人給釘釘群傳送訊息

梦回大唐meng發表於2024-07-16

釘釘群新增自定義機器人

群內新增自定義機器人,從自定義配置中獲取到secret以及accessToken

程式碼呼叫

		Long timestamp = System.currentTimeMillis();
        String secret = "secret";
        String accessToken = "accessToken";
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("https://oapi.dingtalk.com/robot/send?access_token=").append(accessToken);
        //stringBuffer.append("&timestamp=").append(timestamp);
        // stringBuffer.append("&sign=").append(sign);
        System.out.println(stringBuffer.toString());
        //sign欄位和timestamp欄位必須拼接到請求URL上,否則會出現 310000 的錯誤資訊
        DingTalkClient client = new DefaultDingTalkClient(stringBuffer.toString());
        //引數	型別	必選	說明
        //msgtype	string	true	此訊息型別為固定actionCard
        //title	string	true	首屏會話透出的展示內容
        //text	string	true	markdown格式的訊息
        //btns	array	true	按鈕的資訊:title-按鈕方案,actionURL-點選按鈕觸發的URL
        //btnOrientation	string	false	0-按鈕豎直排列,1-按鈕橫向排列
        //hideAvatar	string	false	0-正常發訊息者頭像,1-隱藏發訊息者頭像
		//支援多種request方式
        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
        actionCard.setTitle("杭州天氣");
        actionCard.setText("#### 杭州天氣 @156xxxx8827\n" +
                "> 9度,西北風1級,空氣良89,相對溫度73%\n\n" +
                "> ![screenshot](https://gw.alicdn.com/tfs/TB1ut3xxbsrBKNjSZFpXXcXhFXa-846-786.png)\n"  +
                "> ###### 10點20分發布 [天氣](http://www.thinkpage.cn/) \n");
        // 此處預設為0
        actionCard.setBtnOrientation("0");
        // 此處預設為0
        actionCard.setHideAvatar("0");
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("actionCard");
        request.setActionCard(actionCard);
        OapiRobotSendResponse rsp = client.execute(request);
        System.out.println(rsp.getBody());

相關文章