LINE Messaging API SDK for Go

repository·master·Indexed 21 days ago

https://github.com/line/line-bot-sdk-go

A Go library for developing LINE bots, providing tools for parsing webhooks, managing Messaging API interactions, and handling event types. The v8 SDK supports sending and replying to messages, managing channel access tokens, and interacting with LIFF, insight, and shop modules. It requires Go 1.25 or later.

Tokens
4.6K
Snippets
9
Records
9
Agent score
26%

What's inside line-bot-sdk-go

  1. Import the LINE Messaging API SDK packages

    master

    To use the full suite of features, import the following packages in your Go code:

    import (
    	"github.com/line/line-bot-sdk-go/v8/linebot"
    	"github.com/line/line-bot-sdk-go/v8/linebot/channel_access_token"
    	"github.com/line/line-bot-sdk-go/v8/linebot/insight"
    	"github.com/line/line-bot-sdk-go/v8/linebot/liff"
    	"github.com/line/line-bot-sdk-go/v8/linebot/manage_audience"
    	"github.com/line/line-bot-sdk-go/v8/linebot/messaging_api"
    	"github.com/line/line-bot-sdk-go/v8/linebot/module"
    	"github.com/line/line-bot-sdk-go/v8/linebot/module_attach"
    	"github.com/line/line-bot-sdk-go/v8/linebot/shop"
    	"github.com/line/line-bot-sdk-go/v8/linebot/webhook"
    )
  2. Parse incoming Webhook requests

    master

    Use webhook.ParseRequest() to parse incoming HTTP requests from LINE. This method validates the signature using your LINE_CHANNEL_SECRET and returns a slice of event objects.

    import (
    	"os"
    	"github.com/line/line-bot-sdk-go/v8/linebot/webhook"
    )
    
    // req is the *http.Request from your web server
    cb, err := webhook.ParseRequest(os.Getenv("LINE_CHANNEL_SECRET"), req)
    if err != nil {
    	// Handle error
    }
    
    // Iterate through events and handle them via type assertion
    for _, event := range cb.Events {
    	switch e := event.(type) {
    	case webhook.MessageEvent:
    		// Handle message event
    	case webhook.StickerMessageContent:
    		// Handle sticker content
    	}
    }
  3. Configure the Messaging API client

    master

    Initialize the messaging API client using your LINE Channel Token. You can also provide a custom *http.Client using the messaging_api.WithHTTPClient option.

    import (
    	"os"
    	"net/http"
    	"github.com/line/line-bot-sdk-go/v8/linebot/messaging_api"
    )
    
    func main() {
    	// Basic configuration
    	bot, err := messaging_api.NewMessagingApiAPI(
    		os.Getenv("LINE_CHANNEL_TOKEN"),
    	)
    
    	// Configuration with custom http.Client
    	client := &http.Client{}
    	botWithClient, err := messaging_api.NewMessagingApiAPI(
    		os.Getenv("LINE_CHANNEL_TOKEN"),
    		messaging_api.WithHTTPClient(client),
    	)
    }
  4. Send and Reply to messages

    master

    You can send messages using a PushMessage (requires a User, Group, or Room ID) or ReplyMessage (requires a ReplyToken).

    // Reply to a message using a ReplyToken
    bot.ReplyMessage(
    	&messaging_api.ReplyMessageRequest{
    		ReplyToken: e.ReplyToken,
    		Messages: []messaging_api.MessageInterface{
    			messaging_api.TextMessage{
    				Text: "replyMessage",
    			},
    		},
    	},
    )
    
    // Push a message using a User ID
    bot.PushMessage(
    	&messaging_api.PushMessageRequest{
    		To: "U.......",
    		Messages: []messaging_api.MessageInterface{
    			messaging_api.TextMessage{
    				Text: "pushMessage",
    			},
    		},
    	},
    	"", // x-line-retry-key
    )
  5. Retrieve response headers and error details with WithHttpInfo

    master

    To access response headers (like x-line-request-id) or inspect detailed error bodies, use the WithHttpInfo suffix on API methods (e.g., ReplyMessageWithHttpInfo).

    // Get response headers
    resp, _, _ := bot.ReplyMessageWithHttpInfo(
    	&messaging_api.ReplyMessageRequest{
    		ReplyToken: replyToken,
    		Messages: []messaging_api.MessageInterface{
    			messaging_api.TextMessage{Text: "Hello, world"},
    		},
    	},
    )
    log.Printf("status code: (%v), x-line-request-id: (%v)", resp.StatusCode, resp.Header.Get("x-line-request-id"))
    
    // Get detailed error messages for 4xx responses
    resp, _, err := bot.ReplyMessageWithHttpInfo(
        &messaging_api.ReplyMessageRequest{
            ReplyToken: replyToken + "invalid",
            Messages: []messaging_api.MessageInterface{
                messaging_api.TextMessage{Text: "Hello, world"},
            },
        },
    )
    if err != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 {
        decoder := json.NewDecoder(resp.Body)
        errorResponse := &messaging_api.ErrorResponse{}
        if err := decoder.Decode(&errorResponse); err != nil {
            log.Fatal(err)
        }
        log.Printf("error response: (%v)", errorResponse)
    }
  6. Initialize a new LINE Bot client

    master

    Use linebot.New to create a new client instance. You must provide a channelSecret and a channelToken. You can optionally pass ClientOption functions to customize the client, such as providing a custom http.Client or overriding the API base endpoints.

    Note: The Client type and New function are marked as deprecated. It is recommended to use the OpenAPI-based classes instead for newer projects.

    import "github.com/line/line-bot-sdk-go/linebot"
    
    client, err := linebot.New("YOUR_CHANNEL_SECRET", "YOUR_CHANNEL_ACCESS_TOKEN")
    if err != nil {
        // handle error
    }
  7. Configure the LINE Bot client with options

    master

    The New function accepts variadic ClientOption arguments to modify the default client behavior:

    • WithHTTPClient(c *http.Client): Replaces the default http.DefaultClient with a custom HTTP client.
    • WithEndpointBase(endpointBase string): Overrides the default APIEndpointBase (https://api.line.me).
    • WithEndpointBaseData(endpointBaseData string): Overrides the default APIEndpointBaseData (https://api-data.line.me).
    import (
    	"net/http"
    	"time"
    	"github.com/line/line-bot-sdk-go/linebot"
    )
    
    customHTTPClient := &http.Client{
    	Timeout: time.Second * 10,
    }
    
    client, err := linebot.New(
    	"YOUR_CHANNEL_SECRET",
    	"YOUR_CHANNEL_ACCESS_TOKEN",
    	linebot.WithHTTPClient(customHTTPClient),
    	linebot.WithEndpointBase("https://my-proxy.com"),
    )
  8. Reference: LINE Messaging API Endpoints

    master

    The SDK defines several constant endpoints used for interacting with the LINE Messaging API. These are used internally by the client to construct request URLs.

    // APIEndpoint constants
    const (
    	APIEndpointBase     = "https://api.line.me"
    	APIEndpointBaseData = "https://api-data.line.me"
    
    	APIEndpointPushMessage                = "/v2/bot/message/push"
    	APIEndpointBroadcastMessage           = "/v2/bot/message/broadcast"
    	APIEndpointReplyMessage               = "/v2/bot/message/reply"
    	APIEndpointMulticast                  = "/v2/bot/message/multicast"
    	APIEndpointNarrowcast                 = "/v2/bot/message/narrowcast"
    	APIEndpointValidatePushMessage        = "/v2/bot/message/validate/push"
    	APIEndpointValidateBroadcastMessage   = "/v2/bot/message/validate/broadcast"
    	APIEndpointValidateReplyMessage       = "/v2/bot/message/validate/reply"
    	APIEndpointValidateMulticastMessage   = "/v2/bot/message/validate/multicast"
    	APIEndpointValidateNarrowcastMessage  = "/v2/bot/message/validate/narrowcast"
    	APIEndpointGetMessageContent          = "/v2/bot/message/%s/content"
    	APIEndpointGetMessageQuota            = "/v2/bot/message/quota"
    	APIEndpointGetMessageConsumption      = "/v2/bot/message/quota/consumption"
    	APIEndpointGetMessageQuotaConsumption = "/v2/bot/message/quota/consumption"
    	APIEndpointLeaveGroup                 = "/v2/bot/group/%s/leave"
    	APIEndpointLeaveRoom                  = "/v2/bot/room/%s/leave"
    	APIEndpointGetProfile                 = "/v2/bot/profile/%s"
    	APIEndpointGetFollowerIDs             = "/v2/bot/followers/ids"
    	APIEndpointGetGroupMemberProfile      = "/v2/bot/group/%s/member/%s"
    	APIEndpointGetRoomMemberProfile       = "/v2/bot/room/%s/member/%s"
    	APIEndpointGetGroupMemberIDs          = "/v2/bot/group/%s/members/ids"
    	APIEndpointGetRoomMemberIDs           = "/v2/bot/room/%s/members/ids"
    	APIEndpointGetGroupMemberCount        = "/v2/bot/group/%s/members/count"
    	APIEndpointGetRoomMemberCount         = "/v2/bot/room/%s/members/count"
    	APIEndpointGetGroupSummary            = "/v2/bot/group/%s/summary"
    	APIEndpointCreateRichMenu             = "/v2/bot/richmenu"
    	APIEndpointGetRichMenu                = "/v2/bot/richmenu/%s"
    	APIEndpointListRichMenu               = "/v2/bot/richmenu/list"
    	APIEndpointDeleteRichMenu             = "/v2/bot/richmenu/%s"
    	APIEndpointGetUserRichMenu            = "/v2/bot/user/%s/richmenu"
    	APIEndpointLinkUserRichMenu           = "/v2/bot/user/%s/richmenu/%s"
    	APIEndpointUnlinkUserRichMenu         = "/v2/bot/user/%s/richmenu"
    	APIEndpointSetDefaultRichMenu         = "/v2/bot/user/all/richmenu/%s"
    	APIEndpointDefaultRichMenu            = "/v2/bot/user/all/richmenu"
    	APIEndpointDownloadRichMenuImage      = "/v2/bot/richmenu/%s/content"
    	APIEndpointUploadRichMenuImage        = "/v2/bot/richmenu/%s/content"
    	APIEndpointBulkLinkRichMenu           = "/v2/bot/richmenu/bulk/link"
    	APIEndpointBulkUnlinkRichMenu         = "/v2/bot/richmenu/bulk/unlink"
    	APIEndpointValidateRichMenuObject     = "/v2/bot/richmenu/validate"
    
    	APIEndpointCreateRichMenuAlias = "/v2/bot/richmenu/alias"
    	APIEndpointGetRichMenuAlias    = "/v2/bot/richmenu/alias/%s"
    	APIEndpointUpdateRichMenuAlias = "/v2/bot/richmenu/alias/%s"
    	APIEndpointDeleteRichMenuAlias = "/v2/bot/richmenu/alias/%s"
    	APIEndpointListRichMenuAlias   = "/v2/bot/richmenu/alias/list"
    
    	APIEndpointGetAllLIFFApps = "/liff/v1/apps"
    	APIEndpointAddLIFFApp     = "/liff/v1/apps"
    	APIEndpointUpdateLIFFApp  = "/liff/v1/apps/%s/view"
    	APIEndpointDeleteLIFFApp  = "/liff/v1/apps/%s"
    
    	APIEndpointLinkToken = "/v2/bot/user/%s/linkToken"
    
    	APIEndpointGetMessageDelivery = "/v2/bot/message/delivery/%s"
    	APIEndpointGetMessageProgress = "/v2/bot/message/progress/%s"
    	APIEndpointInsight            = "/v2/bot/insight/%s"
    	APIEndpointGetBotInfo         = "/v2/bot/info"
    
    	APIEndpointIssueAccessToken  = "/v2/oauth/accessToken"
    	APIEndpointRevokeAccessToken = "/v2/oauth/revoke"
    	APIEndpointVerifyAccessToken = "/v2/oauth/verify"
    
    	APIEndpointIssueAccessTokenV2  = "/oauth2/v2.1/token"
    	APIEndpointGetAccessTokensV2   = "/oauth2/v2.1/tokens/kid"
    	APIEndpointRevokeAccessTokenV2 = "/oauth2/v2.1/revoke"
    
    	APIEndpointGetWebhookInfo     = "/v2/bot/channel/webhook/endpoint"
    	APIEndpointSetWebhookEndpoint = "/v2/bot/channel/webhook/endpoint"
    	APIEndpointTestWebhook        = "/v2/bot/channel/webhook/test"
    
    	APIAudienceGroupUpload            = "/v2/bot/audienceGroup/upload"
    	APIAudienceGroupUploadByFile      = "/v2/bot/audienceGroup/upload/byFile"
    	APIAudienceGroupClick             = "/v2/bot/audienceGroup/click"
    	APIAudienceGroupIMP               = "/v2/bot/audienceGroup/imp"
    	APIAudienceGroupUpdateDescription = "/v2/bot/audienceGroup/%d/updateDescription"
    	APIAudienceGroupActivate          = "/v2/bot/audienceGroup/%d/activate"
    	APIAudienceGroup                  = "/v2/bot/audienceGroup/%d"
    	APIAudienceGroupList              = "/v2/bot/audienceGroup/list"
    	APIAudienceGroupAuthorityLevel    = "/v2/bot/audienceGroup/authorityLevel"
    )