LINE Messaging API SDK for Java

repository·master·Indexed 20 days ago

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

A comprehensive set of tools for building LINE bots in Java, featuring clients for Messaging, Insight, and Audience APIs. It provides seamless integration with Spring Boot via the line-bot-spring-boot-webmvc module, utilizing annotations like @LineMessageHandler and @EventMapping for event handling. Requires Java 17 or later.

Tokens
4.6K
Snippets
12
Records
15
Agent score
70%

What's inside line-bot-sdk-java

  1. How event mapping and argument handling works

    master

    The SDK uses reflection to match incoming webhook events to methods annotated with @EventMapping.

    Argument Rules:

    1. Event Objects: You can request an object that implements Event (e.g., MessageEvent, FollowEvent).
    2. Message Content: You can request specific MessageContent objects (e.g., TextMessageContent) as arguments to simplify access to message data.
    3. Destination: You can capture the destination field from the LINE request body by using the @LineBotDestination annotation on a String parameter. This parameter must be the first argument in the method.
    4. Return Values: If your @EventMapping method returns a message type (like TextMessage), the SDK will automatically handle the reply logic for you.

    Example: Handling Text Messages with Destination and Content

    @LineMessageHandler
    public class EchoApplication {
        @EventMapping
        public TextMessage handleTextMessageEvent(@LineBotDestination String destination, 
                                                  MessageEvent<TextMessageContent> event) {
            System.out.println("destination: " + destination);
            return new TextMessage(event.getMessage().getText());
        }
    }
  2. Integrate with Spring Boot using line-bot-spring-boot-webmvc

    master

    You can build a bot application using Spring Boot by utilizing the line-bot-spring-boot-webmvc module.

    To handle events, annotate your application class with @LineMessageHandler and use the @EventMapping annotation on methods that handle specific event types (e.g., MessageEvent<TextMessageContent>). You can inject MessagingApiClient to send replies or other API calls.

    package com.example.bot.spring.echo;
    
    import java.util.List;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import com.linecorp.bot.messaging.client.MessagingApiClient;
    import com.linecorp.bot.messaging.model.ReplyMessageRequest;
    import com.linecorp.bot.messaging.model.TextMessage;
    import com.linecorp.bot.spring.boot.handler.annotation.EventMapping;
    import com.linecorp.bot.spring.boot.handler.annotation.LineMessageHandler;
    import com.linecorp.bot.webhook.model.Event;
    import com.linecorp.bot.webhook.model.MessageEvent;
    import com.linecorp.bot.webhook.model.TextMessageContent;
    
    @SpringBootApplication
    @LineMessageHandler
    public class EchoApplication {
        private final MessagingApiClient messagingApiClient;
    
        public static void main(String[] args) {
            SpringApplication.run(EchoApplication.class, args);
        }
    
        public EchoApplication(MessagingApiClient messagingApiClient) {
            this.messagingApiClient = messagingApiClient;
        }
    
        @EventMapping
        public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) {
            final String originalMessageText = ((TextMessageContent) event.message()).text();
            messagingApiClient.replyMessage(
                new ReplyMessageRequest.Builder(event.replyToken(), List.of(new TextMessage(originalMessageText)))
                    .build()
            );
        }
    
        @EventMapping
        public void handleDefaultMessageEvent(Event event) {
            System.out.println("event: " + event);
        }
    }
  3. Install the LINE Messaging API SDK for Java

    master

    The SDK is available on Maven Central. You can install the required modules using Maven or Gradle.

    Requirements:

    • Java 17 or later

    Note on modules: Many modules like line-bot-parser, line-bot-spring-boot-handler, and line-bot-spring-boot-web are transitively included and do not need to be explicitly declared in your dependencies.

    // Example Gradle (Kotlin) dependencies
    // Replace <VERSION> with the desired version
    implementation("com.linecorp.bot:line-bot-messaging-api-client:<VERSION>")
    implementation("com.linecorp.bot:line-bot-webhook:<VERSION>")
    implementation("com.linecorp.bot:line-bot-spring-boot-webmvc:<VERSION>")
  4. Run the Spring Boot Echo Bot sample

    master

    The sample-spring-boot-echo-kotlin application is a minimal Spring Boot-based bot that echoes messages. You can run it using Gradle by providing your LINE Messaging API credentials as system properties.

    Option 1: Using Command Line Arguments

    Pass your credentials directly via the -D flag:

    ../gradlew bootRun -Dline.bot.channelToken=YOUR_CHANNEL_TOKEN -Dline.bot.channelSecret=YOUR_CHANNEL_SECRET

    Option 2: Using an Application Configuration File

    Alternatively, you can create a configuration file at src/main/resources/application.yml. Use the provided src/main/resources/application-template.yml as a template. Once the file is configured, you can start the server with a simple command:

    ../gradlew bootRun
  5. Run the Spring Boot Kitchen Sink sample application

    master

    The sample-spring-boot-kitchensink is a full-featured sample application demonstrating the LINE Messaging API within a Spring Boot environment. You can run it using Gradle by providing your LINE credentials as system properties.

    Running with Command Line Arguments

    Use the following command to run the application, replacing the placeholders with your actual LINE Channel access token and Channel secret:

    ../gradlew bootRun -Dline.bot.channelToken=YOUR_CHANNEL_TOKEN -Dline.bot.channelSecret=YOUR_CHANNEL_SECRET

    Running with Configuration File

    Alternatively, you can create a permanent configuration file:

    1. Copy src/main/resources/application-template.yml to src/main/resources/application.yml.
    2. Populate the required fields with your credentials.
    3. Run the application using:
    ../gradlew bootRun
  6. Integrate LINE Messaging API with Spring Boot

    master

    The line-bot-spring-boot library provides auto-configuration for the LINE Messaging API. To use it, add the library as a dependency to your Spring Boot project and annotate your application or a component with @LineMessageHandler.

    Inside a @LineMessageHandler class, use the @EventMapping annotation on methods to define event handlers. The SDK automatically routes incoming webhooks to the correct method based on the argument types provided.

    @SpringBootApplication
    @LineMessageHandler
    public class EchoApplication {
        private final MessagingApiClient messagingApiClient;
    
        public EchoApplication(MessagingApiClient messagingApiClient) {
            this.messagingApiClient = messagingApiClient;
        }
    
        @EventMapping
        public void handleTextMessageEvent(MessageEvent event) {
            // Handle event logic here
        }
    }
  7. Run the line-bot-integration-test suite

    master

    The line-bot-integration-test component is an integration test suite for the LINE Bot SDK for Java. By default, the suite does not execute any tests. To enable and run the integration tests, you must provide a configuration file at src/test/resources/integration_test_settings.yml.

    # Place this file at src/test/resources/integration_test_settings.yml
    # The structure is mapped to com.linecorp.bot.client.utils.IntegrationTestSettings
  8. Configure the Spring Boot Echo Bot via application.yml

    master

    Instead of passing command-line arguments, you can configure the bot using a Spring Boot configuration file.

    1. Create a file at src/main/resources/application.yml.
    2. Use the template provided in src/main/resources/application-template.yml as a base.
    3. Define the following properties:
    • line.bot.channelToken: Your Channel access token
    • line.bot.channelSecret: Your Channel secret

    Once configured, you can start the application simply by running:

    ../gradlew bootRun
    # Example structure based on application-template.yml
    line:
      bot:
        channelToken: YOUR_CHANNEL_TOKEN
        channelSecret: YOUR_CHANNEL_SECRET
  9. Retrieve x-line-request-id and handle API errors

    master

    Getting the Request ID

    To retrieve the x-line-request-id header from a successful API response, access it via the requestId() method on the Result<T> object returned by the client.

    Handling Exceptions

    When using MessagingApiClient, errors are typically wrapped in an ExecutionException. You can catch this and inspect the cause to find a MessagingApiClientException. This exception provides:

    • getCode(): The HTTP status code.
    • getDetails(): The error response details.
    • getMessage(): The error message.
    • getHeader(String name): Access specific headers, such as x-line-accepted-request-id from error responses.
    // Get request ID from successful response
    Result<Object> apiResponse = messagingApiClient
        .narrowcast(retryKey, new NarrowcastRequest.Builder(messages).build())
        .get();
    System.out.println("x-line-request-id: " + apiResponse.requestId());
    
    // Handle API errors
    try {
        messagingApiClient.replyMessage(new ReplyMessage(replyToken, messages));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof MessagingApiClientException){
            MessagingApiClientException exception=(MessagingApiClientException)e.getCause();
            System.out.println("Error http status code: " + exception.getCode());
            System.out.println("Error response: " + exception.getDetails());
            System.out.println("Error message: " + exception.getMessage());
            // Get specific header from error
            String acceptedId = exception.getHeader("x-line-accepted-request-id");
        }
    }
  10. Configure Spring Boot Echo Bot credentials

    master

    To run the Spring Boot sample, you must provide the following configuration properties. These can be set via system properties (as shown in the usage guide) or within an application.yml file:

    PropertyDescription
    line.bot.channelTokenYour LINE Channel access token
    line.bot.channelSecretYour LINE Channel secret

    For more details on how Spring Boot handles these values, refer to the Spring Boot Externalized Configuration documentation.

  11. Configure line-bot-spring-boot via properties

    master

    The SDK is automatically configured using system properties (e.g., in application.properties or application.yml).

    # Required
    line.bot.channel-token=YOUR_CHANNEL_TOKEN
    line.bot.channel-secret=YOUR_CHANNEL_SECRET
    
    # Optional
    line.bot.channel-token-supply-mode=FIXED
    line.bot.connect-timeout=1000
    line.bot.read-timeout=1000
    line.bot.write-timeout=1000
    line.bot.skip-signature-verification=false
    line.bot.handler.enabled=true
    line.bot.handler.path=/callback