### Install Dependencies with Bundler Source: https://github.com/line/line-bot-sdk-ruby/blob/master/CONTRIBUTING.md Run this command to install all necessary dependencies for development. Ensure you have Bundler installed. ```bash bundle install ``` -------------------------------- ### Set Up Environment Variables and Install Dependencies Source: https://github.com/line/line-bot-sdk-ruby/blob/master/examples/v2/rich_menu/README.md Configure your LINE channel secret and access token as environment variables. Then, install the necessary Ruby gems and run the application. ```sh $ export LINE_CHANNEL_SECRET=YOUR_CHANNEL_SECRET $ export LINE_CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN $ bundle install $ bundle exec ruby app.rb ``` -------------------------------- ### Set Up Environment Variables and Install Dependencies Source: https://github.com/line/line-bot-sdk-ruby/blob/master/examples/v2/channel_access_token/README.md Before running the script, set the LINE_CHANNEL_ID and LINE_CHANNEL_SECRET environment variables. Then, install the necessary Ruby gems. ```sh $ export LINE_CHANNEL_ID=YOUR_CHANNEL_ID $ export LINE_CHANNEL_SECRET=YOUR_CHANNEL_SECRET $ bundle install $ bundle exec ruby app.rb ``` -------------------------------- ### Start Local YARD Documentation Server Source: https://github.com/line/line-bot-sdk-ruby/blob/master/CONTRIBUTING.md Run this command to start a local YARD server that automatically reloads when files change. Open the printed URL in your browser. ```bash bundle exec yard server --reload ``` -------------------------------- ### Set Up and Run Echo Bot Source: https://github.com/line/line-bot-sdk-ruby/blob/master/examples/v2/echobot/README.md Configure necessary environment variables for LINE channel secret and access token, install dependencies, set the application base URL, and then run the bot application. ```sh $ export LINE_CHANNEL_SECRET=YOUR_CHANNEL_SECRET $ export LINE_CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN $ bundle install $ export APP_BASE_URL="https://your.base.url:4567" $ bundle exec ruby app.rb ``` -------------------------------- ### Install LINE Bot API Gem Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md Add the line-bot-api gem to your application's Gemfile for installation. ```ruby gem 'line-bot-api' ``` -------------------------------- ### Error Handling with HTTP Info Methods Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Utilizes `*_with_http_info` methods to retrieve HTTP status codes and headers, enabling robust error handling for API requests. This example demonstrates handling success, bad requests, and rate limiting. ```ruby require 'json' body, status_code, headers = client.push_message_with_http_info( push_message_request: Line::Bot::V2::MessagingApi::PushMessageRequest.new( to: user_id, messages: [Line::Bot::V2::MessagingApi::TextMessage.new(text: "Hello")] ) ) case status_code when 200 puts "Success! Request ID: #{headers['x-line-request-id']}" when 400 puts "Bad request: #{body.message}" body.details&.each { |d| puts " - #{d.message}" } when 429 puts "Rate limited. Try again later." else puts "Error: #{status_code}" end ``` -------------------------------- ### Get Group Information with Ruby SDK Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Retrieve summary information, member count, and member profiles for a LINE group. Handles paginated retrieval of all member IDs. ```ruby # Get group summary summary = client.get_group_summary(group_id: "C4af4980629...") puts "Group name: #{summary.group_name}" puts "Picture URL: #{summary.picture_url}" ``` ```ruby # Get group member count count = client.get_group_member_count(group_id: "C4af4980629...") puts "Members: #{count.count}" ``` ```ruby # Get member profile in group profile = client.get_group_member_profile(group_id: "C4af4980629...", user_id: "U4af4980629...") puts "Display name: #{profile.display_name}" ``` ```ruby # Get all member IDs (paginated) response = client.get_group_members_ids(group_id: "C4af4980629...") user_ids = response.member_ids while response._next response = client.get_group_members_ids(group_id: "C4af4980629...", start: response._next) user_ids.concat(response.member_ids) end ``` -------------------------------- ### Get User Profile Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Retrieves a user's display name, profile picture URL, and status message using their user ID. ```APIDOC ## get_profile - Get User Profile ### Description Retrieves a user's display name, profile picture URL, and status message. ### Method GET ### Endpoint `/v2/bot/profile/{userId}` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user whose profile to retrieve. ### Request Example ```ruby profile = client.get_profile(user_id: "U4af4980629...") puts "Display name: #{profile.display_name}" puts "Picture URL: #{profile.picture_url}" puts "Status message: #{profile.status_message}" ``` ### Response #### Success Response (200) - **displayName** (string) - The user's display name. - **pictureUrl** (string) - The URL of the user's profile picture. - **statusMessage** (string) - The user's status message. #### Response Example ```json { "displayName": "John Doe", "pictureUrl": "https://example.com/profile.jpg", "statusMessage": "Hello there!" } ``` ``` -------------------------------- ### Get User Profile Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Retrieves a user's display name, profile picture URL, and status message using their user ID. Ensure you have the necessary permissions to access user profiles. ```ruby profile = client.get_profile(user_id: "U4af4980629...") puts "Display name: #{profile.display_name}" puts "Picture URL: #{profile.picture_url}" puts "Status message: #{profile.status_message}" ``` -------------------------------- ### Get Analytics and Statistics Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Retrieves analytics data such as friend demographics, follower counts, and message event statistics using the `Insight::ApiClient`. Ensure the `LINE_CHANNEL_ACCESS_TOKEN` environment variable is set. ```ruby insight_client = Line::Bot::V2::Insight::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) # Get friend demographics demographics = insight_client.get_friends_demographics puts "Available: #{demographics.available}" demographics.genders&.each do |g| puts "#{g.gender}: #{g.percentage}%%" end # Get number of followers followers = insight_client.get_number_of_followers(date: '20240101') puts "Total followers: #{followers.followers}" puts "Targeted reach: #{followers.targeted_reaches}" puts "Blocks: #{followers.blocks}" # Get message event statistics (requires request ID from broadcast/narrowcast) stats = insight_client.get_message_event(request_id: 'request-id-from-broadcast') puts "Delivered: #{stats.overview&.delivered}" puts "Unique impressions: #{stats.overview&.unique_impression}" ``` -------------------------------- ### Handle API Errors in Ruby Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md Use the status code for error handling when API calls fail. Error details are available in the response body. This example demonstrates validating messages with both valid and invalid requests. ```ruby require 'json' require 'line-bot-api' def client @client ||= Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN"), ) end def main dummy_message = Line::Bot::V2::MessagingApi::TextMessage.new( text: "Hello, world!", ) valid_request = Line::Bot::V2::MessagingApi::ValidateMessageRequest.new( messages: [dummy_message, dummy_message, dummy_message, dummy_message, dummy_message], ) body, status_code, _headers = client.validate_push_with_http_info(validate_message_request: valid_request) handle_response(body, status_code) invalid_request = Line::Bot::V2::MessagingApi::ValidateMessageRequest.new( messages: [dummy_message, dummy_message, dummy_message, dummy_message, dummy_message, dummy_message], ) body, status_code, _headers = client.validate_push_with_http_info(validate_message_request: invalid_request) handle_response(body, status_code) end def handle_response(body, status_code) case status_code when 200 puts "Valid" when 400..499 puts "Invalid: #{JSON.parse(body)}" else puts "Other Status: #{status_code}" end end main ``` -------------------------------- ### Initialize ApiBlobClient with Ruby Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Instantiate the `ApiBlobClient` for handling binary content like uploading rich menu images or downloading media. Configure timeouts using `http_options`. ```ruby blob_client = Line::Bot::V2::MessagingApi::ApiBlobClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN"), http_options: { open_timeout: 10, read_timeout: 30 } ) ``` -------------------------------- ### Initialize v1 LINE Bot Client Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Initializes the v1 LINE Bot client using a channel access token from the environment variables. ```ruby client = Line::Bot::Client.new do |config| config.channel_token = ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") end ``` -------------------------------- ### Create and Manage Rich Menus with Ruby Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Programmatically create rich menus with defined areas and actions, upload associated images, and link them to users. Requires `LINE_CHANNEL_ACCESS_TOKEN` environment variable. ```ruby # Create rich menu rich_menu_request = Line::Bot::V2::MessagingApi::RichMenuRequest.new( size: Line::Bot::V2::MessagingApi::RichMenuSize.new(width: 2500, height: 1686), selected: false, name: 'Main Menu', chat_bar_text: 'Tap to open menu', areas: [ Line::Bot::V2::MessagingApi::RichMenuArea.new( bounds: Line::Bot::V2::MessagingApi::RichMenuBounds.new(x: 0, y: 0, width: 1250, height: 843), action: Line::Bot::V2::MessagingApi::MessageAction.new(label: 'Shop', text: 'Show shop') ), Line::Bot::V2::MessagingApi::RichMenuArea.new( bounds: Line::Bot::V2::MessagingApi::RichMenuBounds.new(x: 1250, y: 0, width: 1250, height: 843), action: Line::Bot::V2::MessagingApi::URIAction.new(label: 'Website', uri: 'https://example.com') ) ] ) response = client.create_rich_menu(rich_menu_request: rich_menu_request) rich_menu_id = response.rich_menu_id # Upload rich menu image blob_client = Line::Bot::V2::MessagingApi::ApiBlobClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) blob_client.set_rich_menu_image( rich_menu_id: rich_menu_id, body: File.open('./richmenu.png') ) # Set as default for all users client.set_default_rich_menu(rich_menu_id: rich_menu_id) # Or link to specific user client.link_rich_menu_id_to_user(user_id: "U4af4980629...", rich_menu_id: rich_menu_id) ``` -------------------------------- ### Initialize MessagingApi::ApiClient Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Instantiate the main API client for LINE Messaging API operations. Configure HTTP options like timeouts for custom behavior. ```ruby require 'line-bot-api' def client @client ||= Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN"), http_options: { open_timeout: 5, read_timeout: 5 } ) end ``` -------------------------------- ### Use HTTP Information Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md How to use `*_with_http_info` methods to retrieve response headers like `x-line-request-id`. ```APIDOC ## Use HTTP Information You may need to store the `x-line-request-id` header obtained as a response from several APIs. In this case, please use `*_with_http_info` methods. You can get headers and status codes. The `x-line-accepted-request-id` or `content-type` header can also be obtained in the same way. Note header name must be lowercase. ### Request Example ```ruby push_request = Line::Bot::V2::MessagingApi::PushMessageRequest.new( to: event.source.user_id, messages: [ Line::Bot::V2::MessagingApi::TextMessage.new(text: "[^Request ID] #{headers['x-line-request-id']}") ] ) _body, _status_code, headers = client.push_message_with_http_info(push_message_request: push_request) puts headers['x-line-request-id'] puts headers['x-line-accepted-request-id'] puts headers['content-type'] ``` ### Response Example - **`x-line-request-id`** (string) - The unique identifier for the request. - **`x-line-accepted-request-id`** (string) - The accepted request identifier. - **`content-type`** (string) - The content type of the response. ``` -------------------------------- ### Manage Channel Access Tokens Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Demonstrates managing channel access tokens using the `ChannelAccessToken::ApiClient`. This includes issuing short-lived and stateless tokens, verifying token validity, and revoking tokens. ```ruby token_client = Line::Bot::V2::ChannelAccessToken::ApiClient.new # Issue short-lived channel access token response = token_client.issue_channel_token( grant_type: 'client_credentials', client_id: ENV['LINE_CHANNEL_ID'], client_secret: ENV['LINE_CHANNEL_SECRET'] ) puts "Access token: #{response.access_token}" puts "Expires in: #{response.expires_in} seconds" # Verify token validity verify_response = token_client.verify_channel_token(access_token: response.access_token) puts "Token valid for: #{verify_response.expires_in} seconds" # Revoke token token_client.revoke_channel_token(access_token: response.access_token) # Issue stateless token (15 min validity, no revocation) stateless = token_client.issue_stateless_channel_token_by_client_secret( client_id: ENV['LINE_CHANNEL_ID'], client_secret: ENV['LINE_CHANNEL_SECRET'] ) ``` -------------------------------- ### Initialize v2 Messaging API Client with Hash for request Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Initializes the v2 Messaging API client and constructs a PushMessageRequest using a Hash for the messages. This method is less recommended but can ease v1 migration. ```ruby client = Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) request = Line::Bot::V2::MessagingApi::PushMessageRequest.new( to: 'U1234567890abcdef1234567890abcdef', messages: [ { type: 'text', text: 'Hello, this is a test message!' } ] ) response, status_code, response_headers = client.push_message_with_http_info( push_message_request: request ) puts response.class # => Line::Bot::V2::MessagingApi::PushMessageResponse ``` -------------------------------- ### Initialize v2 Messaging API Client with class Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Initializes the v2 Messaging API client using a channel access token. It utilizes specific classes for message types and requests. ```ruby client = Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) ``` -------------------------------- ### LINE Bot SDK Ruby API Clients Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md Overview of API client classes and their endpoints. ```APIDOC ## LINE Bot SDK Ruby API Clients This section outlines the various API client classes provided by the LINE Bot SDK for Ruby, along with their corresponding API endpoints. ### Channel Access Token API Client - **Class**: `Line::Bot::V2::ChannelAccessToken::ApiClient` - **Endpoint**: `https://api.line.me/` (related to oauth) - **Reference**: [LINE Developers - Channel Access Token](https://developers.line.biz/en/reference/messaging-api/#channel-access-token) ### Insight API Client - **Class**: `Line::Bot::V2::Insight::ApiClient` - **Endpoint**: `https://api.line.me/v2/bot/insight/` - **Reference**: [LINE Developers - Get Insight](https://developers.line.biz/en/reference/messaging-api/#get-insight) ### LIFF API Client - **Class**: `Line::Bot::V2::Liff::ApiClient` - **Endpoint**: `https://api.line.me/liff/` - **Reference**: [LINE Developers - LIFF Server API](https://developers.line.biz/en/reference/liff-server/#server-api) ### Manage Audience API Client - **Class**: `Line::Bot::V2::ManageAudience::ApiClient` - **Endpoint**: `https://api.line.me/v2/bot/audienceGroup/` - **Reference**: [LINE Developers - Manage Audience Group](https://developers.line.biz/en/reference/messaging-api/#manage-audience-group) ### Manage Audience Blob API Client - **Class**: `Line::Bot::V2::ManageAudience::ApiBlobClient` - **Endpoint**: `https://api-data.line.me/v2/bot/audienceGroup/` - **Reference**: [LINE Developers - Manage Audience Group](https://developers.line.biz/en/reference/messaging-api/#manage-audience-group) ### Messaging API Client - **Class**: `Line::Bot::V2::MessagingApi::ApiClient` - **Endpoint**: `https://api.line.me/v2/bot/` - **Reference**: [LINE Developers - Messaging API](https://developers.line.biz/en/reference/messaging-api/) - **Reference**: [LINE Developers - Partner Docs](https://developers.line.biz/en/reference/partner-docs/) ### Messaging API Blob Client - **Class**: `Line::Bot::V2::MessagingApi::ApiBlobClient` - **Endpoint**: `https://api-data.line.me/v2/bot/` - **Reference**: [LINE Developers - Messaging API](https://developers.line.biz/en/reference/messaging-api/) ### Module API Client - **Class**: `Line::Bot::V2::Module::ApiClient` - **Endpoint**: `https://api.line.me/v2/bot/` (related to module) - **Reference**: [LINE Developers - Module](https://developers.line.biz/en/reference/partner-docs/#module) ### Module Attach API Client - **Class**: `Line::Bot::V2::ModuleAttach::ApiClient` - **Endpoint**: `https://manager.line.biz/module/auth/v1/token/` - **Reference**: [LINE Developers - Module](https://developers.line.biz/en/reference/partner-docs/#module) ### Shop API Client - **Class**: `Line::Bot::V2::Shop::ApiClient` - **Endpoint**: `https://api.line.me/shop/` - **Reference**: [LINE Developers - Mission Stickers](https://developers.line.biz/en/reference/partner-docs/#mission-stickers) ``` -------------------------------- ### Basic LINE Bot Callback Handler Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md This Ruby code sets up a Sinatra application to handle LINE Messaging API callbacks. It includes client initialization for messaging and blob operations, webhook parsing, and event handling for text, image, and video messages. Ensure LINE_CHANNEL_ACCESS_TOKEN and LINE_CHANNEL_SECRET environment variables are set. ```ruby # app.rb require 'sinatra' require 'line-bot-api' set :environment, :production def client @client ||= Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) end def blob_client @blob_client ||= Line::Bot::V2::MessagingApi::ApiBlobClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) end def parser @parser ||= Line::Bot::V2::WebhookParser.new(channel_secret: ENV.fetch("LINE_CHANNEL_SECRET")) end post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] begin events = parser.parse(body: body, signature: signature) rescue Line::Bot::V2::WebhookParser::InvalidSignatureError halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request' end events.each do |event| case event when Line::Bot::V2::Webhook::MessageEvent case event.message when Line::Bot::V2::Webhook::TextMessageContent case event.message.text when 'profile' if event.source.type == 'user' profile_response = client.get_profile(user_id: event.source.user_id) reply_text(event, "Display name: #{profile_response.display_name}\nStatus message: #{profile_response.status_message}") else reply_text(event, "Bot can't use profile API without user ID") end else request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::TextMessage.new(text: "[ECHO] #{event.message.text}") ] ) client.reply_message(reply_message_request: request) end when Line::Bot::V2::Webhook::ImageMessageContent, Line::Bot::V2::Webhook::VideoMessageContent response = blob_client.get_message_content(message_id: event.message.message_id) tf = Tempfile.open("content") tf.write(response) end end end # Don't forget to return a successful response "OK" end ``` -------------------------------- ### Validate YARD Documentation Coverage Source: https://github.com/line/line-bot-sdk-ruby/blob/master/CONTRIBUTING.md Execute this command before pushing changes to check YARD documentation coverage and warnings. Fix any reported issues. ```bash bundle exec yard stats ./lib/line/bot/v2 --fail-on-warning ``` -------------------------------- ### Convert Hash/JSON to SDK Classes in Ruby Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md Convert Hash or JSON data into SDK classes using the `#create` method. This allows for type checking and better integration with the SDK's features. ```ruby json = <<~JSON { "to": "U4af4980629...", "messages": [ { "type": "flex", "alt_text": "This is a Flex Message", "contents": { "type": "bubble", "body": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "Hello" } ] } } } ] } JSON request = Line::Bot::V2::MessagingApi::PushMessageRequest.create( JSON.parse(json) ) ``` -------------------------------- ### Create and push v2 TextMessage Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Creates a v2 TextMessage object and a PushMessageRequest, then sends the message using the v1 push_message_with_http_info method. The response object's class is Line::Bot::V2::MessagingApi::PushMessageResponse. ```ruby message = Line::Bot::V2::MessagingApi::TextMessage.new( # No need to pass `type: "text"` text: 'Hello, this is a test message!' ) request = Line::Bot::V2::MessagingApi::PushMessageRequest.new( to: 'U1234567890abcdef1234567890abcdef', messages: [ message ] ) response, status_code, response_headers = client.push_message_with_http_info( push_message_request: request ) puts response.class # => Line::Bot::V2::MessagingApi::PushMessageResponse ``` -------------------------------- ### Run All CI Tasks Locally Source: https://github.com/line/line-bot-sdk-ruby/blob/master/CONTRIBUTING.md Execute all defined CI tasks locally using this command. This is defined in the Rakefile. ```bash bundle exec rake ci ``` -------------------------------- ### Add Quick Reply Buttons with Ruby Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Enhance user interaction by adding quick reply buttons to text messages. Supports various actions like messages, location, camera, and date/time picking. ```ruby request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::TextMessage.new( text: 'What would you like to do?', quick_reply: Line::Bot::V2::MessagingApi::QuickReply.new( items: [ Line::Bot::V2::MessagingApi::QuickReplyItem.new( action: Line::Bot::V2::MessagingApi::MessageAction.new( label: 'Order food', text: 'I want to order food' ) ), Line::Bot::V2::MessagingApi::QuickReplyItem.new( action: Line::Bot::V2::MessagingApi::LocationAction.new( label: 'Share location' ) ), Line::Bot::V2::MessagingApi::QuickReplyItem.new( action: Line::Bot::V2::MessagingApi::CameraAction.new( label: 'Take photo' ) ), Line::Bot::V2::MessagingApi::QuickReplyItem.new( action: Line::Bot::V2::MessagingApi::DatetimePickerAction.new( label: 'Pick date', data: 'action=date', mode: 'date' ) ) ] ) ) ] ) client.reply_message(reply_message_request: request) ``` -------------------------------- ### Using Hash/JSON for Messages Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Allows sending messages using Hash or JSON objects directly, which is beneficial for migrating to the SDK or constructing complex Flex Messages. The SDK can also convert parsed JSON back into SDK classes for type checking. ```ruby # Using Hash directly request = { to: "U4af4980629...", messages: [ { type: "flex", alt_text: "Flex Message", contents: { type: "bubble", body: { type: "box", layout: "horizontal", contents: [{ type: "text", text: "Hello from Hash!" }] } } } ] } client.push_message(push_message_request: request) # Or parse from JSON json_string = '{"to":"U4af4980629...","messages":[{"type":"text","text":"Hello from JSON!"}]}' request = JSON.parse(json_string) client.push_message(push_message_request: request) # Convert JSON to SDK classes for type checking request = Line::Bot::V2::MessagingApi::PushMessageRequest.create(JSON.parse(json_string)) ``` -------------------------------- ### Retrieve HTTP Headers with LINE SDK Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md Use `*_with_http_info` methods to retrieve HTTP headers such as 'x-line-request-id', 'x-line-accepted-request-id', and 'content-type' from API responses. Ensure header names are in lowercase when accessing them. ```ruby push_request = Line::Bot::V2::MessagingApi::PushMessageRequest.new( to: event.source.user_id, messages: [ Line::Bot::V2::MessagingApi::TextMessage.new(text: "[^Request ID] #{headers['x-line-request-id']}") ] ) _body, _status_code, headers = client.push_message_with_http_info(push_message_request: push_request) puts headers['x-line-request-id'] puts headers['x-line-accepted-request-id'] puts headers['content-type'] ``` -------------------------------- ### Send Flex Messages with Ruby Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Construct and send highly customizable Flex Messages using nested boxes, text, and buttons. Ensure the `alt_text` is set for compatibility. ```ruby request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::FlexMessage.new( alt_text: 'Receipt', contents: Line::Bot::V2::MessagingApi::FlexBubble.new( header: Line::Bot::V2::MessagingApi::FlexBox.new( layout: 'vertical', contents: [ Line::Bot::V2::MessagingApi::FlexText.new( text: 'ORDER RECEIPT', weight: 'bold', size: 'xl' ) ] ), body: Line::Bot::V2::MessagingApi::FlexBox.new( layout: 'vertical', contents: [ Line::Bot::V2::MessagingApi::FlexText.new(text: 'Item: Coffee'), Line::Bot::V2::MessagingApi::FlexText.new(text: 'Price: $5.00') ] ), footer: Line::Bot::V2::MessagingApi::FlexBox.new( layout: 'vertical', contents: [ Line::Bot::V2::MessagingApi::FlexButton.new( style: 'primary', action: Line::Bot::V2::MessagingApi::URIAction.new( label: 'View Details', uri: 'https://example.com/order/123' ) ) ] ) ) ) ] ) client.reply_message(reply_message_request: request) ``` -------------------------------- ### Display Loading Indicator Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Shows a loading animation in the chat for up to 60 seconds while a long-running operation is processed. Remember to send a response after the operation completes. ```ruby # Show loading animation for up to 60 seconds client.show_loading_animation( show_loading_animation_request: Line::Bot::V2::MessagingApi::ShowLoadingAnimationRequest.new( chat_id: event.source.user_id ) ) # Perform long-running operation sleep 3 # Send response request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::TextMessage.new(text: "Processing complete!") ] ) client.reply_message(reply_message_request: request) ``` -------------------------------- ### Send Messages to Multiple Users with multicast Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Efficiently send the same message to multiple users (up to 500) simultaneously. Requires a list of user IDs. ```ruby request = Line::Bot::V2::MessagingApi::MulticastRequest.new( to: ["U4af4980629...", "U4af4980630...", "U4af4980631..."], messages: [ Line::Bot::V2::MessagingApi::TextMessage.new(text: "Announcement to all users!") ] ) client.multicast(multicast_request: request) ``` -------------------------------- ### Configure Webhook Endpoint with Ruby SDK Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Set, retrieve, and test webhook endpoint URLs for your LINE bot application. Requires specifying the endpoint URL in the request. ```ruby # Set webhook endpoint URL client.set_webhook_endpoint( set_webhook_endpoint_request: Line::Bot::V2::MessagingApi::SetWebhookEndpointRequest.new( endpoint: 'https://your-server.com/callback' ) ) ``` ```ruby # Get current webhook endpoint info endpoint_info = client.get_webhook_endpoint puts "Endpoint: #{endpoint_info.endpoint}" puts "Active: #{endpoint_info.active}" ``` ```ruby # Test webhook endpoint test_response = client.test_webhook_endpoint( test_webhook_endpoint_request: Line::Bot::V2::MessagingApi::TestWebhookEndpointRequest.new( endpoint: 'https://your-server.com/callback' ) ) puts "Success: #{test_response.success}" puts "Timestamp: #{test_response.timestamp}" puts "Status code: #{test_response.status_code}" ``` -------------------------------- ### Generate Code with Python Script Source: https://github.com/line/line-bot-sdk-ruby/blob/master/CONTRIBUTING.md After editing pebble templates, execute this script to generate the library code. Commit all affected files to ensure CI passes. ```bash generate-code.py ``` -------------------------------- ### Leave Group and Room with Ruby SDK Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Programmatically leave a LINE group or room using the provided group or room ID. ```ruby # Leave group client.leave_group(group_id: "C4af4980629...") ``` ```ruby # Room operations (similar) client.get_room_member_count(room_id: "R4af4980629...") client.leave_room(room_id: "R4af4980629...") ``` -------------------------------- ### MessagingApi::ApiClient - Initialize API Client Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Initializes the main API client for LINE Messaging API operations. It requires a channel access token and allows for customizable HTTP options. ```APIDOC ## MessagingApi::ApiClient - Initialize API Client ### Description The main API client for LINE Messaging API operations. Requires a channel access token and supports customizable HTTP options for timeout configuration. ### Method N/A (Initialization) ### Endpoint N/A ### Parameters #### Request Body - **channel_access_token** (string) - Required - The channel access token for authentication. - **http_options** (object) - Optional - Hash for configuring HTTP client options. - **open_timeout** (integer) - Optional - Timeout in seconds for opening the connection. - **read_timeout** (integer) - Optional - Timeout in seconds for reading the response. ``` -------------------------------- ### LINE Bot v2 Webhook Handler in Ruby Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Handles incoming LINE bot messages using v2 of the SDK. Requires LINE_CHANNEL_ACCESS_TOKEN and LINE_CHANNEL_SECRET environment variables. Includes error handling for invalid signatures. ```ruby require 'sinatra' require 'line-bot-api' set :environment, :production def client @client ||= Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN") ) end def parser @parser ||= Line::Bot::V2::WebhookParser.new(channel_secret: ENV.fetch("LINE_CHANNEL_SECRET")) end post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] begin events = parser.parse(body: body, signature: signature) rescue Line::Bot::V2::WebhookParser::InvalidSignatureError halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request' end events.each do |event| case event when Line::Bot::V2::Webhook::MessageEvent case event.message when Line::Bot::V2::Webhook::TextMessageContent message = event.message.text request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::TextMessage.new(text: message) ] ) client.reply_message(reply_message_request: request) end end end "OK" end ``` -------------------------------- ### multicast - Send Messages to Multiple Users Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Efficiently sends the same message to multiple users (up to 500) at once. ```APIDOC ## multicast - Send Messages to Multiple Users ### Description Efficiently sends the same message to multiple users (up to 500) at once. ### Method POST ### Endpoint /v2/bot/message/multicast ### Parameters #### Request Body - **multicast_request** (object) - Required - The request object for sending a multicast message. - **to** (array) - Required - An array of user IDs to send the message to (max 500). - **messages** (array) - Required - An array of message objects to send. - **type** (string) - Required - The type of message (e.g., 'text', 'sticker'). - **text** (string) - Required for TextMessage - The message text. - **package_id** (string) - Required for StickerMessage - The sticker package ID. - **sticker_id** (string) - Required for StickerMessage - The sticker ID. ``` -------------------------------- ### LINE Bot v1 Webhook Handler in Ruby Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Handles incoming LINE bot messages using v1 of the SDK. Requires LINE_CHANNEL_SECRET and LINE_CHANNEL_TOKEN environment variables. ```ruby require 'sinatra' require 'line/bot' def client @client ||= Line::Bot::Client.new { config.channel_secret = ENV["LINE_CHANNEL_SECRET"] config.channel_token = ENV["LINE_CHANNEL_TOKEN"] } end post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] unless client.validate_signature(body, signature) halt 400, {'Content-Type' => 'text/plain'}, 'Bad Request' end events = client.parse_events_from(body) events.each do |event| case event when Line::Bot::Event::Message case event.type when Line::Bot::Event::MessageType::Text message = { type: 'text', text: event.message['text'] } client.reply_message(event['replyToken'], message) end end end "OK" end ``` -------------------------------- ### Push message using v1 Client Source: https://github.com/line/line-bot-sdk-ruby/blob/master/migration_from_v1_to_v2_guide.md Sends a text message to a specified user ID using the v1 LINE Bot client. The response object's class is Net::HTTPResponse. ```ruby response = client.push_message( 'U1234567890abcdef1234567890abcdef', [ { type: 'text', text: 'Hello, this is a test message!' } ] ) puts response.class # => Net::HTTPResponse ``` -------------------------------- ### Template Messages - Buttons, Carousel, Confirm Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt This section demonstrates how to send various interactive template messages, including buttons, carousels, and confirmation dialogs, using the LINE Messaging API. ```APIDOC ## Template Messages - Buttons, Carousel, Confirm ### Description Sends interactive template messages with buttons, carousels, or confirmation dialogs. ### Method POST ### Endpoint `/v2/bot/message/reply` ### Parameters #### Request Body - **replyToken** (string) - Required - The reply token obtained from an incoming message event. - **messages** (Array[Message]) - Required - An array of messages to send. For templates, use `TemplateMessage`. ### Request Example - Buttons Template ```ruby buttons_request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::TemplateMessage.new( alt_text: 'Button menu', template: Line::Bot::V2::MessagingApi::ButtonsTemplate.new( thumbnail_image_url: 'https://example.com/image.jpg', title: 'Menu', text: 'Please select', actions: [ Line::Bot::V2::MessagingApi::URIAction.new( label: 'Visit website', uri: 'https://example.com' ), Line::Bot::V2::MessagingApi::PostbackAction.new( label: 'Buy', data: 'action=buy&itemid=123' ), Line::Bot::V2::MessagingApi::MessageAction.new( label: 'Say hello', text: 'Hello!' ), Line::Bot::V2::MessagingApi::DatetimePickerAction.new( label: 'Select date', data: 'action=setdate', mode: 'date' ) ] ) ) ] ) client.reply_message(reply_message_request: buttons_request) ``` ### Request Example - Carousel Template ```ruby carousel_request = Line::Bot::V2::MessagingApi::ReplyMessageRequest.new( reply_token: event.reply_token, messages: [ Line::Bot::V2::MessagingApi::TemplateMessage.new( alt_text: 'Product carousel', template: Line::Bot::V2::MessagingApi::CarouselTemplate.new( columns: [ Line::Bot::V2::MessagingApi::CarouselColumn.new( title: 'Product A', text: '$100', actions: [ Line::Bot::V2::MessagingApi::PostbackAction.new(label: 'Buy', data: 'buy_a') ] ), Line::Bot::V2::MessagingApi::CarouselColumn.new( title: 'Product B', text: '$200', actions: [ Line::Bot::V2::MessagingApi::PostbackAction.new(label: 'Buy', data: 'buy_b') ] ) ] ) ) ] ) client.reply_message(reply_message_request: carousel_request) ``` ### Response #### Success Response (200) - **message** (string) - "OK" - **webhook_key** (string) - A unique key for the webhook event. #### Response Example ```json { "message": "OK", "webhook_key": "some_unique_key" } ``` ``` -------------------------------- ### Update RBS Collections Source: https://github.com/line/line-bot-sdk-ruby/blob/master/CONTRIBUTING.md Use this command to update RBS collections for the project. Refer to rbs_collections.yaml and Steepfile for details. ```bash rbs collection update ``` -------------------------------- ### WebhookParser - Parse Incoming Webhook Events Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt The WebhookParser class is used to validate webhook signatures and parse incoming LINE events. It supports signature verification and can optionally skip verification. ```APIDOC ## WebhookParser - Parse Incoming Webhook Events ### Description The WebhookParser class validates webhook signatures and parses incoming LINE events. It supports signature verification with HMAC-SHA256 and can optionally skip verification during development or channel secret rotation. ### Method POST ### Endpoint /callback ### Parameters #### Query Parameters - **skip_signature_verification** (boolean) - Optional - If true, skips signature verification. ### Request Body - **body** (string) - Required - The raw request body from the webhook. - **signature** (string) - Required - The `X-Line-Signature` header value. ### Response #### Success Response (200) - **events** (array) - An array of parsed LINE event objects. #### Error Response (400) - **message** (string) - "Bad Request" if the signature is invalid. ``` -------------------------------- ### Parse Incoming Webhook Events with WebhookParser Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Use WebhookParser to validate webhook signatures and parse incoming LINE events. It supports HMAC-SHA256 verification and can optionally skip verification. ```ruby require 'sinatra' require 'line-bot-api' def parser @parser ||= Line::Bot::V2::WebhookParser.new( channel_secret: ENV.fetch("LINE_CHANNEL_SECRET"), skip_signature_verification: -> { ENV['SKIP_VERIFICATION'] == 'true' } ) end post '/callback' do body = request.body.read signature = request.env['HTTP_X_LINE_SIGNATURE'] begin events = parser.parse(body: body, signature: signature) rescue Line::Bot::V2::WebhookParser::InvalidSignatureError halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request' end events.each do |event| case event when Line::Bot::V2::Webhook::MessageEvent handle_message(event) when Line::Bot::V2::Webhook::FollowEvent handle_follow(event) when Line::Bot::V2::Webhook::UnfollowEvent handle_unfollow(event) when Line::Bot::V2::Webhook::PostbackEvent handle_postback(event) end end "OK" end ``` -------------------------------- ### Download Message Content Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Downloads message content like images, videos, or audio. For video and audio, it checks the transcoding status first. Ensure the 'downloads' directory exists. ```ruby content, status_code, headers = blob_client.get_message_content_with_http_info( message_id: event.message.id ) content_type = headers['content-type'] extension = case content_type when 'image/jpeg' then 'jpg' when 'image/png' then 'png' when 'video/mp4' then 'mp4' else 'bin' end File.open("downloads/#{event.message.id}.#{extension}", 'wb') do |f| f.write(content) end # For video/audio, check transcoding status first transcoding = blob_client.get_message_content_transcoding_by_message_id(message_id: event.message.id) if transcoding.status == 'succeeded' content = blob_client.get_message_content(message_id: event.message.id) end ``` -------------------------------- ### Use Hash/JSON for Push Messages in Ruby Source: https://github.com/line/line-bot-sdk-ruby/blob/master/README.md You can use Hash objects or JSON parsed data directly as parameters for API calls, which is useful for migrating from v1 or building Flex Messages. However, this approach bypasses type checking provided by RBS. ```ruby client = Line::Bot::V2::MessagingApi::ApiClient.new( channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN"), ) request = { to: "U4af4980629...", messages: [ { type: "flex", alt_text: "This is a Flex Message", contents: { type: "bubble", body: { type: "box", layout: "horizontal", contents: [ { type: "text", text: "Hello" } ] } } } ] } client.push_message(push_message_request: request) # or request = JSON.parse( <<~JSON { "to": "U4af4980629...", "messages": [ { "type": "flex", "alt_text": "This is a Flex Message", "contents": { "type": "bubble", "body": { "type": "box", "layout": "horizontal", "contents": [ { "type": "text", "text": "Hello" } ] } } } ] } JSON ) client.push_message(push_message_request: request) ``` -------------------------------- ### push_message - Send Push Messages Source: https://context7.com/line/line-bot-sdk-ruby/llms.txt Sends a message to a specific user, group, or room at any time. Requires the recipient's user ID. ```APIDOC ## push_message - Send Push Messages ### Description Sends a message to a specific user, group, or room at any time. Requires the recipient's user ID. ### Method POST ### Endpoint /v2/bot/message/push ### Parameters #### Request Body - **push_message_request** (object) - Required - The request object for sending a push message. - **to** (string) - Required - The user ID, group ID, or room ID to send the message to. - **messages** (array) - Required - An array of message objects to send. - **type** (string) - Required - The type of message (e.g., 'text', 'sticker'). - **text** (string) - Required for TextMessage - The message text. - **package_id** (string) - Required for StickerMessage - The sticker package ID. - **sticker_id** (string) - Required for StickerMessage - The sticker ID. - **x_line_retry_key** (string) - Optional - A unique key for retrying the request idempotently. ```