### Create Thread Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Create method to start a thread on a message. ```go resp, err := client.Im.V1.Thread.Create(ctx, &larkim.CreateThreadReq{ Body: &larkim.CreateThreadReqBody{ ParentMessageId: "om_xxx", Title: "Discussion", }, }) if err != nil { panic(err) } fmt.Println("Thread ID:", resp.Data.ThreadId) ``` -------------------------------- ### Minimal Channel Bot Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/doc/channel.md This example demonstrates the basic setup and operation of a Feishu bot using the Channel module. It initializes the API and WebSocket clients, creates a Channel instance, registers an event handler for messages, and starts the channel. It also includes lifecycle hooks and graceful shutdown handling. ```go package main import ( "context" "fmt" "os" "os/signal" lark "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/channel" "github.com/larksuite/oapi-sdk-go/v3/channel/types" "github.com/larksuite/oapi-sdk-go/v3/core" larkws "github.com/larksuite/oapi-sdk-go/v3/ws" ) func main() { appID := os.Getenv("FEISHU_APP_ID") appSecret := os.Getenv("FEISHU_APP_SECRET") // 1. Initialize API Client client := lark.NewClient(appID, appSecret, lark.WithLogLevel(core.LogLevelInfo)) // 2. Initialize WebSocket Client wsClient := larkws.NewClient(appID, appSecret, larkws.WithLogLevel(core.LogLevelInfo)) // 3. Create Channel ch := channel.NewChannel(client, wsClient) // 4. Optional lifecycle hooks ch.OnReady(func() { fmt.Println("channel is ready") }) // 5. Register event handlers ch.OnMessage(func(ctx context.Context, msg *types.NormalizedMessage) error { fmt.Printf("received message: %s\n", msg.Content) _, err := ch.Send(ctx, &types.SendInput{ ChatID: msg.ChatID, Markdown: fmt.Sprintf("received: %s", msg.Content), ReplyMessageID: msg.MessageID, }) return err }) // 6. Start Channel so lifecycle hooks are wired through Channel itself if err := ch.Start(context.Background()); err != nil { panic(err) } // 7. Wait for termination stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt) <-stop _ = ch.Stop(context.Background()) } ``` -------------------------------- ### Retrieve Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Get method. ```go resp, err := client.Im.V1.Message.Get(ctx, &larkim.GetMessageReq{ MessageId: "om_xxx", }) if err != nil { panic(err) } fmt.Println("Content:", resp.Data.Body.Content) ``` -------------------------------- ### Get Progress Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Demonstrates how to check the delivery progress of a specific batch message. ```go progress, err := client.Im.V1.BatchMessage.GetProgress(ctx, &larkim.GetProgressBatchMessageReq{ BatchMessageId: "bm_xxx", }, ) if err != nil { panic(err) } fmt.Printf("Delivered: %d\n", progress.Data.MessageCount) ``` -------------------------------- ### Initialize AppPreset instance Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Example instantiation of the AppPreset struct. ```go AppPreset: &AppPreset{ Avatar: []string{"https://example.com/logo.png"}, Name: "My Assistant Bot", Desc: "A helpful bot for team communication", } ``` -------------------------------- ### Get Chat Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Usage example for retrieving details of a specific chat by ID. ```go resp, err := client.Im.V1.Chat.Get(ctx, &larkim.GetChatReq{ ChatId: "oc_xxx", }) if err != nil { panic(err) } fmt.Println("Chat name:", resp.Data.Name) ``` -------------------------------- ### Initialize AppAddonsEvents instance Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Example configuration for event subscriptions. ```go Events: AppAddonsEvents{ Items: AppAddonsEventItems{ Tenant: []string{ "im.message.receive_v1", "im.message.reaction.created_v1", "im.chat.member.bot_added_v1", "card.action.trigger", }, }, } ``` -------------------------------- ### Create Chat Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Usage example for creating a private chat with initial members. ```go resp, err := client.Im.V1.Chat.Create(ctx, &larkim.CreateChatReq{ Body: &larkim.CreateChatReqBody{ Name: "Team Chat", ChatType: "private", UserIdList: []string{"ou_xxx", "ou_yyy"}, }, }) if err != nil { panic(err) } fmt.Println("Chat created:", resp.Data.ChatId) ``` -------------------------------- ### Initialize AppAddonsScopes instance Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Example configuration for application permission scopes. ```go Scopes: AppAddonsScopes{ Tenant: []string{ "im:message:send_as_bot", "im:chat:readonly", "contact:contact:readonly", }, User: []string{ "contact:user:email:read", }, } ``` -------------------------------- ### Example Channel Initialization Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Demonstrates how to instantiate a Channel with required HTTP and WebSocket clients and optional configuration. ```go import ( "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/channel" "github.com/larksuite/oapi-sdk-go/v3/ws" ) httpClient := lark.NewClient("app_id", "app_secret") wsClient := larkws.NewClient("app_id", "app_secret") ch := channel.NewChannel(httpClient, wsClient, channel.WithPolicyConfig(myPolicy), ) ``` -------------------------------- ### Update Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Update method. ```go resp, err := client.Im.V1.Message.Update(ctx, &larkim.UpdateMessageReq{ MessageId: "om_xxx", Body: &larkim.UpdateMessageReqBody{ Content: `{"text":"Updated content"}`, }, }) ``` -------------------------------- ### Initialize AppAddonsCallbacks instance Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Example configuration for webhook callbacks. ```go Callbacks: AppAddonsCallbacks{ Items: []string{ "card.action.trigger", }, } ``` -------------------------------- ### Post Request Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Demonstrates sending a POST request with a JSON body and tenant access token. ```go ctx := context.Background() body := map[string]interface{}{ "chat_id": "oc_xxx", "content": "Hello", } resp, err := client.Post(ctx, "/open-apis/im/v1/messages", body, larkcore.AccessTokenTypeTenant) if err != nil { panic(err) } ``` -------------------------------- ### Send Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Create method to send a text message. ```go resp, err := client.Im.V1.Message.Create(ctx, &larkim.CreateMessageReq{ Body: &larkim.CreateMessageReqBody{ ReceiveId: "oc_xxx", MsgType: "text", Content: `{"text":"Hello World"}`, }, }) if err != nil { panic(err) } fmt.Println("Message sent:", resp.Data.MessageId) ``` -------------------------------- ### List Chats Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Usage example for listing chats and iterating through the results. ```go resp, err := client.Im.V1.Chat.List(ctx, &larkim.ListChatReq{ PageSize: 20, }) if err != nil { panic(err) } for _, chat := range resp.Data.Items { fmt.Println(chat.Name) } ``` -------------------------------- ### Initialize Channel with Custom Options Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Example of creating a new channel instance with overridden safety configuration. ```go ch := channel.NewChannel(httpClient, wsClient, channel.WithSafetyConfig(types.SafetyConfig{ Dedup: struct{...}{ MaxEntries: 5000, SweepIntervalMs: 30 * time.Minute, }, }), ) ``` -------------------------------- ### Add Reaction Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Create method to add an emoji reaction. ```go resp, err := client.Im.V1.MessageReaction.Create(ctx, &larkim.CreateMessageReactionReq{ MessageId: "om_xxx", Body: &larkim.CreateMessageReactionReqBody{ ReactionType: "👍", }, }) ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/constants-enums.md List of supported environment variables and an example of how to set them. ```text LARK_APP_ID # Application ID LARK_APP_SECRET # Application secret LARK_BASE_URL # Custom base URL LARK_OAUTH_BASE_URL # Custom OAuth URL LARK_LOG_LEVEL # Logging level (1-4) ``` ```bash export LARK_APP_ID="app_id" export LARK_APP_SECRET="app_secret" export LARK_LOG_LEVEL="2" ``` -------------------------------- ### Start Channel Connection Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Establishes the WebSocket connection and starts listening for events. Blocks until the context is canceled or an error occurs. ```go func (ch Channel) Start(ctx context.Context) error ``` ```go ctx := context.Background() err := ch.Start(ctx) if err != nil { fmt.Printf("Channel start failed: %v\n", err) } ``` -------------------------------- ### Add Chat Members Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Create method to add multiple users to a chat. ```go resp, err := client.Im.V1.ChatMembers.Create(ctx, &larkim.CreateChatMembersReq{ ChatId: "oc_xxx", Body: &larkim.CreateChatMembersReqBody{ IdList: []string{"ou_xxx", "ou_yyy"}, }, }) ``` -------------------------------- ### List Messages Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the List method to retrieve messages. ```go resp, err := client.Im.V1.Message.List(ctx, &larkim.ListMessageReq{ ContainerId: "oc_xxx", PageSize: 20, }) if err != nil { panic(err) } for _, msg := range resp.Data.Items { fmt.Println(msg.MessageId) } ``` -------------------------------- ### Delete Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Delete method. ```go resp, err := client.Im.V1.Message.Delete(ctx, &larkim.DeleteMessageReq{ MessageId: "om_xxx", }) ``` -------------------------------- ### Stream Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Example of sending a message and appending chunks of text to it. ```go stream, err := ch.Stream(ctx, &types.SendInput{ ChatID: "oc_xxx", Text: "Generating response...", }) if err != nil { panic(err) } // Stream multiple text chunks for chunk := range generatedChunks { if err := stream.Append(ctx, chunk); err != nil { panic(err) } } // Finalize if err := stream.Close(ctx); err != nil { panic(err) } ``` -------------------------------- ### Refresh Usage Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/access-token-reference.md Example implementation of refreshing an access token without user interaction. ```go newToken, err := client.AccessToken.Refresh(ctx, &refreshtoken.TokenRequest{ RefreshToken: "refresh_token_xxx", ClientId: "app_id", ClientSecret: "app_secret", GrantType: "refresh_token", }, ) if err != nil { panic(err) } fmt.Println("New Access Token:", newToken.Data.AccessToken) ``` -------------------------------- ### Configure Chat Permissions Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/constants-enums.md Example of applying permission constants during chat creation. ```go resp, err := client.Im.V1.Chat.Create(ctx, &larkim.CreateChatReq{ Body: &larkim.CreateChatReqBody{ Name: "Chat", MentionAllAuthority: "only_owner", // Only owner can @all AddMemberPermission: "all_members", // Anyone can add members AtAllPermission: "only_owner", // Only owner can @all }, }) ``` -------------------------------- ### RetrieveByAuthorizationCode Usage Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/access-token-reference.md Example implementation of the authorization code grant flow. ```go ctx := context.Background() token, err := client.AccessToken.RetrieveByAuthorizationCode(ctx, &authorizationcode.TokenRequest{ Code: "auth_code_xxx", ClientId: "app_id", ClientSecret: "app_secret", GrantType: "authorization_code", RedirectUri: "https://example.com/callback", }, ) if err != nil { panic(err) } fmt.Println("Access Token:", token.Data.AccessToken) ``` -------------------------------- ### Update Chat Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Usage example for updating a chat's name. ```go resp, err := client.Im.V1.Chat.Update(ctx, &larkim.UpdateChatReq{ ChatId: "oc_xxx", Body: &larkim.UpdateChatReqBody{ Name: "New Chat Name", }, }) ``` -------------------------------- ### List Members Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the List method to retrieve and iterate over chat members. ```go resp, err := client.Im.V1.ChatMembers.List(ctx, &larkim.ListChatMembersReq{ ChatId: "oc_xxx", PageSize: 20, }) for _, member := range resp.Data.Items { fmt.Println(member.MemberId) } ``` -------------------------------- ### Remove Member Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Example usage of the Delete method to remove a member. ```go resp, err := client.Im.V1.ChatMembers.Delete(ctx, &larkim.DeleteChatMembersReq{ ChatId: "oc_xxx", MemberId: "ou_xxx", }) ``` -------------------------------- ### GetAppAccessTokenBySelfBuiltApp Usage Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Demonstrates how to invoke the GetAppAccessTokenBySelfBuiltApp method and handle the response. ```go ctx := context.Background() resp, err := client.GetAppAccessTokenBySelfBuiltApp(ctx, &larkcore.SelfBuiltAppAccessTokenReq{}) if err != nil { panic(err) } fmt.Println("Access Token:", resp.Data.AccessToken) ``` -------------------------------- ### Access Productivity Services Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/services-guide.md Examples for accessing Drive, Wiki, Docs, Docx, Sheets, and Bitable service operations. ```go client.Drive.V1.File.Upload(ctx, req) client.Drive.V1.Folder.Create(ctx, req) client.Drive.V1.File.Download(ctx, req) ``` ```go client.Wiki.V1.WikiNode.Create(ctx, req) client.Wiki.V1.WikiSpace.List(ctx, req) ``` ```go client.Docs.V1.Document.Create(ctx, req) ``` ```go client.Docx.V1.Document.Create(ctx, req) ``` ```go client.Sheets.V3.Spreadsheet.Create(ctx, req) client.Sheets.V3.SpreadsheetValueBatcher.BatchWrite(ctx, req) ``` ```go client.Bitable.V1.App.Create(ctx, req) client.Bitable.V1.AppTable.Create(ctx, req) client.Bitable.V1.AppTableRecord.Create(ctx, req) ``` -------------------------------- ### Channel.Start Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Establishes the WebSocket connection and starts listening for events. Blocks until the context is canceled or an error occurs. ```APIDOC ## func (ch Channel) Start(ctx context.Context) error ### Description Establishes the WebSocket connection and starts listening for events. Blocks until the context is canceled or an error occurs. ### Parameters - **ctx** (context.Context) - Required - The context to control the lifecycle of the connection. ### Example ```go ctx := context.Background() err := ch.Start(ctx) if err != nil { fmt.Printf("Channel start failed: %v\n", err) } ``` ``` -------------------------------- ### Install Lark Suite Go SDK Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/README.md Use this command to add the SDK to your Go project dependencies. ```bash go get github.com/larksuite/oapi-sdk-go/v3 ``` -------------------------------- ### Implement Custom Logger Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/core-types.md Example implementation of the Logger interface using standard library logging. ```go type MyLogger struct{} func (l *MyLogger) Debug(ctx context.Context, args ...interface{}) { log.Println("[DEBUG]", args) } func (l *MyLogger) Info(ctx context.Context, args ...interface{}) { log.Println("[INFO]", args) } func (l *MyLogger) Warn(ctx context.Context, args ...interface{}) { log.Println("[WARN]", args) } func (l *MyLogger) Error(ctx context.Context, args ...interface{}) { log.Println("[ERROR]", args) } ``` -------------------------------- ### Execute Resource Operations Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/service-pattern.md Examples of performing CRUD operations on resources using the SDK client. ```go resp, err := client.Im.V1.Message.Create(ctx, &larkim.CreateMessageReq{ Body: &larkim.CreateMessageReqBody{ ReceiveId: "oc_xxx", MsgType: "text", Content: `{"text":"Hello"}`, }, }) if err != nil { panic(err) } fmt.Println("Message created:", resp.Data.MessageId) ``` ```go resp, err := client.Im.V1.Chat.Get(ctx, &larkim.GetChatReq{ ChatId: "oc_xxx", }) if err != nil { panic(err) } fmt.Println("Chat name:", resp.Data.Name) ``` ```go resp, err := client.Im.V1.Chat.Update(ctx, &larkim.UpdateChatReq{ ChatId: "oc_xxx", Body: &larkim.UpdateChatReqBody{ Name: "New Chat Name", }, }) if err != nil { panic(err) } ``` ```go resp, err := client.Im.V1.Message.Delete(ctx, &larkim.DeleteMessageReq{ MessageId: "om_xxx", }) if err != nil { panic(err) } ``` ```go resp, err := client.Im.V1.Chat.List(ctx, &larkim.ListChatReq{ PageSize: 20, }) if err != nil { panic(err) } for _, chat := range resp.Data.Items { fmt.Println(chat.Name) } // Pagination if resp.Data.HasMore { nextResp, _ := client.Im.V1.Chat.List(ctx, &larkim.ListChatReq{ PageSize: 20, PageToken: resp.Data.PageToken, }) _ = nextResp } ``` -------------------------------- ### Send a Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Basic implementation of sending a text message to a specific chat. ```go result, err := ch.Send(ctx, &types.SendInput{ ChatID: "oc_xxx", Text: "Hello, World!", }) if err != nil { panic(err) } fmt.Println("Message sent:", result.MessageID) ``` -------------------------------- ### Client.Get Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Makes a GET request. ```APIDOC ## func (cli *Client) Get ### Description Makes a GET request to the specified path. ### Parameters - **ctx** (context.Context) - Request context - **httpPath** (string) - API endpoint path - **body** (interface{}) - Request body - **accessTokenType** (AccessTokenType) - Type of access token - **options** (...RequestOptionFunc) - Optional request modifiers ``` -------------------------------- ### Implement Channel Lifecycle Callbacks Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Example usage of channel event listeners to handle connection status changes. ```go ch.OnReady(func() { fmt.Println("Channel is ready") }) ch.OnError(func(err error) { fmt.Printf("Channel error: %v\n", err) }) ch.OnReconnecting(func() { fmt.Println("Reconnecting...") }) ch.OnDisconnected(func() { fmt.Println("Channel disconnected") }) ``` -------------------------------- ### Access Communication Services Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/services-guide.md Examples for accessing IM, Mail, and Video Conferencing service operations. ```go client.Im.V1.Message.Create(ctx, req) client.Im.V1.Chat.List(ctx, req) client.Im.V1.Thread.Create(ctx, req) ``` ```go client.Mail.V1.MailGroup.Create(ctx, req) client.Mail.V1.MailGroupMember.List(ctx, req) ``` ```go client.Vc.V1.Meeting.Create(ctx, req) client.Vc.V1.MeetingRoom.List(ctx, req) ``` -------------------------------- ### Apply request options to a client call Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/core-types.md Example of passing a request option to a client method to customize headers or parameters. ```go resp, err := client.Post(ctx, "/path", body, accessTokenType, larkcore.WithRequestID("custom-id"), ) ``` -------------------------------- ### Send Batch Message Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Demonstrates how to send a text message to multiple users using the batch message API. ```go resp, err := client.Im.V1.BatchMessage.Create(ctx, &larkim.CreateBatchMessageReq{ Body: &larkim.CreateBatchMessageReqBody{ UserIds: []string{"ou_xxx", "ou_yyy"}, MsgType: "text", Content: `{"text":"Announcement"}`, }, }) if err != nil { panic(err) } fmt.Println("Batch ID:", resp.Data.BatchMessageId) ``` -------------------------------- ### Execute IM Message Creation Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/service-pattern.md Example of invoking a service method that automatically utilizes the required tenant access token. ```go resp, err := client.Im.V1.Message.Create(ctx, req) // Uses tenant access token automatically ``` -------------------------------- ### Create Thread Method Signature Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Defines the Create method for starting a new message thread. ```go func (t *thread) Create(ctx context.Context, req *CreateThreadReq, options ...larkcore.RequestOptionFunc) (*CreateThreadResp, error) ``` -------------------------------- ### Configure Client Logging Level Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/constants-enums.md Example of applying a logging level constant during the initialization of a new Lark client. ```go client := lark.NewClient("app_id", "app_secret", lark.WithLogLevel(larkcore.LogLevelDebug), ) ``` -------------------------------- ### Verify Event Signature Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/event-handling-reference.md Example implementation for comparing a computed signature against the header value provided by the request. ```go import "github.com/larksuite/oapi-sdk-go/v3/event" // Verify signature timestamp := req.Header.Get("X-Lark-Request-Timestamp") nonce := req.Header.Get("X-Lark-Request-Nonce") received := req.Header.Get("X-Lark-Signature-V1") computed := event.Signature(timestamp, nonce, eventKey, string(req.Body)) if computed != received { return errors.New("signature verification failed") } ``` -------------------------------- ### Initialize SDK Client Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Demonstrates basic client initialization and usage with optional configuration parameters. ```go package main import ( "context" lark "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/core" ) func main() { // Basic initialization client := lark.NewClient("app_id", "app_secret") // With options client := lark.NewClient( "app_id", "app_secret", lark.WithLogLevel(larkcore.LogLevelDebug), lark.WithReqTimeout(10 * time.Second), ) } ``` -------------------------------- ### Example JSON response Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/access-token-reference.md A sample JSON payload returned by the access token endpoint. ```json { "code": 0, "msg": "success", "data": { "access_token": "u.f8234324f8afbb8f", "token_type": "Bearer", "expires_in": 7200, "refresh_token": "hra_1234567890abcdef", "refresh_token_expires_in": 2592000, "scope": "im:message:send_as_bot contact:contact:readonly" } } ``` -------------------------------- ### Implement Basic Registration Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Demonstrates the full registration flow including QR code display and status polling. ```go package main import ( "context" "fmt" "time" lark "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/scene/registration" ) func main() { // Set context with timeout ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute) defer cancel() // Register the app result, err := registration.RegisterApp(ctx, ®istration.Options{ OnQRCode: func(info *registration.QRCodeInfo) { fmt.Printf("Open this URL in Feishu: %s\n", info.URL) fmt.Printf("QR code expires in %d seconds\n", info.ExpireIn) }, OnStatusChange: func(info *registration.StatusChangeInfo) { fmt.Printf("Status: %s\n", info.Status) if info.Interval > 0 { fmt.Printf("Polling again in %d seconds...\n", info.Interval) } }, }) if err != nil { panic(err) } fmt.Println("Registration successful!") fmt.Println("App ID:", result.ClientID) fmt.Println("App Secret:", result.ClientSecret) fmt.Println("User:", result.UserInfo.OpenID) // Create client with registered credentials client := lark.NewClient(result.ClientID, result.ClientSecret) _ = client } ``` -------------------------------- ### Access Application Service Operations Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/services-guide.md Use these methods to get or list applications via the V6 API. ```go client.Application.V6.App.Get(ctx, req) client.Application.V6.App.List(ctx, req) ``` -------------------------------- ### Send Messages Using Message Type Constants Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/constants-enums.md Examples of sending text and interactive card messages using the CreateMessageReq structure. ```go // Send text message resp, err := client.Im.V1.Message.Create(ctx, &larkim.CreateMessageReq{ Body: &larkim.CreateMessageReqBody{ MsgType: "text", Content: `{"text":"Hello"}`, }, }) // Send card resp, err := client.Im.V1.Message.Create(ctx, &larkim.CreateMessageReq{ Body: &larkim.CreateMessageReqBody{ MsgType: "interactive", Content: cardJson, }, }) ``` -------------------------------- ### Initialize Client from Environment Variables Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/quick-start-patterns.md Avoids hardcoding credentials by retrieving app identifiers from the system environment. ```go // Never hardcode credentials // Use environment variables: // export LARK_APP_ID="..." // export LARK_APP_SECRET="..." func createClientFromEnv() (*lark.Client, error) { appID := os.Getenv("LARK_APP_ID") appSecret := os.Getenv("LARK_APP_SECRET") if appID == "" || appSecret == "" { return nil, errors.New("missing LARK_APP_ID or LARK_APP_SECRET") } return lark.NewClient(appID, appSecret), nil } ``` -------------------------------- ### Delete Chat Example Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Usage example for dissolving a chat by ID. ```go resp, err := client.Im.V1.Chat.Delete(ctx, &larkim.DeleteChatReq{ ChatId: "oc_xxx", }) ``` -------------------------------- ### Usage Example for Event Decryption Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/event-handling-reference.md Demonstrates decrypting an event payload retrieved from request headers using a secret key. ```go import "github.com/larksuite/oapi-sdk-go/v3/event" // Get encryption from request header encrypted := req.Header.Get("X-Lark-Content-V1-Encrypted") secret := "event_key_from_settings" decrypted, err := event.EventDecrypt(encrypted, secret) if err != nil { panic(err) } // decrypted now contains JSON event data ``` -------------------------------- ### Initialize and Access Services in Go Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/services-guide.md Standard pattern for initializing the client and navigating the service hierarchy to execute API operations. ```go client := lark.NewClient("app_id", "app_secret") // Access service service := client.ServiceName // Access API version v1 := service.V1 // or V2, V3 depending on service v2 := service.V2 // Access resource resource := v1.ResourceName // Call operation resp, err := resource.Operation(ctx, req) ``` -------------------------------- ### Accessing SDK Services Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Demonstrates how to access service fields and specific resources from the initialized client. ```go // Access the IM service imService := client.Im // Access a specific resource messages := imService.V1.Message ``` -------------------------------- ### Implement a Complete Channel Handler in Go Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Demonstrates the full lifecycle of a channel, including initialization, event registration, and background execution with signal handling. ```go package main import ( "context" "fmt" "os" "os/signal" "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/channel" "github.com/larksuite/oapi-sdk-go/v3/channel/types" "github.com/larksuite/oapi-sdk-go/v3/ws" ) func main() { // Initialize clients httpClient := lark.NewClient("app_id", "app_secret") wsClient := larkws.NewClient("app_id", "app_secret") // Create channel ch := channel.NewChannel(httpClient, wsClient) // Set up handlers ch.OnReady(func() { fmt.Println("Channel ready") }) ch.OnMessage(func(ctx context.Context, msg *types.NormalizedMessage) error { fmt.Printf("Message from %s: %s\n", msg.UserID, msg.Content) // Echo the message _, err := ch.Send(ctx, &types.SendInput{ ChatID: msg.ChatID, Text: fmt.Sprintf("You said: %s", msg.Content), }) return err }) ch.OnCardAction(func(ctx context.Context, event *types.CardActionEvent) error { fmt.Printf("Card action: %s\n", event.ActionID) return nil }) ch.OnError(func(err error) { fmt.Printf("Channel error: %v\n", err) }) // Handle shutdown sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt) // Start channel in background go func() { ctx := context.Background() if err := ch.Start(ctx); err != nil { fmt.Printf("Start failed: %v\n", err) } }() // Wait for signal <-sigChan fmt.Println("Shutting down...") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() ch.Stop(ctx) } ``` -------------------------------- ### Configure Channel-based WebSocket Event Handling Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/quick-start-patterns.md Sets up a WebSocket client to listen for real-time events. Requires importing the channel and ws packages from the SDK. ```go import ( "github.com/larksuite/oapi-sdk-go/v3/channel" "github.com/larksuite/oapi-sdk-go/v3/channel/types" "github.com/larksuite/oapi-sdk-go/v3/ws" ) func setupChannel(client *lark.Client) error { wsClient := larkws.NewClient("app_id", "app_secret") ch := channel.NewChannel(client, wsClient) ch.OnReady(func() { log.Println("Channel connected") }) ch.OnMessage(func(ctx context.Context, msg *types.NormalizedMessage) error { log.Printf("Message from %s: %s", msg.UserID, msg.Content) // Echo message _, err := ch.Send(ctx, &types.SendInput{ ChatID: msg.ChatID, Text: fmt.Sprintf("You said: %s", msg.Content), }) return err }) ch.OnError(func(err error) { log.Printf("Channel error: %v", err) }) ctx := context.Background() return ch.Start(ctx) } ``` -------------------------------- ### Configure custom addons and update existing apps Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/README.md Demonstrates how to request specific scopes, events, and callbacks, or update an existing app by providing an AppID. ```go _, err := registration.RegisterApp(ctx, ®istration.Options{ Addons: ®istration.AppAddons{ Scopes: registration.AppAddonsScopes{ Tenant: []string{"im:message:send_as_bot"}, User: []string{"calendar:calendar:read"}, }, Events: registration.AppAddonsEvents{ Items: registration.AppAddonsEventItems{ Tenant: []string{"im.message.receive_v1"}, }, }, Callbacks: registration.AppAddonsCallbacks{ Items: []string{"card.action.trigger"}, }, }, CreateOnly: true, OnQRCode: func(info *registration.QRCodeInfo) { fmt.Println(info.URL) }, }) if err != nil { panic(err) } _, err = registration.RegisterApp(ctx, ®istration.Options{ AppID: "cli_xxx", Addons: ®istration.AppAddons{ Scopes: registration.AppAddonsScopes{ Tenant: []string{"drive:drive.metadata:readonly"}, }, }, OnQRCode: func(info *registration.QRCodeInfo) { fmt.Println(info.URL) }, }) if err != nil { panic(err) } ``` -------------------------------- ### Initialize Lark Client Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/quick-start-patterns.md Provides minimal and production-ready client configuration options. ```go package main import ( "context" lark "github.com/larksuite/oapi-sdk-go/v3" ) func main() { client := lark.NewClient("app_id", "app_secret") ctx := context.Background() // Use client... } ``` ```go import ( "context" "log" "os" "time" lark "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/core" ) func main() { client := lark.NewClient( "app_id", "app_secret", lark.WithLogLevel(larkcore.LogLevelInfo), lark.WithReqTimeout(30 * time.Second), lark.WithEnableTokenCache(true), lark.WithLogger(myCustomLogger()), lark.WithSource("my-app-v1.0"), ) ctx := context.Background() // Use client... } func myCustomLogger() larkcore.Logger { // Implement custom logger return nil } ``` -------------------------------- ### CreateThread Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Starts a new thread on a message. ```APIDOC ## func (t *thread) Create(ctx context.Context, req *CreateThreadReq, options ...larkcore.RequestOptionFunc) (*CreateThreadResp, error) ### Description Starts a new thread on a message. ### Parameters - **ParentMessageId** (string) - Required - The ID of the parent message. - **Title** (string) - Optional - The title of the thread. ### Request Example ```go resp, err := client.Im.V1.Thread.Create(ctx, &larkim.CreateThreadReq{ Body: &larkim.CreateThreadReqBody{ ParentMessageId: "om_xxx", Title: "Discussion", }, }) ``` ``` -------------------------------- ### GET /open-apis/im/v1/messages Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Lists messages in a chat. ```APIDOC ## GET /open-apis/im/v1/messages ### Description Lists messages in a chat. ### Method GET ### Endpoint /open-apis/im/v1/messages ### Parameters #### Query Parameters - **ContainerId** (string) - Required - Chat ID - **PageSize** (int) - Optional - Items per page (1-50) - **PageToken** (string) - Optional - Pagination cursor - **SortBy** (string) - Optional - Sort order ``` -------------------------------- ### Access Service via Client Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/service-pattern.md Initialize the client and access specific service modules like IM or Contact. ```go client := lark.NewClient("app_id", "app_secret") imService := client.Im // IM service contactService := client.Contact // Contact service ``` -------------------------------- ### Register a New Application Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Configures a new application with avatar, name, description, scopes, events, and callbacks. Includes error handling for registration failures. ```go result, err := registration.RegisterApp(ctx, ®istration.Options{ AppPreset: ®istration.AppPreset{ Avatar: []string{"https://example.com/logo.png"}, Name: "My Bot", Desc: "A helpful bot for team communication", }, Addons: ®istration.AppAddons{ Scopes: registration.AppAddonsScopes{ Tenant: []string{ "im:message:send_as_bot", "im:chat:readonly", }, User: []string{ "contact:user:email:read", }, }, Events: registration.AppAddonsEvents{ Items: registration.AppAddonsEventItems{ Tenant: []string{ "im.message.receive_v1", "card.action.trigger", }, }, }, Callbacks: registration.AppAddonsCallbacks{ Items: []string{"card.action.trigger"}, }, }, OnQRCode: func(info *registration.QRCodeInfo) { fmt.Println("Scan QR:", info.URL) }, }) if err != nil { var regErr *registration.RegisterAppError if errors.As(err, ®Err) { fmt.Printf("Registration failed: %s - %s\n", regErr.Code, regErr.Description) return } panic(err) } ``` -------------------------------- ### Get Chat Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Retrieves information about a specific chat. ```APIDOC ## Get Chat ### Description Gets chat information. ### Method GET ### Parameters #### Query Parameters - **ChatId** (string) - Required - The ID of the chat to retrieve ``` -------------------------------- ### GET /open-apis/im/v1/messages/{message_id} Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Retrieves a specific message by its ID. ```APIDOC ## GET /open-apis/im/v1/messages/{message_id} ### Description Retrieves a specific message by ID. ### Method GET ### Endpoint /open-apis/im/v1/messages/{message_id} ### Parameters #### Path Parameters - **message_id** (string) - Required - The ID of the message to retrieve ``` -------------------------------- ### Accessing Contact Service Resources Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/services-guide.md Demonstrates importing the contact service and retrieving a user by ID. ```go import "github.com/larksuite/oapi-sdk-go/v3/service/contact" // Get a user resp, err := client.Contact.V3.User.Get(ctx, &contact.GetUserReq{ UserId: "ou_xxx", UserIdType: contact.UserIdTypeOpenId, }) if err != nil { panic(err) } fmt.Printf("User: %s\n", resp.Data.Name) ``` -------------------------------- ### Get Channel Policy Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Retrieves the current policy configuration for the channel. ```go func (ch Channel) GetPolicy() PolicyConfig ``` -------------------------------- ### Configure client with AppType Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/constants-enums.md Sets the application type during client initialization. ```go client := lark.NewClient("app_id", "app_secret", lark.WithAppType(larkcore.AppTypeSelfBuilt), ) ``` -------------------------------- ### Get Chat Method Definition Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Method signature for retrieving chat information. ```go func (c *chat) Get(ctx context.Context, req *GetChatReq, options ...larkcore.RequestOptionFunc) (*GetChatResp, error) ``` -------------------------------- ### Initialize a New Channel Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Constructor signature for creating a new Channel instance using HTTP and WebSocket clients. ```go func NewChannel(client *lark.Client, wsClient *larkws.Client, opts ...types.ChannelOption) types.Channel ``` -------------------------------- ### Initialize the Lark Client Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/README.md Create a thread-safe client instance. Reusing this instance is recommended for performance. ```go client := lark.NewClient("app_id", "app_secret", lark.WithLogLevel(larkcore.LogLevelInfo), lark.WithReqTimeout(30 * time.Second), ) ``` -------------------------------- ### Get Message Method and Request Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Method signature and request structure for retrieving a message by ID. ```go func (m *message) Get(ctx context.Context, req *GetMessageReq, options ...larkcore.RequestOptionFunc) (*GetMessageResp, error) type GetMessageReq struct { MessageId string // Required } ``` -------------------------------- ### Select base template with Preset Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/README.md Configures the base template for app creation using the Preset field in AppAddons. ```go preset := false _, err := registration.RegisterApp(ctx, ®istration.Options{ Addons: ®istration.AppAddons{ Preset: &preset, }, OnQRCode: func(info *registration.QRCodeInfo) { fmt.Println(info.URL) }, }) if err != nil { panic(err) } ``` -------------------------------- ### Configure Application Type Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Sets the application type to either self-built or marketplace. ```go client := lark.NewClient("app_id", "app_secret", lark.WithAppType(larkcore.AppTypeSelfBuilt), ) ``` ```go client := lark.NewClient("app_id", "app_secret", lark.WithMarketplaceApp(), ) ``` -------------------------------- ### Manage OAuth and Tokens Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/README.md The SDK handles token lifecycle automatically, though manual registration is available for specific flows. ```go // Automatic - SDK handles token refresh resp, err := client.Im.V1.Message.Create(ctx, req) // Manual - OAuth device flow result, err := registration.RegisterApp(ctx, opts) // Returns: ClientID, ClientSecret, UserInfo ``` -------------------------------- ### Register a new app with one-click Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/README.md Uses registration.RegisterApp to initiate the device authorization flow and retrieve app credentials. ```go package main import ( "context" "errors" "fmt" "time" lark "github.com/larksuite/oapi-sdk-go/v3" "github.com/larksuite/oapi-sdk-go/v3/scene/registration" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() result, err := registration.RegisterApp(ctx, ®istration.Options{ OnQRCode: func(info *registration.QRCodeInfo) { fmt.Printf("open or scan this url: %s\n", info.URL) fmt.Printf("the link expires in %d seconds\n", info.ExpireIn) }, OnStatusChange: func(info *registration.StatusChangeInfo) { // status: polling | slow_down | domain_switched fmt.Printf("registration status: %s", info.Status) if info.Interval > 0 { fmt.Printf(", next poll after %d seconds", info.Interval) } fmt.Println() }, }) if err != nil { var regErr *registration.RegisterAppError if errors.As(err, ®Err) { fmt.Printf("register app failed: code=%s, description=%s\n", regErr.Code, regErr.Description) return } panic(err) } fmt.Println("App ID:", result.ClientID) fmt.Println("App Secret:", result.ClientSecret) client := lark.NewClient(result.ClientID, result.ClientSecret) _ = client } ``` -------------------------------- ### Get Progress Method Signature Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/im-service.md Defines the method signature for retrieving the status of a batch message operation. ```go func (bm *batchMessage) GetProgress(ctx context.Context, req *GetProgressBatchMessageReq, options ...larkcore.RequestOptionFunc) (*GetProgressBatchMessageResp, error) ``` -------------------------------- ### Set Helpdesk Credentials Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Sets credentials for Helpdesk API access; the SDK automatically handles Base64 encoding. ```go client := lark.NewClient("app_id", "app_secret", lark.WithHelpdeskCredential("helpdesk_id", "helpdesk_token"), ) ``` -------------------------------- ### Use User ID Type in API Request Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/constants-enums.md Example of specifying a user ID type when fetching user information. ```go resp, err := client.Contact.V3.User.Get(ctx, &contact.GetUserReq{ UserId: "ou_xxx", UserIdType: contact.UserIdTypeOpenId, }) ``` -------------------------------- ### NewClient Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/client-reference.md Creates and returns a fully initialized SDK client. The client automatically initializes all service modules, token management, caching, and HTTP handling. ```APIDOC ## NewClient ### Description Creates and returns a fully initialized SDK client. The client automatically initializes all service modules, token management, caching, and HTTP handling. ### Signature `func NewClient(appId, appSecret string, options ...ClientOptionFunc) *Client` ### Parameters - **appId** (string) - Required - The application ID from Feishu Developer Console - **appSecret** (string) - Required - The application secret from Feishu Developer Console - **options** (...ClientOptionFunc) - Optional - Variadic configuration option functions ### Returns - ***Client** - Fully initialized SDK client ready for API calls ``` -------------------------------- ### Define Service Structure Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/service-pattern.md The service entry point defines the structure for versioned API modules and provides a constructor for initialization. ```go // service/{service_name}/service.go type Service struct { *v1.V1 V2 *v2.V2 } func NewService(config *larkcore.Config) *Service { return &Service{ V1: v1.New(config), V2: v2.New(config), } } ``` -------------------------------- ### Define AppPreset struct Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Defines the application profile information including avatar, name, and description. ```go type AppPreset struct { Avatar []string // 1-6 avatar URLs Name string // Application name Desc string // Application description } ``` -------------------------------- ### Get Bot Identity Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/doc/channel.md Retrieve cached bot identity information including OpenID, Name, and ActivateStatus using `ch.GetBotIdentity`. ```go // Resolve and cache bot identity bot := ch.GetBotIdentity(ctx) ``` -------------------------------- ### Handle Channel Errors Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/channel-reference.md Example of handling specific error types during a send operation, including retry logic for rate limits. ```go result, err := ch.Send(ctx, input) if err != nil { switch err { case types.ErrRateLimited: fmt.Println("Rate limited, retrying...") time.Sleep(time.Second) return ch.Send(ctx, input) case types.ErrConnectionClosed: fmt.Println("Connection closed, reconnecting...") default: fmt.Printf("Send failed: %v\n", err) } return err } ``` -------------------------------- ### Configure Registration Options for Self-hosted Feishu Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Use this configuration when deploying the SDK within a self-hosted Feishu environment. ```go opts := ®istration.Options{ LarkDomain: "https://your-domain.feishu.cn", // ... other options } ``` -------------------------------- ### Access Admin Service Operations Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/services-guide.md Use these methods to list admin info and get organization details via the V1 API. ```go client.Admin.V1.Admin.List(ctx, req) client.Admin.V1.Org.Get(ctx, req) ``` -------------------------------- ### OnQRCode Callback Implementation Source: https://github.com/larksuite/oapi-sdk-go/blob/v3_main/_autodocs/registration-reference.md Required callback invoked when the QR code is ready for user scanning. ```go OnQRCode: func(info *QRCodeInfo) { fmt.Printf("Scan this QR code: %s\n", info.URL) fmt.Printf("Expires in: %d seconds\n", info.ExpireIn) } ```