使用Go调用飞书API接口,实现自动化沟通与协作

[TOC]

前言

最近在工作中需要使用飞书进行沟通与协作,为了提升效率,我们希望能够通过编程的方式自动化一些工作流程。飞书提供了开放接口,我们可以使用Go语言通过HTTP请求来调用这些接口。

本文通过介绍如何使用Go调用飞书API接口,实现自动化沟通与协作的方法,旨在帮助读者快速了解该过程。具体实现代码见GitHub仓库链接。

飞书API接口概述

飞书提供了一系列API接口,可以用于实现与企业内部业务相关的数据查询、处理、展现等功能。其中包括:

  • 鉴权接口
  • 群聊接口
  • 用户接口
  • 应用管理接口

详细的接口文档可参考官方文档

这里我们以发送文本消息到群聊为例来介绍如何使用Go调用飞书API接口。

准备工作

使用Go调用飞书API接口,需要进行以下准备工作:

  • 获取AppID和AppSecret
  • 获取TenantAccessToken
  • 获取ChatID

其中,AppID和AppSecret是用于做OAuth2.0的应用凭证,用于应用鉴权的。TenantAccessToken用于应用服务器调用API接口时获取租户授权。ChatID表示要发送消息的群聊ID。

使用Go调用飞书API接口

获取TenantAccessToken

在使用任何飞书API之前,我们需要先获取对应的TenantAccessToken,以便调用各种API接口。

获取租户的TenantAccessToken需要进行鉴权先,具体的步骤如下:

  1. 构造HTTP请求,发送HTTP POST请求到以下URL:

    https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/
  2. 在请求体中设置如下内容:

    {
        "app_id": YOUR_APP_ID,
        "app_secret": YOUR_APP_SECRET
    }
  3. 如果请求成功,服务器将返回如下JSON文本:

    {
        "code": 0,
        "msg": "ok",
        "tenant_access_token": "xxx",
        "expire": 7200
    }

    其中,xxx即为获取到的TenantAccessToken。

具体实现代码如下:

package main

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

const (
    appID     = "xxxx"
    appSecret = "xxxx"
)

type accessTokenResp struct {
    Code             int    `json:"code"`
    Msg              string `json:"msg"`
    TenantAccessToken string `json:"tenant_access_token"`
    Expire           int    `json:"expire"`
}

func main() {
    // 构建HTTP请求体
    reqBody := map[string]string{"app_id": appID, "app_secret": appSecret}
    reqBodyJson, _ := json.Marshal(reqBody)

    // 发送HTTP POST请求
    req, _ := http.NewRequest("POST", "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/", bytes.NewBuffer(reqBodyJson))
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    // 解析接口返回的JSON文本
    var respBody accessTokenResp
    json.NewDecoder(resp.Body).Decode(&respBody)

    // 打印TenantAccessToken信息
    fmt.Println(respBody.TenantAccessToken)
}

获取群聊ID

要发送消息到指定群聊,我们需要先获取群聊的唯一标识符,即ChatID。可以通过以下接口获取:

https://open.feishu.cn/open-apis/chat/v4/list?page_size=20

发送HTTP GET请求后,服务器将返回如下JSON文本:

{
    "data": {
        "has_more": false,
        "groups": [
            {
                "chat_id": "oc_4bbc843d123456789",
                "name": "销售部群聊"
            },
            {
                "chat_id": "oc_4bbc844723456789",
                "name": "研发部群聊"
            }
        ],
        "page_token": ""
    },
    "msg": "ok",
    "code": 0
}

其中,data.groups[*].chat_id表示群聊ID。根据群聊名称或其他关键字来定位群聊。

具体实现代码如下:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

const (
    chatName = "销售部群聊"
)

type chatListResp struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data chatListData `json:"data"`
}

type chatListData struct {
    HasMore    bool         `json:"has_more"`
    Groups     []chatListGroup  `json:"groups"`
    PageToken  string       `json:"page_token"`
}

type chatListGroup struct {
    ChatID string `json:"chat_id"`
    Name   string `json:"name"`
}

func main() {
    // 发送HTTP GET请求
    url := fmt.Sprintf("https://open.feishu.cn/open-apis/chat/v4/list?page_size=20")
    req, _ := http.NewRequest("GET", url, nil)
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    // 解析接口返回的JSON文本
    var respBody chatListResp
    byts, _ := ioutil.ReadAll(resp.Body)
    json.Unmarshal(byts, &respBody)

    // 查找群聊ID
    var chatID string
    for _, group := range respBody.Data.Groups {
        if group.Name == chatName {
            chatID = group.ChatID
            break
        }
    }

    // 打印群聊ID
    fmt.Println(chatID)
}

发送文本消息到群聊

拥有了TenantAccessToken和ChatID之后,我们可以使用以下API接口发送文本消息到指定的群聊:

https://open.feishu.cn/open-apis/message/v4/send/

其中的请求体包含了要发送的文本消息内容:

{
    "chat_id": "oc_4bbc843d123456789",
    "msg_type": "text",
    "content": {
        "text": "Hello World"
    }
}

具体实现代码如下:

package main

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

const (
    appID             = "xxxx"
    appSecret         = "xxxx"
    chatID            = "oc_xxxxxxx"
    messageSendAPIURL = "https://open.feishu.cn/open-apis/message/v4/send/"
)

type accessTokenResp struct {
    Code             int    `json:"code"`
    Msg              string `json:"msg"`
    TenantAccessToken string `json:"tenant_access_token"`
    Expire           int    `json:"expire"`
}

type messageSendReq struct {
    ChatID  string                `json:"chat_id"`
    MsgType string                `json:"msg_type"`
    Content map[string]messageSendReqContent `json:"content"`
}

type messageSendReqContent struct {
    Text string `json:"text"`
}

type messageSendResp struct {
    Code int    `json:"code"`
    Msg  string `json:"msg"`
}

func main() {
    // 获取TenantAccessToken
    tenantAccessToken := getTenantAccessToken(appID, appSecret)

    // 构建HTTP请求体
    reqBody := messageSendReq{
        ChatID:  chatID,
        MsgType: "text",
        Content: map[string]messageSendReqContent{"text": {Text: "Hello World"}},
    }
    reqBodyJson, _ := json.Marshal(reqBody)

    // 发送HTTP POST请求
    req, _ := http.NewRequest("POST", messageSendAPIURL, bytes.NewBuffer(reqBodyJson))
    req.Header.Set("Content-Type", "application/json; charset=utf-8")
    req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", tenantAccessToken))
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    // 解析接口返回的JSON文本
    var respBody messageSendResp
    json.NewDecoder(resp.Body).Decode(&respBody)

    // 打印接口返回值
    fmt.Println(respBody.Code)
}

func getTenantAccessToken(appID, appSecret string) string {
    // 构建HTTP请求体
    reqBody := map[string]string{"app_id": appID, "app_secret": appSecret}
    reqBodyJson, _ := json.Marshal(reqBody)

    // 发送HTTP POST请求
    req, _ := http.NewRequest("POST", "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/", bytes.NewBuffer(reqBodyJson))
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    // 解析接口返回的JSON文本
    var respBody accessTokenResp
    json.NewDecoder(resp.Body).Decode(&respBody)

    // 返回TenantAccessToken
    return respBody.TenantAccessToken
}

总结

本文介绍了如何使用Go调用飞书API接口,实现自动化沟通与协作的方法。首先我们需要获取到AppID、AppSecret和ChatID等信息,然后才能调用API接口。接口调用流程分为获取TenantAccessToken、获取ChatID和发送文本消息三步。具体实现详情可以查看本文实现代码。

分享:

扫一扫在手机阅读、分享本文