### Install LINE Bot SDK for Go Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Use `go get` to install the LINE Bot SDK for Go. Ensure you are using Go 1.25 or later. ```bash go get -u github.com/line/line-bot-sdk-go/v8/linebot ``` -------------------------------- ### Example: Get Bot Info Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Demonstrates how to call the GetBotInfo function and log the bot's user ID and display name. ```go botInfo, err := bot.GetBotInfo() if err == nil { log.Printf("Bot ID: %s, Name: %s", botInfo.UserId, botInfo.DisplayName) } ``` -------------------------------- ### Install LINE Messaging API SDK for Go Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Use this command to install the SDK. Requires Go 1.25 or later. ```sh $ go get -u github.com/line/line-bot-sdk-go/v8/linebot ``` -------------------------------- ### 5-Minute Example: Basic LINE Bot Implementation Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md This Go program demonstrates a basic LINE bot that handles incoming messages and echoes them back. It requires LINE_CHANNEL_TOKEN and LINE_CHANNEL_SECRET environment variables to be set. ```go package main import ( "errors" "log" "net/http" "os" "github.com/line/line-bot-sdk-go/v8/linebot/messaging_api" "github.com/line/line-bot-sdk-go/v8/linebot/webhook" ) func main() { // Initialize bot with channel token bot, _ := messaging_api.NewMessagingApiAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) // Handle incoming webhooks http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { // Parse request and validate signature cb, err := webhook.ParseRequest( os.Getenv("LINE_CHANNEL_SECRET"), r, ) if err != nil { if errors.Is(err, webhook.ErrInvalidSignature) { w.WriteHeader(http.StatusBadRequest) } return } // Handle events for _, event := range cb.Events { if msg, ok := event.(*webhook.MessageEvent); ok { if text, ok := msg.Message.(webhook.TextMessageContent); ok { // Echo the message back bot.ReplyMessage( &messaging_api.ReplyMessageRequest{ ReplyToken: msg.ReplyToken, Messages: []messaging_api.MessageInterface{ messaging_api.TextMessage{ Text: text.Text, }, }, }, ) } } } w.WriteHeader(http.StatusOK) }) http.ListenAndServe(":8080", nil) } ``` -------------------------------- ### Validate Configuration at Startup Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/configuration.md Ensure all required configuration values, such as environment variables for LINE channel tokens and secrets, are present before starting the application. This prevents runtime errors. ```go func validateConfig() error { if os.Getenv("LINE_CHANNEL_TOKEN") == "" { return errors.New("LINE_CHANNEL_TOKEN is required") } if os.Getenv("LINE_CHANNEL_SECRET") == "" { return errors.New("LINE_CHANNEL_SECRET is required") } return nil } func main() { if err := validateConfig(); err != nil { log.Fatal(err) } // Start application } ``` -------------------------------- ### Initialize Messaging API with Environment Variable Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/configuration.md Example of initializing the Messaging API by reading the channel token from the LINE_CHANNEL_TOKEN environment variable. Ensures the token is set before proceeding. ```go func initBot() (*messaging_api.MessagingApiAPI, error) { channelToken := os.Getenv("LINE_CHANNEL_TOKEN") if channelToken == "" { return nil, errors.New("LINE_CHANNEL_TOKEN not set") } return messaging_api.NewMessagingApiAPI(channelToken) } ``` -------------------------------- ### Basic Echo Bot Example Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md This Go program sets up a webhook endpoint that listens for incoming messages. It parses the webhook request, validates the signature, and if it's a text message, it echoes the message back to the user. Ensure your LINE_CHANNEL_TOKEN and LINE_CHANNEL_SECRET environment variables are set. ```go package main import ( "errors" "log" "net/http" "os" "github.com/line/line-bot-sdk-go/v8/linebot/messaging_api" "github.com/line/line-bot-sdk-go/v8/linebot/webhook" ) func main() { // Initialize bot client bot, err := messaging_api.NewMessagingApiAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) if err != nil { log.Fatal(err) } // Setup webhook endpoint http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { // Parse and validate webhook request cb, err := webhook.ParseRequest( os.Getenv("LINE_CHANNEL_SECRET"), r, ) if err != nil { if errors.Is(err, webhook.ErrInvalidSignature) { w.WriteHeader(http.StatusBadRequest) } else { w.WriteHeader(http.StatusInternalServerError) } return } // Handle events for _, event := range cb.Events { switch e := event.(type) { case *webhook.MessageEvent: switch message := e.Message.(type) { case webhook.TextMessageContent: // Echo the message back bot.ReplyMessage( &messaging_api.ReplyMessageRequest{ ReplyToken: e.ReplyToken, Messages: []messaging_api.MessageInterface{ messaging_api.TextMessage{ Text: message.Text, }, }, }, ) } } } w.WriteHeader(http.StatusOK) }) port := os.Getenv("PORT") if port == "" { port = "8080" } log.Printf("Server listening on port %s", port) log.Fatal(http.ListenAndServe(":"+port, nil)) } ``` -------------------------------- ### Get Room Summary Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves summary information about a room using its ID. ```go func (client *MessagingApiAPI) GetRoomSummary(roomId string) (*RoomSummaryResponse, error) ``` -------------------------------- ### Get All LIFF Apps Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Retrieves all LIFF apps for the channel. Use this to list all available LIFF applications. ```go apps, err := liffClient.GetAllLIFFApps() if err == nil { for _, app := range apps.Apps { log.Printf("LIFF App: %s - %s", app.LiffId, app.View.Url) } } ``` -------------------------------- ### Import Guide for SDK Modules Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/MODULES.md Shows how to import various modules from the LINE Messaging API SDK for Go. This includes core messaging, webhook handling, LIFF apps, and analytics. ```go import ( // Core messaging "github.com/line/line-bot-sdk-go/v8/linebot/messaging_api" // Webhook handling "github.com/line/line-bot-sdk-go/v8/linebot/webhook" // Rich menus (part of messaging_api) // LIFF apps "github.com/line/line-bot-sdk-go/v8/linebot/liff" // Analytics "github.com/line/line-bot-sdk-go/v8/linebot/insight" // Audience management "github.com/line/line-bot-sdk-go/v8/linebot/manage_audience" // Token management "github.com/line/line-bot-sdk-go/v8/linebot/channel_access_token" ) ``` -------------------------------- ### Example Webhook Handler in Go Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md This snippet demonstrates how to set up an HTTP handler to process incoming webhook events from the LINE platform. It parses the request, checks for errors, and iterates through events. Ensure you have your channel secret configured. ```go http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { cb, err := webhook.ParseRequest(channelSecret, r) if err != nil { w.WriteHeader(http.StatusBadRequest) return } for _, event := range cb.Events { // Process event } w.WriteHeader(http.StatusOK) }) ``` -------------------------------- ### Set Environment Variables for LINE Bot Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Configure your LINE channel access token, channel secret, and port using environment variables. This is the recommended setup method. ```bash export LINE_CHANNEL_TOKEN="your_channel_access_token" export LINE_CHANNEL_SECRET="your_channel_secret" export PORT=8080 ``` -------------------------------- ### Handle Different Message Types Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Process incoming messages based on their type. This example shows how to log text messages and download image content. ```go switch message := event.Message.(type) { case webhook.TextMessageContent: log.Printf("Text: %s", message.Text) case webhook.ImageMessageContent: // Download image content, _ := bot.GetMessageContent(message.Id) defer content.Close() case webhook.StickerMessageContent: log.Printf("Sticker: %s", message.StickerId) case webhook.LocationMessageContent: log.Printf("Location: %f, %f", message.Latitude, message.Longitude) case webhook.FileMessageContent: log.Printf("File: %s (%d bytes)", message.FileName, message.FileSize) } ``` -------------------------------- ### Processing Message Events Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/webhook.md An example of how to iterate through received events and process MessageEvents, logging the source and message content. ```go for _, event := range cb.Events { if msg, ok := event.(*webhook.MessageEvent); ok { log.Printf("Message from %v: %v", msg.Source, msg.Message) } } ``` -------------------------------- ### Get Message Delivery Statistics Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/insight.md Retrieves message delivery statistics for a specified date (yesterday in this example). It calculates the total messages sent and logs the delivery status and API failures if any. ```Go import ( "github.com/line/line-bot-sdk-go/v8/linebot/insight" "time" "log" ) func checkDeliveryStats(insightClient *insight.InsightAPI) { // Get delivery for yesterday yesterday := time.Now().Add(-24 * time.Hour).Format("2006-01-02") delivery, err := insightClient.GetMessageDelivery(yesterday) if err != nil { log.Printf("Failed to get delivery stats: %v", err) return } total := delivery.Broadcast + delivery.Contact + delivery.Push log.Printf("Total messages sent: %d", total) log.Printf("Delivery status: %s", delivery.Status) if delivery.ApiFailed > 0 { log.Printf("API failures: %d", delivery.ApiFailed) } } ``` -------------------------------- ### Get User Profile Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Retrieves the display name, picture URL, and status message of a specific user using their user ID. ```go profile, err := bot.GetProfile("U1234567890abcdef") if err == nil { log.Printf("User: %s", profile.DisplayName) log.Printf("Picture: %s", profile.PictureUrl) log.Printf("Status: %s", profile.StatusMessage) } ``` -------------------------------- ### Webhook Parsing and Event Handling Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/webhook.md This example demonstrates how to parse incoming webhook requests, handle potential signature errors, and iterate through different event types such as MessageEvent, FollowEvent, and PostbackEvent. ```APIDOC ## Parse and Handle Webhook Events ### Description This function parses incoming webhook requests from the LINE Messaging API. It validates the request signature and then processes various event types, including message events (text, image), follow events, and postback events. ### Method `webhook.ParseRequest(channelSecret string, r *http.Request) ([]Event, error)` ### Parameters #### Request - `channelSecret` (string) - The channel secret obtained from the LINE Developers console. - `r` (*http.Request) - The incoming HTTP request object. ### Response #### Success Response (200 OK) - `[]Event` - A slice of `Event` objects representing the incoming events. #### Error Responses - `webhook.ErrInvalidSignature` (400 Bad Request) - If the request signature is invalid. - `http.StatusInternalServerError` (500 Internal Server Error) - For other internal server errors during parsing. ### Request Example ```go import ( "net/http" "github.com/line/line-bot-sdk-go/v8/linebot/webhook" ) func handleWebhook(w http.ResponseWriter, r *http.Request) { cb, err := webhook.ParseRequest( os.Getenv("LINE_CHANNEL_SECRET"), r, ) if err != nil { if errors.Is(err, webhook.ErrInvalidSignature) { w.WriteHeader(http.StatusBadRequest) } else { w.WriteHeader(http.StatusInternalServerError) } return } for _, event := range cb.Events { switch e := event.(type) { case *webhook.MessageEvent: switch msg := e.Message.(type) { case webhook.TextMessageContent: log.Printf("Text: %s", msg.Text) case webhook.ImageMessageContent: log.Printf("Image ID: %s", msg.Id) } case *webhook.FollowEvent: log.Println("User followed the bot") case *webhook.PostbackEvent: log.Printf("Postback data: %s", e.Postback.Data) } } w.WriteHeader(http.StatusOK) } ``` ``` -------------------------------- ### Get Response Header with Go SDK Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Use `~WithHttpInfo` to retrieve response headers, including `x-line-request-id`, status codes, and other headers like `content-type`. This is useful for tracking requests. ```go resp, _, _ := app.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 User Profile Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves a user's profile information, including their display name and picture URL. Requires a user ID. ```Go profile, err := bot.GetProfile("U1234567890abcdef") if err == nil { log.Printf("User: %s, Picture: %s", profile.DisplayName, profile.PictureUrl) } ``` -------------------------------- ### Module Initialization Pattern Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/MODULES.md Demonstrates the common pattern for initializing a module client and executing operations. This pattern is applicable across most modules in the SDK. ```go // Create client client, err := package.NewPackageAPI( channelToken, package.WithHTTPClient(customClient), package.WithEndpoint("https://custom-endpoint"), ) if err != nil { log.Fatal(err) } // Execute operations result, err := client.Operation(request) ``` -------------------------------- ### Get Room Member Count Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves the total number of members in a room. ```go func (client *MessagingApiAPI) GetRoomMemberCount(roomId string) (int, error) ``` -------------------------------- ### Get Group Member Count Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves the total number of members in a group. ```go func (client *MessagingApiAPI) GetGroupMemberCount(groupId string) (int, error) ``` -------------------------------- ### Manage Rich Menus Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Demonstrates creating a rich menu with specified areas and actions, linking it to a user, and uploading a menu image. ```go // Create rich menu menuID, err := bot.CreateRichMenu( &messaging_api.CreateRichMenuRequest{ Size: &messaging_api.RichMenuSize{ Width: 800, Height: 810, }, Selected: true, Name: "Main Menu", Areas: []messaging_api.RichMenuArea{ { Bounds: &messaging_api.RichMenuArea_Bounds{ X: 0, Y: 0, Width: 267, Height: 810, }, Action: &messaging_api.MessageAction{ Label: "Help", Text: "help", }, }, }, }, ) // Link to user bot.LinkUserRichMenu("U1234567890abcdef", menuID) // Upload menu image file, _ := os.Open("menu_image.jpg") defer file.Close() bot.UploadRichMenuImage(menuID, file) ``` -------------------------------- ### Get Delivery Statistics Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Retrieves message delivery statistics for a specified date. ```APIDOC ## Get Delivery Statistics ### Description Retrieves statistics on message delivery for a given date, categorized by delivery type. ### Method Not specified (SDK method call) ### Endpoint Not specified (SDK method call) ### Parameters #### Path Parameters - **date** (string) - Required - The date for which to retrieve delivery statistics (format: YYYY-MM-DD). ### Request Example ```go insightClient, _ := insight.NewInsightAPI(token) delivery, _ := insightClient.GetMessageDelivery("2025-06-20") // Access delivery.Broadcast, delivery.Contact, delivery.Push, delivery.Multicast, delivery.NarrowCast ``` ### Response #### Success Response - **delivery** (*insight.MessageDeliveryStatistics) - An object containing message delivery statistics. - **Broadcast** (int) - **Contact** (int) - **Push** (int) - **Multicast** (int) - **NarrowCast** (int) #### Response Example (Response structure depends on MessageDeliveryStatistics object) ``` -------------------------------- ### Get Follower IDs Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Retrieves a list of user IDs who are following the bot. ```go followers, err := bot.GetFollowerIds() if err == nil { for _, id := range followers.UserIds { log.Printf("Follower: %s", id) } } ``` -------------------------------- ### Get Room Member IDs Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves a list of all member IDs present in a room. ```go func (client *MessagingApiAPI) GetRoomMemberIds(roomId string) (*GetRoomMemberIdsResponse, error) ``` -------------------------------- ### Get Group Member IDs Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves a list of all member IDs present in a group. ```go func (client *MessagingApiAPI) GetGroupMemberIds(groupId string) (*GetGroupMemberIdsResponse, error) ``` -------------------------------- ### Get Reply Token Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Retrieve the reply token from an event object, which is necessary for replying to messages. ```go replyToken := event.ReplyToken ``` -------------------------------- ### Initialize Channel Access Token API Client Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/channel-access-token.md Creates a new client for the Channel Access Token API. Requires a valid channel token for authentication. Optional configurations can be provided. ```go catClient, err := channel_access_token.NewChannelAccessTokenAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure Messaging API Client Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Initialize the Messaging API client using your channel access token. Ensure the LINE_CHANNEL_TOKEN environment variable is set. ```go import ( "github.com/line/line-bot-sdk-go/v8/linebot/messaging_api" ) func main() { bot, err := messaging_api.NewMessagingApiAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) ... } ``` -------------------------------- ### Get User Profile Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Retrieves the profile information of a specified user, including their display name and picture. ```APIDOC ## Get User Profile ### Description Retrieves the profile information of a specified user. ### Method Not specified (SDK method call) ### Endpoint Not specified (SDK method call) ### Parameters #### Path Parameters - **userID** (string) - Required - The user ID of the profile to retrieve. ### Request Example ```go profile, err := bot.GetProfile("U1234567890abcdef") // Access profile.DisplayName, profile.PictureURL, profile.StatusMessage ``` ### Response #### Success Response - **profile** (*UserProfile) - The user's profile information. - **DisplayName** (string) - **PictureURL** (string) - **StatusMessage** (string) #### Response Example (Response structure depends on the UserProfile object) ``` -------------------------------- ### Initialize Manage Audience Client Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/manage-audience.md Creates a new client for the Manage Audience API. Ensure your LINE_CHANNEL_TOKEN environment variable is set. ```go auditClient, err := manage_audience.NewManageAudienceAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Message Quota Information Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Retrieves the daily message quota and the current message consumption for the day. ```go quota, err := bot.GetMessageQuota() if err == nil { log.Printf("Daily quota: %d messages", quota.Value) } consumption, err := bot.GetMessageQuotaConsumption() if err == nil { log.Printf("Messages used today: %d", consumption.Value) } ``` -------------------------------- ### Standard API Operation Pattern Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Illustrates the common pattern for making API calls using the SDK. It shows how to handle both successful results and errors, including variants that provide HTTP response details. ```go // Method returns result or error result, err := client.Operation(request) if err != nil { // Handle error } // WithHttpInfo variant returns HTTP response details resp, result, err := client.OperationWithHttpInfo(request) if err != nil { // Handle error } if resp.StatusCode != 200 { // Handle HTTP error } ``` -------------------------------- ### Get Message Delivery Progress Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/insight.md Retrieves the progress of a narrowcast or broadcast message delivery using its request ID. ```go progress, err := insightClient.GetMessageProgress("noncw3j4d37nvmzs9swykr8j1") if err == nil { log.Printf("Progress: %d%% (%d/%d)", (progress.Checking+progress.Success)*100/(progress.Checking+progress.Success+progress.Failure), progress.Success, progress.Checking+progress.Success+progress.Failure) } ``` -------------------------------- ### Initialize LIFF API Client Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Creates a new LIFF API client instance using a LINE channel access token. Ensure the LINE_CHANNEL_TOKEN environment variable is set. ```go liffClient, err := liff.NewLiffAPI(os.Getenv("LINE_CHANNEL_TOKEN")) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Follower IDs Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves the user IDs of followers for a LINE official account. This function returns paginated results. ```go func (client *MessagingApiAPI) GetFollowerIds() (*GetFollowerIdsResponse, error) ``` -------------------------------- ### Configuration Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/SUMMARY.txt Information on configuring the HTTP client, custom endpoints, and managing context and timeouts. ```APIDOC ## Configuration ### Description This section provides guidance on configuring the LINE Bot SDK for Go client. It covers setting up custom HTTP clients with specific configurations such as timeouts, transports, and proxy settings. Developers can also learn how to specify custom API endpoints, manage context and timeouts for requests, and utilize environment variables. Best practices for secret management and client reuse are also discussed. ### Modules Covered - configuration.md ### Key Configuration Options - Custom HTTP client (timeout, transport, proxy) - Custom API endpoints - Context and timeout management - Environment variables - Best practices (secret management, client reuse) ``` -------------------------------- ### QuickReplyButtonObject Structure Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/types.md Represents a single quick reply button. Configure its type, optional image, and the associated action (e.g., sending a message or a postback). ```go type QuickReplyButtonObject struct { Type string // "action" ImageUrl string Action QuickReplyActionInterface } ``` -------------------------------- ### Get Group Summary Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves summary information about a group using its ID. Requires the group ID obtained from a webhook. ```go func (client *MessagingApiAPI) GetGroupSummary(groupId string) (*GroupSummaryResponse, error) ``` -------------------------------- ### Check Message Quota Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Get the overall message quota and current consumption. This helps in monitoring message sending limits. ```go quota, _ := bot.GetMessageQuota() consumption, _ := bot.GetMessageQuotaConsumption() ``` -------------------------------- ### Get Message Delivery Statistics Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/insight.md Retrieves message delivery status for a specific date. Requires the date in YYYY-MM-DD format. ```go delivery, err := insightClient.GetMessageDelivery("2025-06-20") if err == nil { log.Printf("Sent: %d, Delivered: %d, Failed: %d", delivery.Broadcast, delivery.Contact, delivery.Audience) } ``` -------------------------------- ### Import All Packages in Go Code Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Import all available packages from the SDK to use various functionalities. ```go 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" ) ``` -------------------------------- ### Get Daily Message Quota Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves the daily message quota and current usage. Use this to monitor message sending limits. ```Go quota, err := bot.GetMessageQuota() if err == nil { log.Printf("Daily Quota: %d", quota.Value) } ``` -------------------------------- ### Initialize Insight API Client Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/insight.md Creates a new Insight API client using the channel access token. Optional configurations can be provided. ```go insightClient, err := insight.NewInsightAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create Rich Menu Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Create a new rich menu for a bot. Define its size, name, and interactive areas. The menu ID is returned upon successful creation. ```go menuID, _ := bot.CreateRichMenu(&messaging_api.CreateRichMenuRequest{ Size: &messaging_api.RichMenuSize{Width: 800, Height: 810}, Name: "Main Menu", Areas: []messaging_api.RichMenuArea{...}, }) ``` -------------------------------- ### Get Paginated Audience Groups Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/manage-audience.md Retrieves a paginated list of all audience groups. Check the 'HasNextPage' field to determine if more pages are available. ```go response, err := auditClient.GetAudienceGroups(1) if err == nil { for _, group := range response.AudienceGroups { log.Printf("- %s (Size: %d)", group.Name, group.Count) } if response.HasNextPage { log.Println("More pages available") } } ``` -------------------------------- ### WithHTTPClient Option Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Configures a custom http.Client for the API client. ```APIDOC ## WithHTTPClient Option ### Description Configures a custom `http.Client` for the API client. ### Signature ```go func WithHTTPClient(c *http.Client) MessagingApiAPIOption ``` ### Parameters #### Path Parameters - **c** (*http.Client) - Required - HTTP client instance ### Example ```go customClient := &http.Client{ Timeout: time.Second * 30, } bot, err := messaging_api.NewMessagingApiAPI( token, messaging_api.WithHTTPClient(customClient), ) ``` ``` -------------------------------- ### Get Channel Access Token Key IDs Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/channel-access-token.md This operation retrieves the key IDs used for verifying channel access tokens. ```APIDOC ## Get Channel Access Token Key IDs ### Description Retrieves the key IDs used for verifying channel access tokens. ### Method GET ### Endpoint `/v2/oauth/apple/keys` ### Response #### Success Response (200) - **Kids** ([]string) - Array of key IDs for token verification. #### Response Example ```json { "kids": [ "key_id_1", "key_id_2" ] } ``` ``` -------------------------------- ### Initialize Messaging API with Custom HTTP Client Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Create a new instance of the Messaging API client, specifying a custom HTTP client with a defined timeout. This allows for fine-grained control over network requests. ```go client := &http.Client{Timeout: 10 * time.Second} bot, err := messaging_api.NewMessagingApiAPI( token, messaging_api.WithHTTPClient(client), ) ``` -------------------------------- ### Bulk Link Rich Menu to Users Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/rich-menu.md Efficiently link a single rich menu to multiple users simultaneously. Provide a list of user IDs and the target rich menu ID. ```go func (client *MessagingApiAPI) BulkLinkRichMenu( bulkLinkRichMenuRequest *BulkLinkRichMenuRequest, ) error ``` ```go err := bot.BulkLinkRichMenu( &messaging_api.BulkLinkRichMenuRequest{ RichMenuId: "richmenu-1234567890abcdef", UserIds: []string{ "U1111111111111111111111111111111", "U2222222222222222222222222222222", }, }, ) ``` -------------------------------- ### Get Daily Message Consumption Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves the number of messages consumed today. This provides a count of messages sent within the current day. ```Go func (client *MessagingApiAPI) GetMessageQuotaConsumption() (*GetMessageConsumptionResponse, error) ``` -------------------------------- ### Client Initialization Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/channel-access-token.md Initializes a new Channel Access Token API client. You can optionally provide custom HTTP clients or endpoints. ```APIDOC ## NewChannelAccessTokenAPI ### Description Creates a new Channel Access Token API client. ### Method `NewChannelAccessTokenAPI` ### Parameters #### Path Parameters - **channelToken** (string) - Required - Channel token for authentication - **options** (*[]ChannelAccessTokenAPIOption) - Optional - Optional configuration ### Returns - (*ChannelAccessTokenAPI) - Channel access token client - (error) - Error during client creation ### Example ```go catClient, err := channel_access_token.NewChannelAccessTokenAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) if err != nil { log.Fatal(err) } ``` ``` ```APIDOC ## WithHTTPClient Option ### Description Configures a custom HTTP client for the API client. ### Method `WithHTTPClient` ### Parameters #### Request Body - **c** (*http.Client) - Required - The HTTP client to use ### Returns - (ChannelAccessTokenAPIOption) - An option to configure the HTTP client ``` ```APIDOC ## WithEndpoint Option ### Description Configures a custom API endpoint for the API client. ### Method `WithEndpoint` ### Parameters #### Request Body - **endpoint** (string) - Required - The custom API endpoint URL ### Returns - (ChannelAccessTokenAPIOption) - An option to configure the API endpoint ``` -------------------------------- ### Go Struct: AddLiffAppRequest Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Defines the structure for adding a new LIFF app. It includes view configuration and an optional description. ```go type AddLiffAppRequest struct { View *LiffViewRequest Description string } ``` -------------------------------- ### Get User, Group, or Room ID Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Extract the user ID, group ID, or room ID from an event object to identify the sender. ```go userID := event.Source.UserId groupID := event.Source.GroupId RoomID := event.Source.RoomId ``` -------------------------------- ### Get Bot Information Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves information about the bot user (official account), including its ID, basic ID, display name, and picture URL. ```go func (client *MessagingApiAPI) GetBotInfo() (*GetBotInfoResponse, error) ``` -------------------------------- ### ContentProvider Structure Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/types.md Defines the source of content, whether it's from LINE itself or an external URL. Specify the type and relevant URLs for original content and previews. ```go type ContentProvider struct { Type string // "line" or "external" OriginalContentUrl string PreviewImageUrl string } ``` -------------------------------- ### Get Room Member Profile Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves a user's profile within a specific room context. Requires both the room ID and the user ID. ```go func (client *MessagingApiAPI) GetRoomMemberProfile(roomId string, userId string) (*UserProfileResponse, error) ``` -------------------------------- ### Reuse Bot Client Instance (Go) Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Initialize the Messaging API client once globally and reuse it across different request handlers. This improves efficiency by avoiding repeated client creation. ```go var bot *messaging_api.MessagingApiAPI func init() { var err error bot, err = messaging_api.NewMessagingApiAPI( os.Getenv("LINE_CHANNEL_TOKEN"), ) if err != nil { log.Fatal(err) } } func handleMessage(w http.ResponseWriter, r *http.Request) { // Use global bot client bot.ReplyMessage(request) } ``` -------------------------------- ### Module Structure Overview Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/MODULES.md This tree displays the directory structure of the LINE Messaging API SDK for Go, highlighting the purpose of each module. ```go github.com/line/line-bot-sdk-go/v8/linebot/ ├── messaging_api/ # Core messaging and user management ├── webhook/ # Event parsing and validation ├── liff/ # LIFF app management ├── insight/ # Analytics and metrics ├── manage_audience/ # Audience segment management ├── channel_access_token/ # Token management ├── module/ # Mini app modules ├── module_attach/ # Module attachments ├── shop/ # Shop features ├── client.go # Legacy client (deprecated) ├── message.go # Legacy message types (deprecated) ├── actions.go # Action types ├── error.go # Error types (deprecated) └── webhook.go # Legacy webhook (deprecated) ``` -------------------------------- ### Get Group Member Profile Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves a user's profile within a specific group context. Requires both the group ID and the user ID. ```go func (client *MessagingApiAPI) GetGroupMemberProfile(groupId string, userId string) (*UserProfileResponse, error) ``` -------------------------------- ### Go: Manage Audience Group and Send Narrowcast Message Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/manage-audience.md This snippet demonstrates how to create an audience group, add users to it, retrieve audience information, and then use the audience ID to send a narrowcast message. Ensure the `manage_audience` and `messaging_api` packages are imported. ```go import ( "github.com/line/line-bot-sdk-go/v8/linebot/manage_audience" "github.com/line/line-bot-sdk-go/v8/linebot/messaging_api" ) func setupAudience(auditClient *manage_audience.ManageAudienceAPI, bot *messaging_api.MessagingAPI) { // Create audience resp, err := auditClient.CreateAudienceGroup( &manage_audience.CreateAudienceGroupRequest{ Name: "Q2 Campaign", Description: "Users for Q2 2025 campaign", IsIfaAudience: false, }, ) if err != nil { log.Fatal(err) } audienceId := resp.AudienceGroupId // Add users err = auditClient.AddAudienceToAudienceGroup( &manage_audience.AddAudienceToAudienceGroupRequest{ AudienceGroupId: audienceId, UserIds: []string{"U123...", "U456..."}, }, ) // Retrieve audience info audience, _ := auditClient.GetAudienceGroup(audienceId) log.Printf("Audience %s has %d users", audience.Name, audience.Count) // Use in narrowcast message narrowcastReq := &messaging_api.NarrowcastRequest{ Messages: []messaging_api.MessageInterface{ messaging_api.TextMessage{ Text: "Special offer for Q2 users", }, }, Recipient: &messaging_api.Recipient{ AudienceId: int32(audienceId), }, } bot.Narrowcast(narrowcastReq, "") } ``` -------------------------------- ### Get Delivery Statistics Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Retrieve message delivery statistics for a specific date. Provides insights into broadcast, contact, push, multicast, and narrowcast messages. ```go insightClient, _ := insight.NewInsightAPI(token) delivery, _ := insightClient.GetMessageDelivery("2025-06-20") // delivery.Broadcast, Contact, Push, Multicast, NarrowCast ``` -------------------------------- ### QuickReplyItems Structure Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/types.md Defines a collection of quick reply buttons. Use this to group multiple quick reply options for user interaction. ```go type QuickReplyItems struct { Items []*QuickReplyButtonObject } ``` -------------------------------- ### Get Default Rich Menu ID Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/rich-menu.md Retrieve the ID of the currently set default rich menu. This helps in identifying which rich menu is active by default. ```go func (client *MessagingApiAPI) GetDefaultRichMenu() (string, error) ``` -------------------------------- ### Get Channel Access Token Key IDs Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/channel-access-token.md Retrieves the key IDs associated with channel access tokens. This information can be useful for managing token-related security configurations. ```go keyIds, err := catClient.GetChannelAccessTokenKeyIds() if err == nil { for _, kid := range keyIds.Kids { log.Printf("Key ID: %s", kid) } } ``` -------------------------------- ### Configure Custom TLS Settings Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/configuration.md Customize TLS settings for secure connections, such as specifying the minimum TLS version or skipping certificate verification (use with caution). ```go tlsConfig := &tls.Config{ InsecureSkipVerify: false, // Always verify in production MinVersion: tls.VersionTLS12, } transport := &http.Transport{ TLSClientConfig: tlsConfig, } client := &http.Client{ Transport: transport, } bot, err := messaging_api.NewMessagingApiAPI(token, messaging_api.WithHTTPClient(client)) ``` -------------------------------- ### Go Struct: LiffAppInfo Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Contains detailed information about a specific LIFF app, including its ID, view configuration, description, and creation timestamp. ```go type LiffAppInfo struct { LiffId string View LiffViewInfo Description string Created int64 } ``` -------------------------------- ### Handle 404 Not Found: User Profile Not Found Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/errors.md This snippet demonstrates a 404 Not Found error when trying to retrieve a profile for a non-existent user ID. Verify that the user ID is correct and exists. ```go profile, err := bot.GetProfile("U_DOES_NOT_EXIST") if err != nil { // Returns 404: "User profile not found" } ``` -------------------------------- ### Handle FollowEvent in Go Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/QUICKSTART.md Log when a user follows the bot. This event is triggered when a user adds the bot as a friend. ```go case *webhook.FollowEvent: log.Println("User followed the bot") ``` -------------------------------- ### Go Struct: LiffViewInfo Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Provides information about the view configuration of a LIFF app, including its type and URL. ```go type LiffViewInfo struct { Type string // "FULL" or "TALL" Url string } ``` -------------------------------- ### Get Message Content Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Retrieves the binary content of a message, such as an image, video, audio, or file. Requires a message ID obtained from a webhook. Ensure to close the returned ReadCloser. ```Go content, err := bot.GetMessageContent("message123") if err != nil { log.Fatal(err) } defer content.Close() file, _ := os.Create("downloaded_image.jpg") defer file.Close() io.Copy(file, content) ``` -------------------------------- ### Get Audience Group Details Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/manage-audience.md Retrieves the details of a specific audience group using its ID. This includes the group's name, status, creation timestamp, and user count. ```go audience, err := auditClient.GetAudienceGroup(12345) if err == nil { log.Printf("Audience: %s (%s)", audience.Name, audience.Status) log.Printf("Created: %d, Size: %d", audience.Created, audience.Count) } ``` -------------------------------- ### Create a New Rich Menu Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/rich-menu.md Use this function to create a new rich menu with specified size, name, and interactive areas. Ensure the `messaging_api` package is imported. ```go menuID, err := bot.CreateRichMenu( &messaging_api.CreateRichMenuRequest{ Size: &messaging_api.RichMenuSize{ Width: 800, Height: 810, }, Selected: false, Name: "Main Menu", Areas: []messaging_api.RichMenuArea{ { Bounds: &messaging_api.RichMenuArea_Bounds{ X: 0, Y: 0, Width: 267, Height: 405, }, Action: &messaging_api.URIAction{ Label: "Website", Uri: "https://example.com", }, }, }, }, ) if err != nil { log.Fatal(err) } log.Printf("Rich menu created: %s", menuID) ``` -------------------------------- ### Configure Channel Access Token API with HTTP Client Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/configuration.md Use this option to provide a custom http.Client for the Channel Access Token API. This allows for advanced configurations like custom timeouts or transport settings. ```go func WithHTTPClient(c *http.Client) ChannelAccessTokenAPIOption ``` -------------------------------- ### Get Message Narrowcast Progress Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/insight.md Retrieves the progress of a narrowcast message using its request ID. It calculates and logs the success rate and the current phase details (success, failure, checking). ```Go import ( "github.com/line/line-bot-sdk-go/v8/linebot/insight" "log" ) func checkNarrowcastProgress(insightClient *insight.InsightAPI, requestId string) { progress, err := insightClient.GetMessageProgress(requestId) if err != nil { log.Printf("Failed to get progress: %v", err) return } total := progress.Success + progress.Failure + progress.Checking if total > 0 { successRate := (float64(progress.Success) / float64(total)) * 100 log.Printf("Success rate: %.2f%%", successRate) } log.Printf("Phase: %s (Success: %d, Failure: %d, Checking: %d)", progress.Phase, progress.Success, progress.Failure, progress.Checking) } ``` -------------------------------- ### WithContext Method Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/messaging-api.md Attaches a context for request execution. ```APIDOC ## WithContext Method ### Description Attaches a context for request execution. ### Signature ```go func (client *MessagingApiAPI) WithContext(ctx context.Context) *MessagingApiAPI ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for cancellation and timeouts ### Returns - The modified `MessagingApiAPI` client. ### Example ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() bot.WithContext(ctx) ``` ``` -------------------------------- ### Add a New LIFF App Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Creates a new LIFF app and returns its LIFF ID. Requires LIFF app configuration including view type and URL. ```go liffID, err := liffClient.AddLIFFApp( &liff.AddLiffAppRequest{ View: &liff.LiffViewRequest{ Type: "FULL", Url: "https://example.com/liff", }, Description: "My LIFF App", }, ) if err != nil { log.Fatal(err) } log.Printf("LIFF app created: %s", liffID) ``` -------------------------------- ### Create Rich Menu Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/README.md Creates a new rich menu for the LINE Official Account. ```APIDOC ## Create Rich Menu ### Description Creates a new rich menu with specified size, name, and areas. ### Method Not specified (SDK method call) ### Endpoint Not specified (SDK method call) ### Parameters #### Request Body - **request** (*messaging_api.CreateRichMenuRequest) - Required - The request body for creating a rich menu. - **Size** (*messaging_api.RichMenuSize) - Required - The size of the rich menu. - **Width** (int) - Required - **Height** (int) - Required - **Name** (string) - Required - The name of the rich menu. - **Areas** ([]messaging_api.RichMenuArea) - Required - The areas defined within the rich menu. ### Request Example ```go menuID, _ := bot.CreateRichMenu(&messaging_api.CreateRichMenuRequest{ Size: &messaging_api.RichMenuSize{Width: 800, Height: 810}, Name: "Main Menu", Areas: []messaging_api.RichMenuArea{...}, // Define areas here }) ``` ### Response #### Success Response - **menuID** (string) - The ID of the newly created rich menu. #### Response Example (Returns the ID of the created rich menu) ``` -------------------------------- ### User Source Structure Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/webhook.md Defines the structure for a user source in a webhook event. ```go type UserSource struct { Type string // "user" UserId string } ``` -------------------------------- ### QuickReplyButtonObject Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/types.md Defines a single quick reply button, including its type, an optional image URL, and the associated action (e.g., sending a message or a postback). ```APIDOC ## QuickReplyButtonObject ### Description Defines a single quick reply button, including its type, an optional image URL, and the associated action (e.g., sending a message or a postback). ### Fields - **Type** (string) - Always "action" - **ImageUrl** (string) - Optional icon URL - **Action** (QuickReplyActionInterface) - Button action (message, postback, etc.) ``` -------------------------------- ### List All Rich Menus Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/rich-menu.md Retrieves a paginated list of all rich menus associated with the account. The loop iterates through `menus.RichMenus` to access individual menu IDs and names. ```go menus, err := bot.ListRichMenu() if err == nil { for _, menu := range menus.RichMenus { log.Printf("Menu: %s (%s)", menu.Id, menu.Name) } } ``` -------------------------------- ### Configure Messaging API Client with HTTP Client Source: https://github.com/line/line-bot-sdk-go/blob/master/README.md Configure the Messaging API client with a custom http.Client and endpoint. The Blob client also offers similar configuration options. ```go client := &http.Client{} bot, err := messaging_api.NewMessagingApiAPI( os.Getenv("LINE_CHANNEL_TOKEN"), messaging_api.WithHTTPClient(client), ) ... ``` -------------------------------- ### Load Secrets Securely Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/configuration.md Avoid hardcoding sensitive credentials like channel access tokens directly in your code. Load them from environment variables or a secure secrets management system. ```go // Bad: Secrets in code bot, _ := messaging_api.NewMessagingApiAPI("my_actual_token_1234567890") // Good: Secrets from environment bot, _ := messaging_api.NewMessagingApiAPI(os.Getenv("LINE_CHANNEL_TOKEN")) // Better: Secrets from secure storage token, _ := secretsManager.GetSecret("line_channel_token") bot, _ := messaging_api.NewMessagingApiAPI(token) ``` -------------------------------- ### Configure Custom HTTP Client for LIFF API Source: https://github.com/line/line-bot-sdk-go/blob/master/_autodocs/api-reference/liff.md Use the WithHTTPClient option to provide a custom http.Client for the LIFF API. This allows for advanced configurations like connection pooling or custom transport settings. ```go func WithHTTPClient(c *http.Client) LiffAPIOption ```