图文教学,服务端如何发送(钉钉 +飞书 )机器人通知

一共就两步,创建自定义机器人,然后拿到请求接口,最后把消息发出去。完事~

飞书和钉钉基本上都是一个套路,很简单的~

我们开始

创建一个钉钉机器人

首先你得有个群聊

如果没有发送的文字里没有我们刚刚设定关键字,钉钉接口会返回如下内容

钉钉服务端发送代码

接下来只需要对这个接口进行http请求就完事了

我先来演示下效果,然后,会给出node,php,java,go,python五个语言的演示case

🟩 1. Node.js(ESM版)

javascript 复制代码
import express from "express";
import axios from "axios";

const app = express();
const PORT = 3000;

const DINGTALK_WEBHOOK =
  "https://oapi.dingtalk.com/robot/send?access_token=YOUR_DINGTALK_TOKEN";

app.get("/send-dingtalk", async (req, res) => {
  try {
    const payload = {
      msgtype: "text",
      text: {
        content: "Node.js 发送测试",
      },
    };

    const response = await axios.post(DINGTALK_WEBHOOK, payload);

    res.json(response.data);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.listen(PORT, () => {
  console.log(`http://localhost:${PORT}`);
});

🟨 2. Java(Spring Boot)

typescript 复制代码
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;

@RestController
public class DingController {

    private static final String WEBHOOK =
        "https://oapi.dingtalk.com/robot/send?access_token=YOUR_DINGTALK_TOKEN";

    @GetMapping("/send-dingtalk")
    public Object send() {
        RestTemplate restTemplate = new RestTemplate();

        Map<String, Object> payload = new HashMap<>();
        payload.put("msgtype", "text");

        Map<String, String> text = new HashMap<>();
        text.put("content", "Java 发送测试");

        payload.put("text", text);

        return restTemplate.postForObject(WEBHOOK, payload, String.class);
    }
}

🟪 3. PHP

php 复制代码
<?php

$url = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_DINGTALK_TOKEN";

$data = [
    "msgtype" => "text",
    "text" => [
        "content" => "PHP 发送测试"
    ]
];

$options = [
    "http" => [
        "header"  => "Content-Type: application/json",
        "method"  => "POST",
        "content" => json_encode($data),
    ]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;

🟦 4. Python

makefile 复制代码
import requests

url = "https://oapi.dingtalk.com/robot/send?access_token=YOUR_DINGTALK_TOKEN"

payload = {
    "msgtype": "text",
    "text": {
        "content": "Python 发送测试"
    }
}

response = requests.post(url, json=payload)

print(response.json())

🟫 5. Go

go 复制代码
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

func main() {
	url := "https://oapi.dingtalk.com/robot/send?access_token=YOUR_DINGTALK_TOKEN"

	payload := map[string]interface{}{
		"msgtype": "text",
		"text": map[string]string{
			"content": "Go 发送测试",
		},
	}

	jsonData, _ := json.Marshal(payload)

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("Status:", resp.Status)
}

创建一个飞书机器人

其实飞书和钉钉的流程大差不差

飞书发送代码

其实设钉钉的流程是一样的,就是吧url换一下,入参结构换一下。为了大家方便,我还是五个语言的case都来一份,要case的可以直接cv过去试试

1️⃣ Node.js

ini 复制代码
import axios from "axios";

const FEISHU_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN_HERE";

const payload = {
  msg_type: "text",
  content: {
    text: "这是给伙计们的测试数据,带了'测试'两个字"
  }
};

axios.post(FEISHU_WEBHOOK, payload)
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

2️⃣ Python

makefile 复制代码
import requests

FEISHU_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN_HERE"

payload = {
    "msg_type": "text",
    "content": {
        "text": "这是给伙计们的测试数据,带了'测试'两个字"
    }
}

response = requests.post(FEISHU_WEBHOOK, json=payload)
print(response.json())

3️⃣ Java (使用 HttpClient, Java 11+)

java 复制代码
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class FeishuBot {
    public static void main(String[] args) throws Exception {
        String webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN_HERE";

        String json = "{"
                + ""msg_type":"text","
                + ""content":{"text":"这是给伙计们的测试数据,带了'测试'两个字"}"
                + "}";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(webhook))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}

4️⃣ PHP

php 复制代码
<?php
$webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN_HERE";

$data = [
    "msg_type" => "text",
    "content" => [
        "text" => "这是给伙计们的测试数据,带了'测试'两个字"
    ]
];

$options = [
    'http' => [
        'header'  => "Content-Type: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($data),
    ],
];

$context  = stream_context_create($options);
$result = file_get_contents($webhook, false, $context);
if ($result === FALSE) { /* 错误处理 */ }

echo $result;

5️⃣ Go

go 复制代码
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    webhook := "https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN_HERE"

    payload := map[string]interface{}{
        "msg_type": "text",
        "content": map[string]string{
            "text": "这是给伙计们的测试数据,带了'测试'两个字",
        },
    }

    b, _ := json.Marshal(payload)
    resp, err := http.Post(webhook, "application/json", bytes.NewBuffer(b))
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    fmt.Println(result)
}

最后

如果对你有用的话

点赞收藏吃灰去呀~

相关推荐
guestsun2 小时前
Idea反编译插件--方便查看和修改class文件
java·intellij-idea·jar·反编辑工具·idea反编译插件·class反编译·jar反编译
竹林8182 小时前
从零集成RainbowKit:我如何解决多链钱包连接中的“幽灵网络”问题
前端·javascript
前端炒粉2 小时前
Webpack 基础核心内容总结
前端·webpack·node.js
光影少年2 小时前
前端安全问题?XSS和CSRF?
前端·安全·xss
happymaker06262 小时前
web前端学习日记——DAY08(jQuery,json文件格式,bootstrap)
前端·学习·jquery
小小小小宇2 小时前
算法工程师分类
前端
tuokuac2 小时前
Spring 最核心的注解@Bean本质
java·后端·spring
jiankeljx2 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
Lyyaoo.2 小时前
Spring中的拦截器
java·后端·spring