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

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

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

我们开始

创建一个钉钉机器人

首先你得有个群聊

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

钉钉服务端发送代码

接下来只需要对这个接口进行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)
}

最后

如果对你有用的话

点赞收藏吃灰去呀~

相关推荐
Q26433650233 分钟前
【有源码】基于SpringBoot+Vue的博物馆展览与服务一体化平台-java博物馆数字化展品展示与交互平台设计
java·vue.js·spring boot·spring·毕业设计·javaweb·课程设计
guo_wen_qiang8 分钟前
项目使用sentinel遇到的问题
java·sentinel
小小龙学IT10 分钟前
Go 语言 reflect 反射包深度解析:从 Type/Value 到三大定律与工业实践
前端·golang
CarIise12 分钟前
IDEA与Maven基础课堂笔记
java·intellij-idea·caffe
小溪学编程19 分钟前
C语言篇:枚举类型
java·c语言·前端
xingpanvip22 分钟前
星盘接口开发文档:推算星座接口指南
前端·php
Da Da 泓25 分钟前
HTML浅浅入门
前端·html
এ慕ོ冬℘゜27 分钟前
es6基础
前端·javascript·es6
云和数据.ChenGuang28 分钟前
JAVAEE AI工程师路线图
java·人工智能·java-ee·fastapi·springai·langchain4j
2601_9628857228 分钟前
如何用 Python 统计 A 股连续涨停(几连板)?
java·linux·python