### ngrok Usage Example Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/kitchensink/README.md Demonstrates the output when starting the server with ngrok integration, showing the generated public URL for the webhook. ```text ❯ npm start ... It seems that BASE_URL is not set. Connecting to ngrok... listening on https://ffffffff.ngrok.io/callback ``` -------------------------------- ### Navigate to Example Directory Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot-ts-cjs/README.md Change your current directory to the echo bot example. ```bash cd line-bot-sdk-nodejs/examples/echo-bot-ts-cjs ``` -------------------------------- ### Install Dependencies and Build SDK Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot-ts-cjs/README.md Install all necessary project dependencies and build the SDK. ```bash npm run build-sdk npm install ``` -------------------------------- ### Install Dependencies Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/rich-menu/README.md Installs the necessary dependencies for the SDK. Run these commands in your project directory. ```shell $ npm run build-sdk $ npm install ``` -------------------------------- ### Install npm Dependencies Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/kitchensink/README.md Install SDK and project dependencies. Ensure FFmpeg and ImageMagick are installed for media echoing. ```bash npm run build-sdk # build SDK installed from local directory npm install ``` -------------------------------- ### Install LINE SDK for Node.js via npm Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/getting-started/install.md Install the SDK using npm. This is the recommended method for most users. ```bash $ npm install @line/bot-sdk ``` -------------------------------- ### Install Dependencies Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot/README.md Install the necessary dependencies for the echo bot project. ```shell $ npm build-sdk $ npm install ``` -------------------------------- ### Build and Run the Application Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot-ts-cjs/README.md Compile the TypeScript code and start the echo bot application. ```bash npm run build npm start ``` -------------------------------- ### Start Webhook Server Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/kitchensink/README.md Starts the LINE bot's webhook server. The server will listen on the configured port and base URL. ```bash npm start ``` -------------------------------- ### Install LINE Messaging API SDK for Node.js Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/README.md Install the SDK using npm, yarn, or pnpm. Ensure you have Node.js 20 or higher. ```bash npm install @line/bot-sdk ``` ```bash yarn add @line/bot-sdk ``` ```bash pnpm add @line/bot-sdk ``` -------------------------------- ### Clone the Repository Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot-ts-cjs/README.md Use this command to get the project files. ```bash git clone https://github.com/line/line-bot-sdk-nodejs.git ``` -------------------------------- ### Install SDK Version 10.8.0 Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md Update your project to version 10.8.0 of the `@line/bot-sdk` package to begin the migration process. This version allows both legacy and new APIs to coexist. ```sh npm install --ignore-scripts @line/bot-sdk@10.8.0 ``` -------------------------------- ### Install LINE Bot SDK for Node.js Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Install the SDK using npm, yarn, or pnpm. This package is required to use the LINE Bot SDK in your Node.js project. ```bash npm install @line/bot-sdk # or yarn add @line/bot-sdk # or pnpm add @line/bot-sdk ``` -------------------------------- ### Build LINE SDK for Node.js from Source Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/getting-started/install.md Clone the repository and run npm install and build scripts to build the SDK from source. The built files will be in the dist/ directory. ```bash $ git clone https://github.com/line/line-bot-sdk-nodejs $ cd line-bot-sdk-nodejs $ npm install $ npm run build ``` -------------------------------- ### Run the Echo Bot Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot/README.md Start the LINE echo bot application by running the main script. ```shell $ node . ``` -------------------------------- ### Set Environment Variables Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/kitchensink/README.md Configure the bot using environment variables for channel secret, access token, base URL, and port. Example shown for Bash. ```bash export CHANNEL_SECRET=YOUR_CHANNEL_SECRET export CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN export BASE_URL=https://your.base.url # for static file serving export PORT=1234 ``` -------------------------------- ### Get Response Headers and Status Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/client.md Use `~WithHttpInfo` functions to retrieve response headers, such as 'x-line-request-id', and the HTTP status code from API calls. ```javascript await client .replyMessageWithHttpInfo({ replyToken: replyToken, messages: [message] }) .then((response) => { console.log(response.httpResponse.headers.get('x-line-request-id')); console.log(response.httpResponse.status); }); ``` -------------------------------- ### Echoing Webhook Server with Express Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/getting-started/basic-usage.md A full example of an Express server that uses the LINE Bot SDK middleware to handle incoming messages and reply with an echo of the text message. Ensure your environment variables CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN are set. ```javascript import * as line from '@line/bot-sdk' import express from 'express' // create LINE SDK config from env variables const config = { channelSecret: process.env.CHANNEL_SECRET, }; // create LINE SDK client const client = line.LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN }); // create Express app // about Express itself: https://expressjs.com/ const app = express(); // register a webhook handler with middleware // about the middleware, please refer to doc app.post('/callback', line.middleware(config), (req, res) => { Promise .all(req.body.events.map(handleEvent)) .then((result) => res.json(result)) .catch((err) => { console.error(err); res.status(500).end(); }); }); // event handler function handleEvent(event) { if (event.type !== 'message' || event.message.type !== 'text') { // ignore non-text-message event return Promise.resolve(null); } // create an echoing text message const echo = { type: 'text', text: event.message.text }; // use reply API return client.replyMessage({ replyToken: event.replyToken, messages: [echo], }); } // listen on port const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`listening on ${port}`); }); ``` -------------------------------- ### Handle Webhook Errors with Express Middleware Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/webhook.md Implement error middleware to catch and handle SignatureValidationFailed and JSONParseError. This example uses Express.js to set up the middleware and listen for incoming webhook requests. ```javascript import express from 'express' import {middleware, JSONParseError, SignatureValidationFailed} from '@line/bot-sdk' const app = express() const config = { channelSecret: 'YOUR_CHANNEL_SECRET' } app.use(middleware(config)) app.post('/webhook', (req, res) => { res.json(req.body.events) // req.body will be webhook event object }) app.use((err, req, res, next) => { if (err instanceof SignatureValidationFailed) { res.status(401).send(err.signature) return } else if (err instanceof JSONParseError) { res.status(400).send(err.raw) return } next(err) // will throw default 500 }) app.listen(8080) ``` -------------------------------- ### Prevent Typos with TypeScript Configuration Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/typescript.md Use TypeScript to catch typos in configuration objects during compilation. This example shows how a mistyped channel access token would cause a compile-time error. ```typescript const config = { channelAccessToken: "", // typo Token } const c = LineBotClient.fromChannelAccessToken(config) // will throw a compile error ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/rich-menu/README.md Sets up essential environment variables for authentication. Replace placeholders with your actual channel secret and access token. ```shell $ export CHANNEL_SECRET=YOUR_CHANNEL_SECRET $ export CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot-ts-cjs/README.md Set your LINE channel access token, channel secret, and desired port. ```bash export CHANNEL_ACCESS_TOKEN= export CHANNEL_SECRET= export PORT= ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot/README.md Set the required environment variables for your LINE bot. Replace placeholders with your actual channel secret, channel access token, and desired port. ```shell $ export CHANNEL_SECRET=YOUR_CHANNEL_SECRET $ export CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN $ export PORT=1234 ``` -------------------------------- ### Handle Webhook Message Events Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/client.md Process incoming webhook events, specifically message events. This example demonstrates replying to a 'bye' message by leaving a group or room, or responding to a 1-on-1 chat. ```javascript const event = req.body.events[0]; if (event.type === 'message') { const message = event.message; if (message.type === 'text' && message.text === 'bye') { if (event.source.type === 'room') { await client.leaveRoom(event.source.roomId); } else if (event.source.type === 'group') { await client.leaveGroup(event.source.groupId); } else { await client.replyMessage({ replyToken: event.replyToken, messages: [{ type: 'text', text: 'I cannot leave a 1-on-1 chat!', }] }); } } } ``` -------------------------------- ### Configure LINE Bot Client and Middleware Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/getting-started/basic-usage.md Initialize the LINE Bot client with your channel access token and set up the middleware with your channel secret for webhook verification. ```javascript line.LineBotClient.fromChannelAccessToken({ channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN', }); line.middleware({ channelSecret: 'YOUR_CHANNEL_SECRET' }); ``` -------------------------------- ### Build a Webhook Server with Express and LINE SDK Middleware Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/webhook.md Set up an Express server to handle LINE webhook events. The `middleware` from `@line/bot-sdk` automatically validates the signature and parses incoming event objects. ```javascript import express from 'express' import { middleware } from '@line/bot-sdk' const app = express() const config = { channelSecret: 'YOUR_CHANNEL_SECRET' } app.post('/webhook', middleware(config), (req, res) => { req.body.events // webhook event objects from LINE Platform req.body.destination // user ID of the bot ... }) app.listen(8080) ``` -------------------------------- ### client.createRichMenu / client.setRichMenuImage Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Creates a rich menu definition and uploads the associated image, then optionally sets it as default or links it to specific users. ```APIDOC ## `client.createRichMenu(richMenuRequest)` / `client.setRichMenuImage(richMenuId, body)` — Rich menus Creates a rich menu definition and uploads the associated image, then optionally sets it as default or links it to specific users. ```ts import fs from 'node:fs'; import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); // 1. Create the rich menu structure const { richMenuId } = await client.createRichMenu({ size: { width: 2500, height: 1686 }, selected: true, name: 'Main Menu', chatBarText: 'Tap to open', areas: [ { bounds: { x: 0, y: 0, width: 1250, height: 1686 }, action: { type: 'message', label: 'Left', text: 'left tapped' }, }, { bounds: { x: 1250, y: 0, width: 1250, height: 1686 }, action: { type: 'uri', label: 'Right', uri: 'https://example.com' }, }, ], }); console.log(`Created rich menu: ${richMenuId}`); // 2. Upload the image (must be JPEG or PNG, ≤ 1 MB) const imageBuffer = fs.readFileSync('./rich-menu.png'); const imageBlob = new Blob([imageBuffer], { type: 'image/png' }); await client.setRichMenuImage(richMenuId, imageBlob); // 3. Set it as the default for all users await client.setDefaultRichMenu(richMenuId); // Or link to a specific user only await client.linkRichMenuIdToUser('Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', richMenuId); ``` ``` -------------------------------- ### Create LineBotClient Instance Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Instantiate the `LineBotClient` using the static factory method `fromChannelAccessToken`. This client is the main entry point for all bot API operations. Optional URL overrides can be provided for testing or proxying. ```typescript import { LineBotClient, HTTPFetchError } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, // Optional overrides: // apiBaseURL: 'https://api.line.me', // dataApiBaseURL: 'https://api-data.line.me', // managerBaseURL: 'https://manager.line.biz', // defaultHeaders: { 'X-Custom-Header': 'value' }, }); // Verify the client works by fetching bot info try { const botInfo = await client.getBotInfo(); console.log(botInfo.displayName); // "My LINE Bot" console.log(botInfo.userId); // "Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } catch (err) { if (err instanceof HTTPFetchError) { console.error(`HTTP ${err.status}: ${err.body}`); } } ``` -------------------------------- ### Create LineBotClient Instance Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/client.md Instantiate the LineBotClient using a channel access token. This client bundles various LINE bot APIs. ```javascript const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: 'YOUR_CHANNEL_ACCESS_TOKEN', }); ``` -------------------------------- ### Initialize ChannelAccessTokenClient Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/client.md Create an instance of ChannelAccessTokenClient for managing channel access tokens, such as issuing or revoking them. ```javascript import { channelAccessToken } from '@line/bot-sdk'; const tokenClient = new channelAccessToken.ChannelAccessTokenClient({}); ``` -------------------------------- ### Set Up Webhook URL Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/echo-bot-ts-cjs/README.md Configure your LINE Official Account webhook URL. Ensure greeting and auto-response messages are disabled. ```bash https://example.com/callback ``` -------------------------------- ### Generate Client with Custom Generator (Mac/Linux) Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/generator/README.md Use this command to generate a client using your custom line-bot-sdk-nodejs generator. Ensure you replace the placeholder paths with your actual file locations. ```bash 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 ``` -------------------------------- ### Generate Client with Custom Generator (Windows) Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/generator/README.md This command is for Windows users to generate a client using your custom line-bot-sdk-nodejs generator. Note the use of ';' instead of ':' for the classpath separator. ```bash 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 ``` -------------------------------- ### Importing SDK Components in TypeScript Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/typescript.md Demonstrates how to import necessary components from the LINE Bot SDK for Node.js when using TypeScript. This includes the client, middleware, and exception types. ```typescript import { // unified client LineBotClient, // middleware middleware, // webhook webhook, // exceptions JSONParseError, SignatureValidationFailed, } from "@line/bot-sdk"; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: "..." }); ``` -------------------------------- ### Configure Local SDK Dependency Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/kitchensink/README.md Specifies the local path for the @line/bot-sdk package. Update to "*" to use the npm version. ```json { "@line/bot-sdk": "../../" } ``` -------------------------------- ### client.showLoadingAnimation(request) Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Displays a loading animation in a one-on-one chat while the bot processes a request, improving perceived responsiveness. The animation can last up to 60 seconds. ```APIDOC ## `client.showLoadingAnimation(request)` — Loading indicator Displays a loading animation in a one-on-one chat while the bot processes a request, improving perceived responsiveness. ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the chat where the loading animation should be displayed. - **loadingSeconds** (number) - Required - The duration of the loading animation in seconds (up to 60). ### Request Example ```json { "chatId": "Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "loadingSeconds": 10 } ``` ``` -------------------------------- ### client.addLIFFApp(request) / client.getAllLIFFApps() Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Manages LINE Front-end Framework (LIFF) apps by registering, updating, querying, and removing them. ```APIDOC ## `client.addLIFFApp(request)` / `client.getAllLIFFApps()` — LIFF app management Registers, updates, queries, and removes LINE Front-end Framework (LIFF) apps attached to the channel. ```ts import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); // Add a new LIFF app const { liffId } = await client.addLIFFApp({ view: { type: 'full', url: 'https://example.com/liff', }, description: 'My LIFF App', features: { ble: false, qrCode: false }, permanentLinkPattern: 'replace', scope: ['profile', 'chat_message.write'], botPrompt: 'aggressive', }); console.log(`LIFF app ID: ${liffId}`); // Share as: https://liff.line.me/{liffId} // List all LIFF apps const { apps } = await client.getAllLIFFApps(); apps?.forEach(app => console.log(`${app.liffId} -> ${app.view.url}`)); // Update the view URL await client.updateLIFFApp(liffId, { view: { type: 'full', url: 'https://example.com/liff-v2' }, }); // Delete when no longer needed await client.deleteLIFFApp(liffId); ``` ``` -------------------------------- ### Create and Manage Rich Menus with LINE SDK Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Defines a rich menu structure, uploads an associated image, and optionally sets it as default or links it to specific users. Image must be JPEG or PNG and ≤ 1 MB. ```typescript import fs from 'node:fs'; import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); // 1. Create the rich menu structure const { richMenuId } = await client.createRichMenu({ size: { width: 2500, height: 1686 }, selected: true, name: 'Main Menu', chatBarText: 'Tap to open', areas: [ { bounds: { x: 0, y: 0, width: 1250, height: 1686 }, action: { type: 'message', label: 'Left', text: 'left tapped' }, }, { bounds: { x: 1250, y: 0, width: 1250, height: 1686 }, action: { type: 'uri', label: 'Right', uri: 'https://example.com' }, }, ], }); console.log(`Created rich menu: ${richMenuId}`); // 2. Upload the image (must be JPEG or PNG, ≤ 1 MB) const imageBuffer = fs.readFileSync('./rich-menu.png'); const imageBlob = new Blob([imageBuffer], { type: 'image/png' }); await client.setRichMenuImage(richMenuId, imageBlob); // 3. Set it as the default for all users await client.setDefaultRichMenu(richMenuId); // Or link to a specific user only await client.linkRichMenuIdToUser('Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', richMenuId); ``` -------------------------------- ### LineBotClient.fromChannelAccessToken Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Instantiate the LineBotClient using a channel access token. This client is the primary entry point for all bot API operations. Optional URL overrides can be provided for testing or proxying. ```APIDOC ## LineBotClient.fromChannelAccessToken(config) ### Description Creates the main bot client instance. ### Method `LineBotClient.fromChannelAccessToken(config)` ### Parameters - **config** (object) - Required - Configuration object. - **channelAccessToken** (string) - Required - The channel access token for authentication. - **apiBaseURL** (string) - Optional - Override for the base API URL. - **dataApiBaseURL** (string) - Optional - Override for the data API base URL. - **managerBaseURL** (string) - Optional - Override for the manager API base URL. - **defaultHeaders** (object) - Optional - Default headers to include in requests. ### Request Example ```ts import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); ``` ### Response - **LineBotClient** - An instance of the LineBotClient. ### Example Usage ```ts try { const botInfo = await client.getBotInfo(); console.log(botInfo.displayName); console.log(botInfo.userId); } catch (err) { // Handle errors } ``` ``` -------------------------------- ### Upgrade to SDK Version 11 Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md After removing all usages of the legacy API, upgrade to version 11 of the `@line/bot-sdk` package. This version removes the deprecated `Client` and `OAuth` classes and related types. ```sh npm install @line/bot-sdk@11 ``` -------------------------------- ### Configure npm SDK Dependency Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/examples/kitchensink/README.md Specifies to use the latest version of the @line/bot-sdk package from npm. ```json { "@line/bot-sdk": "*" } ``` -------------------------------- ### client.getProfile Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Fetches the display name, profile picture URL, status message, and language of a user. ```APIDOC ## `client.getProfile(userId)` — Retrieve a user's profile Fetches the display name, profile picture URL, status message, and language of a user. ```ts import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); const profile = await client.getProfile('Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); console.log(profile.displayName); // "John Doe" console.log(profile.pictureUrl); // "https://profile.line-scdn.net/" console.log(profile.statusMessage); // "Hello LINE!" console.log(profile.language); // "en" ``` ``` -------------------------------- ### Import LINE Bot SDK Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/getting-started/basic-usage.md Import the LINE Bot SDK for Node.js using either ES Modules/TypeScript or CommonJS syntax. ```javascript import * as line from '@line/bot-sdk'; // CommonJS const line = require('@line/bot-sdk'); ``` -------------------------------- ### Profile & Group Methods Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md This section covers methods related to retrieving user profiles and managing group/room members. Note any renames or changes in pagination behavior. ```APIDOC ## Profile & Group Methods ### `getProfile(userId)` #### Description Retrieves the profile information for a given user ID. #### Method `getProfile(userId)` ### `getGroupMemberProfile(groupId, userId)` #### Description Retrieves the profile information of a member within a specific group. #### Method `getGroupMemberProfile(groupId, userId)` ### `getRoomMemberProfile(roomId, userId)` #### Description Retrieves the profile information of a member within a specific room. #### Method `getRoomMemberProfile(roomId, userId)` ### `getGroupMemberIds(groupId)` #### Description Retrieves a list of member IDs for a given group. This method no longer auto-paginates and returns a single page of results. The method name has been updated from `getGroupMembersIds`. #### Method `getGroupMemberIds(groupId)` ### `getRoomMemberIds(roomId)` #### Description Retrieves a list of member IDs for a given room. This method no longer auto-paginates and returns a single page of results. The method name has been updated from `getRoomMembersIds`. #### Method `getRoomMemberIds(roomId)` ### `getBotFollowersIds()` #### Description Retrieves a list of follower IDs for the bot. This method has been renamed to `getFollowers`. It no longer auto-paginates and returns a single page of results (`GetFollowersResponse`). To retrieve all followers, you need to loop using the `next` token. #### Method `getFollowers(start?, limit?)` ### `getGroupMembersCount(groupId)` #### Description Retrieves the total count of members in a specific group. The method name has been updated from `getGroupMemberCount` (removed 's'). #### Method `getGroupMembersCount(groupId)` ### `getRoomMembersCount(roomId)` #### Description Retrieves the total count of members in a specific room. The method name has been updated from `getRoomMemberCount` (removed 's'). #### Method `getRoomMembersCount(roomId)` ### `getGroupSummary(groupId)` #### Description Retrieves a summary of a specific group. #### Method `getGroupSummary(groupId)` ### `getBotInfo()` #### Description Retrieves information about the bot. #### Method `getBotInfo()` ### `leaveGroup(groupId)` #### Description Allows the bot to leave a specific group. #### Method `leaveGroup(groupId)` ### `leaveRoom(roomId)` #### Description Allows the bot to leave a specific room. #### Method `leaveRoom(roomId)` ``` -------------------------------- ### Show Loading Animation with LINE Bot SDK Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Use this to display a loading animation in a one-on-one chat while the bot processes a request. The animation can last up to 60 seconds. ```typescript import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); async function handleEvent(event: any) { if (event.type !== 'message') return; // Show loading animation immediately (up to 60 seconds) await client.showLoadingAnimation({ chatId: event.source.userId, loadingSeconds: 10, }); // Simulate processing const result = await expensiveOperation(); // Send the actual reply await client.replyMessage({ replyToken: event.replyToken, messages: [{ type: 'text', text: result }], }); } async function expensiveOperation(): Promise { return new Promise(resolve => setTimeout(() => resolve('Done!'), 3000)); } ``` -------------------------------- ### Import LINE Bot SDK Modules Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Import necessary modules from the SDK for use in your project. Supports both ESM/TypeScript and CommonJS module systems. ```typescript // ESM / TypeScript import { LineBotClient, middleware, webhook, channelAccessToken } from '@line/bot-sdk'; // CommonJS const { LineBotClient, middleware } = require('@line/bot-sdk'); ``` -------------------------------- ### Instantiate ChannelAccessTokenClient Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md Use this to instantiate the `ChannelAccessTokenClient` for OAuth-related operations. It is constructed without a channel access token. ```javascript const { channelAccessToken } = require('@line/bot-sdk'); const oauthClient = new channelAccessToken.ChannelAccessTokenClient({}); ``` -------------------------------- ### Replace Client Construction Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md Update how you instantiate the client and OAuth objects. The new `LineBotClient` is constructed using `fromChannelAccessToken`, and `ChannelAccessTokenClient` is used for OAuth operations. ```javascript // Before const { Client, OAuth } = require('@line/bot-sdk'); const client = new Client({ channelAccessToken: '...' }); const oauth = new OAuth(); // After const { LineBotClient, channelAccessToken } = require('@line/bot-sdk'); const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: '...' }); const oauthClient = new channelAccessToken.ChannelAccessTokenClient({}); ``` -------------------------------- ### Method Mapping: multicast Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md Demonstrates the signature update for the `multicast` method, requiring arguments to be passed as a request object and the retry key as a second parameter. ```typescript multicast(to, messages, notificationDisabled?, customAggregationUnits?) ``` ```typescript multicast({ to, messages, notificationDisabled, customAggregationUnits }, xLineRetryKey?) ``` -------------------------------- ### Rich Menu Operations Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md This section details the migration of Rich Menu related client methods to their corresponding LineBotClient methods, noting any changes in parameters or return types. ```APIDOC ## Rich Menu Operations ### getRichMenu - **Description**: Retrieves a rich menu. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu to retrieve. ### createRichMenu - **Description**: Creates a new rich menu. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuRequest** (object) - Required - The rich menu object to create. - **Notes**: Return type changed from `string` to `RichMenuIdResponse`. ### deleteRichMenu - **Description**: Deletes a rich menu. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu to delete. ### getRichMenuAliasList - **Description**: Retrieves a list of rich menu aliases. - **Method**: N/A (SDK Method) ### getRichMenuAlias - **Description**: Retrieves a specific rich menu alias. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuAliasId** (string) - Required - The ID of the rich menu alias to retrieve. ### createRichMenuAlias - **Description**: Creates a rich menu alias. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu. - **richMenuAliasId** (string) - Required - The alias ID for the rich menu. - **Notes**: Arguments wrapped in a request object. ### deleteRichMenuAlias - **Description**: Deletes a rich menu alias. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuAliasId** (string) - Required - The ID of the rich menu alias to delete. ### updateRichMenuAlias - **Description**: Updates a rich menu alias. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuAliasId** (string) - Required - The ID of the rich menu alias to update. - **richMenuId** (string) - Required - The new rich menu ID to associate with the alias. - **Notes**: 2nd argument wrapped in a request object. ### getRichMenuIdOfUser - **Description**: Retrieves the rich menu ID associated with a user. - **Method**: N/A (SDK Method) - **Parameters**: - **userId** (string) - Required - The ID of the user. - **Notes**: Return type changed from `string` to `RichMenuIdResponse`. ### linkRichMenuToUser - **Description**: Links a rich menu to a user. - **Method**: N/A (SDK Method) - **Parameters**: - **userId** (string) - Required - The ID of the user. - **richMenuId** (string) - Required - The ID of the rich menu to link. - **Notes**: Renamed from `linkRichMenuToUser`. ### unlinkRichMenuFromUser - **Description**: Unlinks a rich menu from a user. - **Method**: N/A (SDK Method) - **Parameters**: - **userId** (string) - Required - The ID of the user. - **Notes**: Renamed from `unlinkRichMenuFromUser`. ### linkRichMenuToMultipleUsers - **Description**: Links a rich menu to multiple users. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu. - **userIds** (string[]) - Required - An array of user IDs. - **Notes**: Renamed from `linkRichMenuToMultipleUsers`. Arguments wrapped in a request object. ### unlinkRichMenusFromMultipleUsers - **Description**: Unlinks rich menus from multiple users. - **Method**: N/A (SDK Method) - **Parameters**: - **userIds** (string[]) - Required - An array of user IDs. - **Notes**: Renamed from `unlinkRichMenusFromMultipleUsers`. Arguments wrapped in a request object. ### getRichMenuImage - **Description**: Retrieves the image of a rich menu. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu. ### setRichMenuImage - **Description**: Sets the image for a rich menu. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu. - **body** (Blob) - Optional - The image data. - **Notes**: `body` is now `Blob` (optional) instead of `Buffer | Readable`. `contentType` removed. ### getRichMenuList - **Description**: Retrieves a list of all rich menus. - **Method**: N/A (SDK Method) - **Notes**: Return type changed from `RichMenuResponse[]` to `RichMenuListResponse`. ### setDefaultRichMenu - **Description**: Sets a default rich menu for users. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenuId** (string) - Required - The ID of the rich menu to set as default. ### getDefaultRichMenuId - **Description**: Retrieves the ID of the default rich menu. - **Method**: N/A (SDK Method) - **Notes**: Return type changed from `string` to `RichMenuIdResponse`. ### cancelDefaultRichMenu - **Description**: Cancels the default rich menu setting. - **Method**: N/A (SDK Method) - **Notes**: Renamed from `deleteDefaultRichMenu`. ### validateRichMenuObject - **Description**: Validates a rich menu object. - **Method**: N/A (SDK Method) - **Parameters**: - **richMenu** (object) - Required - The rich menu object to validate. - **Notes**: Renamed from `validateRichMenu`. ``` -------------------------------- ### Retrieve User Profile with LINE SDK Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Fetches a user's display name, profile picture URL, status message, and language. Requires the user's ID. ```typescript import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); const profile = await client.getProfile('Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); console.log(profile.displayName); // "John Doe" console.log(profile.pictureUrl); // "https://profile.line-scdn.net/..." console.log(profile.statusMessage); // "Hello LINE!" console.log(profile.language); // "en" ``` -------------------------------- ### client.missionStickerV3(request) Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Sends a mission sticker to a user as part of a sticker campaign. This is a partner API for specific campaign integrations. ```APIDOC ## `client.missionStickerV3(request)` — Send mission stickers Sends a mission sticker to a user as part of a sticker campaign (partner API). ### Parameters #### Request Body - **to** (string) - Required - The user ID of the recipient. - **packageId** (number) - Required - The ID of the sticker package. - **stickerId** (number) - Required - The ID of the sticker. - **subscriberId** (string) - Required - The unique ID of the subscriber. - **lang** (string) - Optional - The language code for the sticker (e.g., 'en'). ### Request Example ```json { "to": "Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "packageId": 12345, "stickerId": 98765, "subscriberId": "user-unique-id-001", "lang": "en" } ``` ``` -------------------------------- ### middleware Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Generates a Connect-compatible middleware for Express/Connect servers. It validates the `X-Line-Signature` header and parses the JSON body, ensuring secure and efficient handling of incoming webhook events. ```APIDOC ## middleware(config) ### Description Provides Express/Connect-compatible middleware for handling webhook requests. It verifies the request signature and parses the request body. ### Method `middleware(config)` ### Parameters - **config** (object) - Required - Configuration object. - **channelSecret** (string) - Required - The channel secret for signature validation. ### Request Example ```ts import express from 'express'; import { middleware, LineBotClient } from '@line/bot-sdk'; const middlewareConfig = { channelSecret: process.env.CHANNEL_SECRET!, }; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); const app = express(); app.post('/callback', middleware(middlewareConfig), async (req, res) => { const body = req.body; await Promise.all(body.events!.map(handleEvent)); res.status(200).json({ status: 'ok' }); }); ``` ### Error Handling - **SignatureValidationFailed**: Thrown if the signature is invalid. - **JSONParseError**: Thrown if the request body is not valid JSON. ``` -------------------------------- ### Manage LIFF Apps Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Provides functionality to register, update, query, and delete LINE Front-end Framework (LIFF) apps. Requires `CHANNEL_ACCESS_TOKEN` to be configured. ```typescript import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); // Add a new LIFF app const { liffId } = await client.addLIFFApp({ view: { type: 'full', url: 'https://example.com/liff', }, description: 'My LIFF App', features: { ble: false, qrCode: false }, permanentLinkPattern: 'replace', scope: ['profile', 'chat_message.write'], botPrompt: 'aggressive', }); console.log(`LIFF app ID: ${liffId}`); // Share as: https://liff.line.me/{liffId} // List all LIFF apps const { apps } = await client.getAllLIFFApps(); apps?.forEach(app => console.log(`${app.liffId} -> ${app.view.url}`)); // Update the view URL await client.updateLIFFApp(liffId, { view: { type: 'full', url: 'https://example.com/liff-v2' }, }); // Delete when no longer needed await client.deleteLIFFApp(liffId); ``` -------------------------------- ### Error Handling: Legacy Client vs. LineBotClient Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md Compares error handling between the legacy axios-based Client and the new fetch-based LineBotClient. Note the different error types and property access for status, headers, and body. ```typescript // Before (legacy Client — axios-based) import { HTTPError } from '@line/bot-sdk'; try { await client.pushMessage(to, messages); } catch (err) { if (err instanceof HTTPError) { console.error(err.originalError.response.status); console.error(err.originalError.response.headers.get('x-line-request-id')); console.error(err.originalError.response.data); // parsed JSON } } ``` ```typescript // After (LineBotClient — fetch-based) import { HTTPFetchError } from '@line/bot-sdk'; try { await client.pushMessage({ to, messages }); } catch (err) { if (err instanceof HTTPFetchError) { console.error(err.status); console.error(err.headers.get('x-line-request-id')); console.error(err.body); // raw string — JSON.parse() if needed } } ``` -------------------------------- ### Import LineBotClient Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/client.md Import the LineBotClient class for use in ES modules or TypeScript, or using CommonJS. ```javascript // ES modules or TypeScript import { LineBotClient } from '@line/bot-sdk'; // CommonJS const { LineBotClient } = require('@line/bot-sdk'); ``` -------------------------------- ### Link Token Operations Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md This section details the migration of Link Token related client methods to their corresponding LineBotClient methods, noting any changes in parameters or return types. ```APIDOC ## Link Token Operations ### issueLinkToken - **Description**: Issues a link token for a user. - **Method**: N/A (SDK Method) - **Parameters**: - **userId** (string) - Required - The ID of the user for whom to issue the link token. - **Notes**: Renamed from `getLinkToken`. Return type changed from `string` to `IssueLinkTokenResponse`. ``` -------------------------------- ### Create Audience Group from Text File Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Creates an audience group by uploading a text file containing user IDs, with one ID per line. The `CHANNEL_ACCESS_TOKEN` must be configured. ```typescript // Or upload via a text file (one user ID per line) const fileBlob = new Blob(['Uxxxxxxxx\nUyyyyyyyy\n'], { type: 'text/plain' }); const { audienceGroupId: fileAudienceId } = await client.createAudienceForUploadingUserIds( fileBlob, 'File-based audience', false, // isIfaAudience 'batch import', // uploadDescription ); ``` -------------------------------- ### client.getMessageContent Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Downloads image, video, or audio content sent by a user, returning a Node.js `Readable` stream. ```APIDOC ## `client.getMessageContent(messageId)` — Download user-sent media Downloads image, video, or audio content sent by a user, returning a Node.js `Readable` stream. ```ts import fs from 'node:fs'; import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); // In a webhook handler for a message event with message.type === 'image' async function saveUserImage(messageId: string) { const stream = await client.getMessageContent(messageId); await new Promise((resolve, reject) => { const dest = fs.createWriteStream(`/tmp/${messageId}.jpg`); stream.pipe(dest); stream.on('error', reject); dest.on('finish', resolve); }); console.log(`Saved image to /tmp/${messageId}.jpg`); } ``` ``` -------------------------------- ### Method Mapping: pushMessage Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md Illustrates the change in the `pushMessage` method signature from the legacy Client to LineBotClient. Arguments are now wrapped in a request object, and the retry key is a separate parameter. ```typescript pushMessage(to, messages, notificationDisabled?, customAggregationUnits?) ``` ```typescript pushMessage({ to, messages, notificationDisabled, customAggregationUnits }, xLineRetryKey?) ``` -------------------------------- ### client.getBotInfo Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Fetches information about the bot, such as its display name and user ID. This method can be used to verify that the bot client is configured correctly and can communicate with the LINE platform. ```APIDOC ## client.getBotInfo() ### Description Fetches information about the bot associated with the client. ### Method `client.getBotInfo()` ### Parameters None ### Response #### Success Response (200) - **displayName** (string) - The display name of the bot. - **userId** (string) - The user ID of the bot. ### Request Example ```ts try { const botInfo = await client.getBotInfo(); console.log(botInfo.displayName); console.log(botInfo.userId); } catch (err) { // Handle errors } ``` ``` -------------------------------- ### client.multicast Source: https://context7.com/line/line-bot-sdk-nodejs/llms.txt Efficiently delivers the same message to a list of up to 500 user IDs in one call. Cannot target groups or multi-person chats. ```APIDOC ## `client.multicast(request, xLineRetryKey?)` — Send to multiple users Efficiently delivers the same message to a list of up to 500 user IDs in one call. Cannot target groups or multi-person chats. ```ts import { LineBotClient } from '@line/bot-sdk'; const client = LineBotClient.fromChannelAccessToken({ channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN!, }); await client.multicast({ to: [ 'Uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Uyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy', 'Uzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz', ], messages: [ { type: 'template', altText: 'Confirm template', template: { type: 'confirm', text: 'Are you sure?', actions: [ { type: 'message', label: 'Yes', text: 'yes' }, { type: 'message', label: 'No', text: 'no' }, ], }, }, ], }); ``` ``` -------------------------------- ### Webhook Operations Source: https://github.com/line/line-bot-sdk-nodejs/blob/master/docs/guide/migration.md This section details the migration of Webhook related client methods to their corresponding LineBotClient methods, noting any changes in parameters or return types. ```APIDOC ## Webhook Operations ### setWebhookEndpoint - **Description**: Sets the webhook endpoint URL. - **Method**: N/A (SDK Method) - **Parameters**: - **endpoint** (string) - Required - The URL for the webhook endpoint. - **Notes**: Renamed from `setWebhookEndpointUrl`. Argument wrapped in a request object. ### getWebhookEndpoint - **Description**: Retrieves the current webhook endpoint information. - **Method**: N/A (SDK Method) ### testWebhookEndpoint - **Description**: Tests the webhook endpoint. - **Method**: N/A (SDK Method) - **Parameters**: - **endpoint** (string) - Optional - The URL to test. If not provided, the current endpoint is used. - **Notes**: Argument wrapped in a request object. The entire request object is optional. ```