An easy-to-use unofficial SDK for Feishu and Lark Open Platform

Overview

go-lark

build

go-lark is an easy-to-use unofficial SDK for Feishu and Lark Open Platform.

go-lark implements messaging APIs, with full-fledged supports on building Chat Bot and Notification Bot.

It is widely used and tested by in-house ~450 developers with over 1.5k Go packages.

Features

  • Notification bot & chat bot supported
  • Send messages (Group, Private, Rich Text, and Card)
  • Quick to build message with MsgBuffer
  • Easy to create incoming message hook
  • Encryption and Token Verification supported
  • Middleware support for Gin web framework
  • Documentation & tests

Installation

go get github.com/go-lark/lark

Quick Start

Prerequisite

There are two types of bot that is supported by go-lark. We need to create a bot manually.

Chat Bot:

Notification Bot:

  • Create from group chat.
  • Web Hook URL is required.

Sending Message

Chat Bot:

import "github.com/go-lark/lark"

func main() {
    bot := lark.NewChatBot("<App ID>", "<App Secret>")
    bot.StartHeartbeat()
    bot.PostText("hello, world", lark.WithEmail("[email protected]"))
}

Notification Bot:

import "github.com/go-lark/lark"

func main() {
    bot := lark.NewNotificationBot("WEB HOOK URL")
    bot.PostNotification("go-lark", "example")
}

Feishu/Lark API offers more features, please refers to Usage for further documentation.

Limits

  • go-lark is tested on Feishu endpoints, which literally compats Lark endpoints, because Feishu and Lark basically shares the same API specification. We do not guarantee all of the APIs work well with Lark, until we have tested it on Lark.
  • go-lark only supports Custom App. Marketplace App is not supported yet.
  • go-lark implements bot and messaging API, other APIs such as Lark Doc, Calendar and so so are not supported.

Switch to Lark Endpoints

The default API endpoints are for Feishu, in order to switch to Lark, we should use SetDomain:

bot := lark.NewChatBot("<App ID>", "<App Secret>")
bot.SetDomain(lark.DomainLark)

Usage

Auth

Auto-renewable authentication:

// initialize a chat bot with appID and appSecret
bot := lark.NewChatBot(appID, appSecret)
// Renew access token periodically
bot.StartHeartbeat()
// Stop renewal
bot.StopHeartbeat()

Single-pass authentication:

bot := lark.NewChatBot(appID, appSecret)
resp, err := bot.GetTenantAccessTokenInternal(true)
// and we can now access the token value with `bot.tenantAccessToken()`

Example: examples/auth

Messaging

For Chat Bot, we can send simple messages with the following method:

  • PostText
  • PostTextMention
  • PostTextMentionAll
  • PostImage
  • PostShareChatCard

Basic message examples: examples/basic-message

To build rich messages, we may use Message Buffer (or simply MsgBuffer), which builds message conveniently with chaining methods.

Examples

Apart from the general auth and messaging chapter, there are comprehensive examples for almost all APIs. Here is a collection of ready-to-run examples for each part of go-lark:

Message Buffer

We can build message body with MsgBuffer and send with PostMessage, which supports the following message types:

  • MsgText: Text
  • MsgPost: Rich Text
  • MsgImage: Image
  • MsgShareCard: Group Share Card
  • MsgInteractive: Interactive Card

MsgBuffer provides binding functions and content functions.

Binding functions:

Function Usage Comment
BindChatID Bind a chat ID Either OpenID, UserID, Email or ChatID should be present
BindOpenID Bind a user open ID
BindUserID Bind a user ID
BindEmail Bind a user email
BindReply Bind a reply ID Required when reply other message

Content functions pair with message content types. If it mismatched, it would not have sent successfully. Content functions:

Function Message Type Usage Comment
Text MsgText Append plain text May build with TextBuilder
Post MsgPost Append rich text May build with PostBuilder
Image MsgImage Append image Need to upload to Lark server in advance
ShareChat MsgShareCard Append group share card
Card MsgInteractive Append interactive card No InteractiveBuilder yet. You may try Cardbuilder.

Error Handling

Each go-lark API function returns response and err. err is the error from HTTP client, when it was not nil, HTTP might have gone wrong.

While response is HTTP response from Lark API server, in which Code and Ok represent whether it succeeds. The meaning of Code is defined here.

Event

Lark provides a number of events. go-lark now only implements two of them, which are needed for interacting between bot and Lark server:

  • URL Challenge
  • Receiving Messages

We recommend Gin middleware to handle these events.

Gin Middleware

Example: examples/gin-middleware

URL Challenge

r := gin.Default()
middleware := larkgin.NewLarkMiddleware()
middleware.BindURLPrefix("/handle") // suppose URL is http://your.domain.com/handle
r.Use(middleware.LarkChallengeHandler())

Receiving Message

r := gin.Default()
middleware := larkgin.NewLarkMiddleware()
r.POST("/handle", func(c *gin.Context) {
    if msg, ok := middleware.GetMessage(c); ok && msg != nil {
        text := msg.Event.Text
        // your awesome logic
    }
})

Security & Encryption

Lark Open Platform offers AES encryption and token verification to ensure security for events.

  • AES Encryption: when switch on, all traffic will be encrypted with AES.
  • Token Verification: simple token verification for incoming messages.

We also recommend Gin middleware to handle encryption.

Debugging

Lark does not provide messaging API debugger officially. Thus, we have to debug with real Lark conversation. We add PostEvent to simulate message sending to make it easier. PostEvent can also be used to redirect message, which acts like a reverse proxy.

Example: examples/event-forward

Notice: PostEvent does not support AES encryption at the moment.

Compatibility

go-lark is based on Lark API v3 and v4. The compatibility of each API depends on actual implementation. Compatibility table:

API scope Compatibility Migration
auth N/A Lark does not offer v4
messaging v4 only
interactive card v4 only
bot N/A Lark does not offer v4
group partial v3 & v4 WIP

FAQ

  • I got 99991401 when sending messages
    • remove IP Whitelist from dashboard
  • My bot failed sending messages
    1. check authentication.
    2. not invite to the group.
    3. API permission not applied.
  • Does go-lark support interactive message card?
    • It can send but no card builder provided. You may need to build it manually and send with go-lark.

Contributing

  • If you think you've found a bug with go-lark, please file an issue.
  • Pull Request is welcomed.

License

Copyright (c) David Zhang, 2018-2021. Licensed under MIT License.

Issues
  • feat: improve StartHeartbeat

    feat: improve StartHeartbeat

    Hi @crispgm , I also encounterd the #28 issue. The manually GetTenantAccessTokenInternal(true) call can be avoid if we do the first call in blocking mode. It's a common pattern to init and refresh a resource.

    Closes #28

    opened by wfxr 5
  • BOE服务调用接口返回tls: first record does not look like a TLS handshake

    BOE服务调用接口返回tls: first record does not look like a TLS handshake

    报错信息包括: SendLarkMessage resp:&{Code:0 TenantAppAccessToken: Expire:0}, error: tls: first record does not look like a TLS handshake

    GetTenantAccessTokenInternal error: tls: first record does not look like a TLS handshake

    但是相同配置我在本地跑单测来发送的时候就可以

    opened by 1170300617 1
  • 调用SDK发送消息报错

    调用SDK发送消息报错

    Error 2022-03-25 06:27:10,985 v1(7) logger.go:26 10.189.53.21 tikcast.union.notice_mint_cron - default - 0 [PostMessage] call failed: unexpect status Bad Request, resp body: {"code":99991661,"msg":"Need a token","data":{}} 调用SDK报错,已经初始化自动授权更新。麻烦同学帮忙看下~飞书:xieruijun

    opened by xrj1 1
  • feat: api im

    feat: api im

    • [x] support union ID and check union ID
    • [x] Compat PostMessage
    • [x] GetMessage
    • [x] Replace RecallMessage
    • [x] Compat message v1
    • [x] MsgBuf support ShareUser
    • [x] MsgBuf support File
    • [ ] MsgBuf support Sticker
    • [ ] MsgBuf support Media
    • [ ] MsgBuf support Audio
    opened by crispgm 1
Owner
go-lark-sdk
Unofficial Lark/Feishu Golang SDK
go-lark-sdk
Unofficial SDK to access for Open Threat Exchange (OTX) in Go

gotx Unofficial SDK to access for Open Threat Exchange (OTX) API in Go. Usage package main import ( "context" "fmt" "os" "github.com/m-mizutani/

Masayoshi Mizutani 0 Feb 12, 2022
Unofficial Golang SDK for TON (The Open Network)

TonWeb Unofficial Golang SDK for TON (The Open Network) Installation go get github.com/neotoolkit/tonweb Usage package main import ( "fmt" "os" "

null 4 Jun 13, 2022
null 88 Jun 15, 2022
Twilight is an unofficial Golang SDK for Twilio APIs

Twilight is an unofficial Golang SDK for Twilio APIs. Twilight was born as a result of my inability to spell Twilio correctly. I searched for a Twillio Golang client library and couldn’t find any, I decided to build one. Halfway through building this, I realized I had spelled Twilio as Twillio when searching for a client library on Github.

Ghvst Code 18 Jul 2, 2021
Unofficial SDK of official notion API in Go

notion-go A go client for the Notion API Description This aims to be an unofficial Go version of the official SDK which is written in JavaScript. Inst

Pei-Ming Wu 11 May 12, 2022
Unofficial Fiber Handler for Sentry SDK

Fiber Handler for Sentry SDK Welcome to another "I can't find one, so I made one" episode of mine. Installation $ go get github.com/aldy505/sentry-fib

Reinaldy Rafli 13 Jun 24, 2022
Unofficial Go SDK for GoPay Payments REST API

Unofficial Go SDK for GoPay Payments REST API Installation go get https://github.com/apparently-studio/gopay-go-api Basic usage client := gopay.NewCl

Apparently Studio 2 Feb 5, 2022
unofficial NBA Stats API SDK in Go

nba api go (nag) is an unofficial NBA Stats API in Go. it is very much a Go port of nba_api. endpoints alltimeleadersgrids assistleaders assisttracker

aprp 0 Dec 11, 2021
Amplitude unofficial client for Go, inspired in their official SDK for Node

Amplitude Golang SDK Amplitude unofficial client for Go, inspired in their official SDK for Node. For reference, visit HTTP API v2 documentation. Inst

Renato Almeida 5 Apr 23, 2022
Unofficial getpocket.com API Golang SDK

GetPocket API Golang SDK https://getpocket.com/developer/ Example usage: package main import ( "context" "fmt" pocket "github.com/ernur-eskermes/p

Ernur Eskermes 0 Nov 28, 2021
Golang SDK for Dusupay payment gateway API (Unofficial)

Dusupay API SDK GO (Unofficial) Description Unofficial Dusupay payment gateway API Client for Go API documentation https://docs.dusupay.com/ Installat

Anton Kornilov 1 Mar 22, 2022
Nextengine-sdk-go: the NextEngine SDK for the Go programming language

NextEngine SDK for Go nextengine-sdk-go is the NextEngine SDK for the Go programming language. Getting Started Install go get github.com/takaaki-s/nex

null 0 Dec 7, 2021
Commercetools-go-sdk is fork of original commercetools-go-sdk

commercetools-go-sdk The Commercetools Go SDK is automatically generated based on the official API specifications of Commercetools. It should therefor

Flink 0 Dec 13, 2021
Sdk-go - Go version of the Synapse SDK

synapsesdk-go Synapse Protocol's Go SDK. Currently in super duper alpha, do not

null 0 Jan 7, 2022
Redash-go-sdk - An SDK for the programmatic management of Redash, in Go

Redash Go SDK An SDK for the programmatic management of Redash. The main compone

RecoLabs 24 Mar 3, 2022
SDK to provide access to JUNO API (Open Banking) (2.0.0)

Juno API - Golang SDK Juno API (Open Banking) (2.0.0) Why? This project is part of my personal portfolio, so, I'll be happy if you could provide me an

Vinícius Boscardin 4 Aug 9, 2021
Getting presigned urls for S3 with AWS SDK Go V2. Easy deploy with Velcel CLI.

S3-Presigned-Urls-Vercel-Serverless Setup yarn install && yarn setup Run(Local) yarn start You need to set environment variables with os.setenv for lo

Jayden 0 Jan 14, 2022
Go SDK for working with the Nightfall Developer Platform

Nightfall Go SDK nightfall-go-sdk is a Go client library for accessing the Nightfall API. It allows you to add functionality to your applications to s

Nightfall AI 10 Jun 20, 2022
Unofficial Google Trends API for Go

Google Trends API for Go Unofficial Google Trends API for Golang gogtrends is API wrapper which allows to get reports from Google Trends. All contribu

Max Ivanov 65 Jun 14, 2022