Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

An easy-to-use SDK for Feishu and Lark Open Platform (Instant Messaging API only)

License

NotificationsYou must be signed in to change notification settings

go-lark/lark

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

buildcodecovGo Report CardGo ModuleGo ReferenceMentioned in Awesome Go

简体中文

go-lark is an easy-to-use SDK for Feishu and Lark Open Platform,which implements messaging APIs, with full-fledged supports on building Chat Bot and Notification Bot.

It is widely used and tested by ~650 ByteDance in-house developers with over 3k Go packages.

Features

  • Notification bot & chat bot supported
  • Send messages (Group, Private, Rich Text, and Card)
  • Quick to build message withMsgBuffer
  • Easy to create incoming message hook
  • Encryption and token verification supported
  • Middleware support for Gin & Hertz web framework
  • Highly extensible
  • 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"funcmain() {bot:=lark.NewChatBot("<App ID>","<App Secret>")bot.StartHeartbeat()bot.PostText("hello, world",lark.WithEmail("someone@example.com"))}

Notification Bot:

import"github.com/go-lark/lark"funcmain() {bot:=lark.NewNotificationBot("<WEB HOOK URL>")bot.PostNotificationV2(lark.NewMsgBuffer(lark.MsgText).Text("hello, world").Build())}

Feishu/Lark API offers more features, please refers toUsage 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 messaging, group chat, and bot API, other APIs such as Lark Doc, Calendar and so on are not supported.

Switch to Lark Endpoints

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

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

Usage

Auth

Auto-renewable authentication:

// initialize a chat bot with appID and appSecretbot:=lark.NewChatBot(appID,appSecret)// Renew access token periodicallybot.StartHeartbeat()// Stop renewalbot.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
  • ReplyMessage
  • AddReaction
  • DeleteReaction

Basic message examples:examples/basic-message

To build rich messages, we may useMessage Buffer (or simplyMsgBuffer),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 ofgo-lark:

Message Buffer

We can build message body withMsgBuffer and send withPostMessage, which supports the following message types:

  • MsgText: Text
  • MsgPost: Rich Text
  • MsgInteractive: Interactive Card
  • MsgShareCard: Group Share Card
  • MsgShareUser: User Share Card
  • MsgImage: Image
  • MsgFile: File
  • MsgAudio: Audio
  • MsgMedia: Media
  • MsgSticker: Sticker

MsgBuffer provides binding functions and content functions.

Binding functions:

FunctionUsageComment
BindChatIDBind a chat IDEitherOpenID,UserID,Email,ChatID orUnionID should be present
BindOpenIDBind a user open ID
BindUserIDBind a user ID
BindUnionIDBind a union ID
BindEmailBind a user email
BindReplyBind a reply IDRequired when reply a message

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

FunctionMessage TypeUsageComment
TextMsgTextAppend plain textMay build withTextBuilder
PostMsgPostAppend rich textMay build withPostBuilder
CardMsgInteractiveAppend interactive cardMay build withCardBuilder
TemplateMsgInteractiveAppend card templateRequired to build withCardKit
ShareChatMsgShareCardAppend group share card
ShareUserMsgShareUserAppend user share card
ImageMsgImageAppend imageRequired to upload to Lark server in advance
FileMsgFileAppend fileRequired to upload to Lark server in advance
AudioMsgAudioAppend audioRequired to upload to Lark server in advance
MediaMsgMediaAppend mediaRequired to upload to Lark server in advance
StickerMsgStickerAppend stickerRequired to upload to Lark server in advance

Error Handling

Eachgo-lark API function returnsresponse anderr.err is the error from HTTP client, when it was notnil, HTTP might have gone wrong.

Whileresponse is HTTP response from Lark API server, in whichCode andOK represent whether it succeeds.The meaning ofCode is definedhere.

Event

Lark provides a number ofevents and they are in two different schema (1.0/2.0).go-lark now only implements a few of them, which are needed for interacting between bot and Lark server:

  • URL Challenge
  • Receiving Messages

We recommend HTTP middlewares to handle these events.

Middlewares

We have already implemented HTTP middlewares to support event handling:

Example:examples/gin-middlewareexamples/hertz-middleware

URL Challenge

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

Event V2

Lark has provided event v2 and it applied automatically to newly created bots.

r:=gin.Default()middleware:=larkgin.NewLarkMiddleware()r.Use(middleware.LarkEventHandler())

Get the event (e.g. Message):

r.POST("/",func(c*gin.Context) {ifevt,ok:=middleware.GetEvent(c);ok {// => GetEvent instead of GetMessageifevt.Header.EventType==lark.EventTypeMessageReceived {ifmsg,err:=evt.GetMessageReceived();err==nil {fmt.Println(msg.Message.Content)            }        }    }})

Card Callback

We may also setup callback for card actions (e.g. button). The URL challenge part is the same.

We may useLarkCardHandler to handle the actions:

r.Use(middleware.LarkCardHandler())r.POST("/callback",func(c*gin.Context) {ifcard,ok:=middleware.GetCardCallback(c);ok {    }})

Receiving Message (Event V1)

For older bots, please use v1:

r:=gin.Default()middleware:=larkgin.NewLarkMiddleware()middleware.BindURLPrefix("/handle")// supposed URL is http://your.domain.com/handler.POST("/handle",func(c*gin.Context) {ifmsg,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 recommend you to enable token verification. If HTTPS is not available on your host, then enable AES encryption.

middleware.WithTokenVerfication("<verification-token>")middleware.WithEncryption("<encryption-key>")

Debugging

Lark does not provide messaging API debugger officially. Thus, we have to debug with real Lark conversation.We recommendngrok to debug events.

And we addPostEvent to simulate message sending to make it even easier.PostEvent can also be used to redirect events, which acts like a reverse proxy.

Development

Test

  1. Dotenv Setup

    go-lark usesgodotenv test locally. You may have to create a.env file in repo directory, which contains environmental variables:

    LARK_APP_IDLARK_APP_SECRETLARK_USER_EMAILLARK_USER_IDLARK_UNION_IDLARK_OPEN_IDLARK_CHAT_IDLARK_WEBHOOK_V2LARK_WEBHOOK_V2_SIGNED

    LARK_APP_ID andLARK_APP_SECRET are mandatory. Others are required only by specific API tests.

  2. Run Test

    GO_LARK_TEST_MODE=local ./scripts/test.sh

Extensions

go-lark's dev utilities (authentication, HTTP handling, and etc.) are capable for easily implementing most of APIs provided by Lark Open Platform.And we may use that as an extension for go-lark.

Here is an example that implementing a Lark Doc API with go-lark:

package larkimport"github.com/go-lark/lark"constcopyFileAPIPattern="/open-apis/drive/explorer/v2/file/copy/files/%s"// CopyFileResponse .typeCopyFileResponsestruct {lark.BaseResponseDataCopyFileData`json:"data"`}// CopyFileData .typeCopyFileDatastruct {FolderTokenstring`json:"folderToken"`Revisionint64`json:"revision"`Tokenstring`json:"token"`Typestring`json:"type"`URLstring`json:"url"`}// CopyFile implementationfuncCopyFile(bot*lark.Bot,fileToken,dstFolderToken,dstNamestring) (*CopyFileResponse,error) {varrespData model.CopyFileResponseerr:=bot.PostAPIRequest("CopyFile",fmt.Sprintf(copyFileAPIPattern,fileToken),true,map[string]interface{}{"type":"doc","dstFolderToken":dstFolderToken,"dstName":dstName,"permissionNeeded":true,"CommentNeeded":false,},&respData,)return&respData,err}

FAQ

  • I got99991401 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?
    • Yes, use a CardBuilder.

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-2024. Licensed under MIT License.

About

An easy-to-use SDK for Feishu and Lark Open Platform (Instant Messaging API only)

Topics

Resources

License

Stars

Watchers

Forks

Languages


[8]ページ先頭

©2009-2025 Movatter.jp