LINE Messaging API SDK for Node.js

repository·master·Indexed 21 days ago

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

A Node.js SDK designed to simplify the development of interactive bots using the LINE Messaging API. The library provides tools for building bot experiences within the LINE ecosystem, including examples for Echo Bots (supporting ES Modules, CommonJS, and TypeScript) and a Kitchen Sink Bot. It also includes a custom OpenAPI generator for the SDK.

Tokens
20.6K
Snippets
51
Records
74
Agent score
76%

What's inside @line/bot-sdk

  1. Migrate from Client to LineBotClient (Audience)

    master

    Audience management in LineBotClient features significant renames and changes to how groups are updated. For updating descriptions, you must now use a separate call. Many methods also changed their parameter types (e.g., audienceGroupId from string to number) and file types (from Buffer | Readable to Blob).

    Audience Method Mapping

    Legacy Client methodNew LineBotClient methodNotes
    createUploadAudienceGroup(...)createAudienceGroup(...)Renamed.
    createUploadAudienceGroupByFile(...)createAudienceForUploadingUserIds(file, ...)Renamed. file type changed to Blob.
    updateUploadAudienceGroup(...)addAudienceToAudienceGroup(...) + updateAudienceGroupDescription(...)Renamed. Description requires a separate call.
    updateUploadAudienceGroupByFile(...)addUserIdsToAudience(file, ...)Renamed. file type changed to Blob.
    createClickAudienceGroup(...)createClickBasedAudienceGroup(...)Renamed.
    createImpAudienceGroup(...)createImpBasedAudienceGroup(...)Renamed.
    setDescriptionAudienceGroup(desc, id)updateAudienceGroupDescription(id, { desc })Renamed. Argument order reversed. audienceGroupId is now number.
    deleteAudienceGroup(id)deleteAudienceGroup(id)audienceGroupId is now number.
    getAudienceGroup(id)getAudienceData(id)Renamed. audienceGroupId is now number.
    getAudienceGroups(...)getAudienceGroups(...)Last two arguments swapped.
    getAudienceGroupAuthorityLevel()DeletedNo equivalent.
    changeAudienceGroupAuthorityLevel(...)DeletedNo equivalent.
  2. System requirements for line-bot-sdk-nodejs

    master

    To use the LINE Messaging API SDK for Node.js, ensure your environment meets the following requirements:

    • Node.js: Version 22 or higher is required. The SDK utilizes ES2022 features.
    • npm: Version 10 or higher is recommended.

    Other necessary dependencies are managed automatically via npm during installation and do not require manual pre-installation.

  3. Test against a local build of @line/bot-sdk

    master

    If you are developing the SDK itself within this repository and want to test the Echo Bot example against your unreleased local changes instead of the published npm package, use the build-sdk command.

    Run the following sequence after cloning the repository:

    npm install
    npm run build-sdk

    If you omit npm run build-sdk, the example will use the standard published version of @line/bot-sdk from the npm registry.

  4. Build and use the OpenAPI Generator

    master

    This project is a boilerplate for creating a custom OpenAPI generator for the line-bot-sdk-nodejs-generator. To use it, you must first modify the generator logic and templates, build it into a JAR file using Maven, and then run it using the OpenAPI Generator CLI.

    1. Modify the Generator

    You must customize the following files to implement your specific logic:

    • LineBotSdkNodejsGeneratorGenerator.java: The core generator logic.
    • src/main/resources/line-bot-sdk-nodejs-generator: The Mustache template files.

    2. Build the JAR

    Run the following command in your generator project directory:

    mvn package

    The resulting JAR file will be located in the target directory.

    3. Run the Generator

    Use the java command to run the OpenAPI Generator CLI with your custom JAR in the classpath. Replace the placeholder paths with your actual file locations.

    macOS / Linux:

    java -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g line-bot-sdk-nodejs-generator -i /path/to/openapi.yaml -o ./test

    Windows:

    java -cp /path/to/openapi-generator-cli.jar;/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g line-bot-sdk-nodejs-generator -i /path/to/openapi.yaml -o ./test
  5. Use TypeScript with @line/bot-sdk

    master

    The @line/bot-sdk library is written in TypeScript and provides built-in type definitions for its core components. While you can use the pre-compiled JavaScript files via npm without any extra configuration, using TypeScript provides several benefits:

    1. Type Safety for Configuration: Prevents typos in configuration keys (e.g., using channelAccessToken correctly).
    2. Message Validation: Ensures complex message objects (like TemplateMessage) contain all required fields and follow the correct structure.
    3. Literal Type Support: Uses literal types for type fields, allowing the compiler to validate specific string values and infer object types based on the type property.
    4. Autocomplete: Provides a default type set for most objects used in webhooks and the client.
    import {
      LineBotClient,
      middleware,
      webhook,
      JSONParseError,
      SignatureValidationFailed,
    } from "@line/bot-sdk";
    
    const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: "..." });
  6. Migrate OAuth methods to ChannelAccessTokenClient

    master

    When migrating from the legacy Client to LineBotClient, note that OAuth methods are no longer available on LineBotClient. Instead, they have been moved to channelAccessToken.ChannelAccessTokenClient.

    To use these methods, you must construct a new ChannelAccessTokenClient without passing a channel access token in the configuration object.

    Method Mapping Table

    Legacy OAuth MethodNew ChannelAccessTokenClient MethodNotes
    issueAccessToken(client_id, client_secret)issueChannelToken('client_credentials', client_id, client_secret)Renamed. grant_type is now an explicit argument.
    revokeAccessToken(access_token)revokeChannelToken(access_token)Renamed.
    verifyAccessToken(access_token)verifyChannelTokenByJWT(access_token)Renamed. Verifies a v2.1 (JWT-issued) channel access token.
    verifyIdToken(...)DeletedNo direct equivalent.
    issueChannelAccessTokenV2_1(client_assertion)issueChannelTokenByJWT('client_credentials', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion)Renamed. grant_type and client_assertion_type are now explicit arguments.
    getChannelAccessTokenKeyIdsV2_1(client_assertion)getsAllValidChannelAccessTokenKeyIds('urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion)Renamed. client_assertion_type is now an explicit argument. Response shape changed: key_idskids.
    revokeChannelAccessTokenV2_1(client_id, client_secret, access_token)revokeChannelTokenByJWT(client_id, client_secret, access_token)Renamed.
    const { channelAccessToken } = require('@line/bot-sdk');
    const oauthClient = new channelAccessToken.ChannelAccessTokenClient({});
  7. Set up the Echo Bot (ES Modules) example

    master

    This example demonstrates a basic LINE bot that echoes received messages using ES modules. To set it up, install the dependencies, configure your LINE Messaging API credentials via environment variables, and run the bot.

    # Install dependencies
    $ npm install
    
    # Configure environment variables
    $ export CHANNEL_SECRET=YOUR_CHANNEL_SECRET
    $ export CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN
    $ export PORT=1234
    
    # Run the bot
    $ node .
  8. Debug the OpenAPI Generator templates

    master

    When developing custom templates (e.g., in api.mustache), you can inspect the data available to the template engine by passing debug flags to the java generation command. This helps you identify which keys and objects are accessible during the generation process.

    Debug Flags

    • -DdebugOpenAPI: Prints the OpenAPI Specification as interpreted by the codegen.
    • -DdebugModels: Prints models passed to the template engine.
    • -DdebugOperations: Prints operations passed to the template engine.
    • -DdebugSupportingFiles: Prints additional data passed to the template engine.

    Example Usage

    To debug operations, include the -DdebugOperations flag in your execution command:

    java -DdebugOperations -cp /path/to/openapi-generator-cli.jar:/path/to/your.jar org.openapitools.codegen.OpenAPIGenerator generate -g line-bot-sdk-nodejs-generator -i /path/to/openapi.yaml -o ./test
  9. Handle webhook middleware errors

    master

    The webhook middleware() can throw two specific error types that should be handled using Express error-handling middleware:

    • SignatureValidationFailed: Thrown when the X-Line-Signature header is missing or the signature does not match the request body (indicating a potential fraud attempt).
    • JSONParseError: Occurs when the request body cannot be parsed as valid JSON.

    Example of handling these errors in Express:

    import express from 'express'
    import {middleware, JSONParseError, SignatureValidationFailed} from '@line/bot-sdk'
    
    const app = express()
    const config = { channelSecret: 'YOUR_CHANNEL_SECRET' }
    
    app.post('/webhook', middleware(config), (req, res) => {
      res.json(req.body.events)
    })
    
    // Error handling middleware
    app.use((err, req, res, next) => {
      if (err instanceof SignatureValidationFailed) {
        // Handle invalid signature (e.g., 401 Unauthorized)
        res.status(401).send(err.signature)
        return
      } else if (err instanceof JSONParseError) {
        // Handle invalid JSON (e.g., 400 Bad Request)
        res.status(400).send(err.raw)
        return
      }
      next(err)
    })
    
    app.listen(8080)
  10. Build a webhook server with Express

    master

    A LINE webhook server is an HTTP(S) server that receives requests from the LINE Platform when user events occur. The recommended way to build this server is using the middleware() function from @line/bot-sdk, which handles both Signature validation (verifying the X-Line-Signature header) and Webhook event object parsing (converting the JSON body into usable objects).

    When using Express, apply the middleware specifically to your webhook route to avoid errors on other routes.

    import express from 'express'
    import { middleware } from '@line/bot-sdk'
    
    const app = express()
    
    const config = {
      channelSecret: 'YOUR_CHANNEL_SECRET'
    }
    
    // Apply middleware only to the webhook route
    app.post('/webhook', middleware(config), (req, res) => {
      // req.body.events contains the webhook event objects
      // req.body.destination contains the user ID of the bot
      console.log(req.body.events)
      res.status(200).send('OK')
    })
    
    app.listen(8080)
  11. Set up an Echo Bot using TypeScript and CommonJS

    master

    An Echo Bot is a basic bot that replies to a user's message with the same content. This guide demonstrates how to set up a LINE Echo Bot from scratch using TypeScript and CommonJS (CJS).

    Prerequisites

    • Node.js: Version 20 or higher.
    • LINE Channel: A channel created in the LINE Developers Console providing a CHANNEL_ACCESS_TOKEN and CHANNEL_SECRET.

    Installation and Setup

    1. Clone the repository and navigate to the example directory:
      git clone https://github.com/line/line-bot-sdk-nodejs.git
      cd line-bot-sdk-nodejs/examples/echo-bot-ts-cjs
    2. Install dependencies:
      npm install
    3. Configure environment variables:
      export CHANNEL_ACCESS_TOKEN=<YOUR_CHANNEL_ACCESS_TOKEN>
      export CHANNEL_SECRET=<YOUR_CHANNEL_SECRET>
      export PORT=<YOUR_PORT>
    4. Set up your Webhook URL in the LINE Official Account settings (e.g., https://example.com/callback). Note: Disable greeting messages and auto-response messages in your LINE Official Account settings for the best experience.
    5. Build and run the application:
      npm run build
      npm start
    git clone https://github.com/line/line-bot-sdk-nodejs.git
    cd line-bot-sdk-nodejs/examples/echo-bot-ts-cjs
    npm install
    export CHANNEL_ACCESS_TOKEN=<YOUR_CHANNEL_ACCESS_TOKEN>
    export CHANNEL_SECRET=<YOUR_CHANNEL_SECRET>
    export PORT=<YOUR_PORT>
    npm run build
    npm start