lark Go SDK

repository·master·Indexed 19 days ago

https://github.com/chyroc/lark

A comprehensive Go SDK for the Feishu/Lark Open API. It supports all API endpoints, event callbacks, and various application types, including ISV and self-built applications. The SDK provides modules for Contact, CoreHR, Directory, Drive, Chat, Hire, and Helpdesk, with features such as UserAccessToken authentication, mocking capabilities for testing, and a pluggable Logger interface.

Tokens
121.3K
Snippets
304
Records
382
Agent score
64%

What's inside lark

  1. Overview of supported APIs and events in lark

    master
    The lark project provides a comprehensive set of interfaces for interacting with the platform. As of the current version, the library supports a total of 1,630 APIs and 153 events. These interfaces allow developers to perform various actions and respond to platform-triggered events within the Lark ecosystem.
  2. Overview of Lark (Feishu) Open API Go SDK

    master

    The lark package is a Go SDK for the Feishu/Lark Open API. It provides comprehensive support for interacting with Lark services, including all Open APIs and Event Callbacks.

    Key features include:

    • Support for both ISV (Independent Software Vendor) and self-built applications.
    • Support for UserAccessToken authentication.
    • Mocking capabilities to facilitate testing.
    • Pluggable Logger interface.
    • Automated API and documentation updates via code generation.
  3. Overview of the Lark/Feishu Go SDK

    master

    The lark package is a Go SDK for the Lark (Feishu) open platform. It provides comprehensive support for all open platform APIs and event callbacks.

    Key features include:

    • Support for a wide range of APIs and events.
    • Support for both ISV (Independent Software Vendor) and self-built apps.
    • Mock support to facilitate testing.
    • Support for custom Logger interfaces.
    • Support for UserAccessToken authentication.
    • Automatically generated code to ensure timely updates with the official API and documentation.
  4. Explore Lark Support APIs by category

    master

    The Lark SDK provides a wide range of APIs categorized by functional domains. Developers can interact with various services including Access Control (ACS), Artificial Intelligence (AI), Application Platform as a Service (APaaS), Administrative tools, Aily (AI assistant), AppLink (deep linking), Application management, Approvals, Attendance, Authentication, Baike (knowledge base), Bitable (database), Bots, Calendar, Cardkit, Chat, and Compensation.

    Common functional areas include:

    • AI: Image recognition, text translation, and speech processing.
    • Bitable: CRUD operations for records, fields, tables, and views.
    • Chat: Managing chat rooms, members, tabs, and announcements.
    • Approval: Managing approval instances, tasks, and comments.
    • Auth: Obtaining access tokens and user information.
    • Calendar: Managing calendars, events, and attendees.
  5. Initialize a lark client

    master

    Use lark.New with functional options to configure the client based on your application type and region.

    Common configurations include:

    • Standard App/Bot: Use lark.WithAppCredential("<APP_ID>", "<APP_SECRET>").
    • Larksuite (Non-China): Set the base URLs using lark.WithOpenBaseURL("https://open.larksuite.com") and lark.WithWWWBaseURL("https://www.larksuite.com").
    • Event Callbacks: Provide encryption keys and verification tokens using lark.WithEventCallbackVerify("<ENCRYPT_KEY>", "<VERIFICATION_TOKEN>").
    • Helpdesk App: Use lark.WithHelpdeskCredential("<HELPDESK_ID>", "HELPDESK_TOKEN").
    • ISV App: Enable ISV mode with lark.WithISV(true) and specify a store with lark.WithStore("<NEW_STORE>").
    // Standard App
    cli := lark.New(lark.WithAppCredential("<APP_ID>", "<APP_SECRET>"))
    
    // Larksuite (non-China region)
    cli := lark.New(
        lark.WithAppCredential("<APP_ID>", "<APP_SECRET>"),
        lark.WithOpenBaseURL("https://open.larksuite.com"),
        lark.WithWWWBaseURL("https://www.larksuite.com"),
    )
    
    // Helpdesk
    cli := lark.New(
        lark.WithAppCredential("<APP_ID>", "<APP_SECRET>"),
        lark.WithHelpdeskCredential("<HELPDESK_ID>", "HELPDESK_TOKEN"),
    )
  6. Handle event callbacks

    master

    To handle incoming events (like receiving a message), register a handler using the EventCallback service and then use ListenCallback within an HTTP server to process the requests.

    1. Initialize the client with lark.WithEventCallbackVerify.
    2. Use a specific handler method (e.g., HandlerEventIMMessageReceiveV1) to define the logic for a specific event type.
    3. Use cli.EventCallback.ListenCallback inside an HTTP handler to route the request body to the registered event handlers.
    cli := lark.New(
        lark.WithAppCredential("<APP_ID>", "<APP_SECRET>"),
        lark.WithEventCallbackVerify("<ENCRYPT_KEY>", "<VERIFICATION_TOKEN>"),
    )
    
    // handle message callback
    cli.EventCallback.HandlerEventIMMessageReceiveV1(func(ctx context.Context, cli *lark.Lark, schema string, header *lark.EventV2Header, event *lark.EventV2IMMessageReceiveV1) (string, error) {
        _, _, err := cli.Message.Reply(event.Message.MessageID).SendText(ctx, "hi, "+event.Message.Content)
        return "", err
    })
    
    http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
        cli.EventCallback.ListenCallback(r.Context(), r.Body, w)
    })
    
    log.Fatal(http.ListenAndServe(":9726", nil))
  7. Use ISV (Independent Software Vendor) mode

    master

    For ISV applications, initialize the client with lark.WithISV(true) and specify your store with lark.WithStore("<NEW_STORE>"). You can then switch contexts to a specific tenant using cli.WithTenant("<TENANT_KEY>") to perform actions on behalf of that tenant.

    cli := lark.New(
        lark.WithAppCredential("<APP_ID>", "<APP_SECRET>"),
        lark.WithISV(true),
        lark.WithStore("<NEW_STORE>"),
    )
    
    tenantKey1Cli := cli.WithTenant("<TENANT_KEY_1>")
    resp, _, err := tenantKey1Cli.Chat.CreateChat(ctx, &lark.CreateChatReq{
        Name: ptrString("<CHAT_NAME_1>"),
    })
  8. Understand GetAttendanceUserStatsDataResp structure

    master

    The response object containing user attendance statistics.

    Top-level fields:

    • UserDatas: A list of GetAttendanceUserStatsDataRespUserData (max 1000).
    • InvalidUserList: A list of user IDs that the caller does not have permission to access.

    User Data (GetAttendanceUserStatsDataRespUserData):

    • Name: User's name.
    • UserID: User's ID.
    • Datas: A list of statistical data points (GetAttendanceUserStatsDataRespUserDataData).

    Statistical Data Point (GetAttendanceUserStatsDataRespUserDataData):

    • Code: Field identifier.
    • Value: The data value.
    • Title: The field title.
    • Features: Additional attributes (e.g., clock-in results, leave application times).
    • DurationNum: A map of time units (Day, HalfDay, Hour, HalfHour, Minute) to duration values.
    type GetAttendanceUserStatsDataResp struct {
    	UserDatas       []*GetAttendanceUserStatsDataRespUserData `json:"user_datas,omitempty"` 
    	InvalidUserList []string                                  `json:"invalid_user_list,omitempty"` 
    }
    
    type GetAttendanceUserStatsDataRespUserData struct {
    	Name   string                                        `json:"name,omitempty"`    
    	UserID string                                        `json:"user_id,omitempty"` 
    	Datas  []*GetAttendanceUserStatsDataRespUserDataData `json:"datas,omitempty"`   
    }
    
    type GetAttendanceUserStatsDataRespUserDataData struct {
    	Code        string                                                 `json:"code,omitempty"`         
    	Value       string                                                 `json:"value,omitempty"`        
    	Features    []*GetAttendanceUserStatsDataRespUserDataDataFeature   `json:"features,omitempty"`     
    	Title       string                                                 `json:"title,omitempty"`       
    	DurationNum *GetAttendanceUserStatsDataRespUserDataDataDurationNum `json:"duration_num,omitempty"` 
    }
  9. Understand GetAdminBadgeGrantListResp structure

    master

    The GetAdminBadgeGrantListResp contains the list of grants and pagination metadata:

    • Grants: A slice of *GetAdminBadgeGrantListRespGrant objects representing the grant list.
    • PageToken: A string used for the next page of results. Only returned if HasMore is true.
    • HasMore: A boolean indicating if there are more items to fetch.
  10. Configure rule details for badge grants

    master

    When updating a badge grant, you can use the UpdateAdminBadgeGrantReqRuleDetail struct to manage the timing and lifecycle of the grant. This is particularly important when GrantType is set to manual selection.

    Fields in UpdateAdminBadgeGrantReqRuleDetail:

    • EffectiveTime: The start timestamp. For manual types, this must be the midnight timestamp of the day in the specified TimeZone (e.g., 1649606400 for Asia/Shanghai).
    • ExpirationTime: The end timestamp.
      • Must not exceed EffectiveTime + 100 years.
      • For non-permanent grants, this must be the 23:59:59 timestamp of the day in the specified TimeZone (e.g., 1649692799).
      • For permanent grants, set this to 0.
    • Anniversary: The work anniversary day (range 1 to 60) used for grants based on hire date.
    • EffectivePeriod: The validity period for hire-date-based grants (e.g., 1 for one year, 2 for permanent).
    rule := &lark.UpdateAdminBadgeGrantReqRuleDetail{
        EffectiveTime:  ptrString("1649606400"),
        ExpirationTime: ptrString("1649692799"),
    }
    
    req := &lark.UpdateAdminBadgeGrantReq{
        // ... other fields
        RuleDetail: rule,
    }
  11. Manage messages (Delete)

    master

    Delete an existing message by its ID using cli.Message.DeleteMessage(ctx, &lark.DeleteMessageReq{...}).

    cli := lark.New(lark.WithAppCredential("<APP_ID>", "<APP_SECRET>"))
    
    resp, _, err := cli.Message.DeleteMessage(ctx, &lark.DeleteMessageReq{
        MessageID: "<MESSAGE_ID>",
    })
    fmt.Println(resp, err)