LINE Messaging API SDK for Ruby

repository·master·Indexed 19 days ago

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

A structured SDK for Ruby developers to build bots for the LINE platform. It provides tools for webhook parsing, message sending, profile management, and interaction with the Messaging API (Insight) and Manage Audience API. The SDK supports Ruby 3.3 or later and is distributed as the line-bot-api gem.

Tokens
10.9K
Snippets
49
Records
52
Agent score
67%

What's inside line-bot-sdk-ruby

  1. Compare v1 and v2 Webhook handling

    master

    Webhook handling has changed significantly between versions:

    • v1: Used Line::Bot::Client#validate_signature and Line::Bot::Client#parse_events_from to handle incoming requests.
    • v2: Uses a dedicated Line::Bot::V2::WebhookParser. The parser handles signature validation and returns structured event objects. You should rescue Line::Bot::V2::WebhookParser::InvalidSignatureError to handle invalid requests.
    # v2 Webhook Implementation Example
    require 'line-bot-api'
    
    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| 
        # Handle events (e.g., Line::Bot::V2::Webhook::MessageEvent)
      end
      "OK"
    end
  2. Use Hashes or JSON instead of SDK classes

    master

    You can pass a plain Ruby Hash or a JSON parsed object as a parameter to API methods instead of using formal SDK classes (like TextMessage). This is useful for complex structures like Flex Messages or when migrating from older versions.

    Warning: Using Hashes bypasses RBS type checking.

    # Using a Hash
    request = {
      to: "USER_ID",
      messages: [
        {
          type: "flex",
          alt_text: "Flex Message",
          contents: { type: "bubble", body: { type: "box", layout: "horizontal", contents: [] } }
        }
      ]
    }
    client.push_message(push_message_request: request)
  3. Compare v1 and v2 API calling patterns

    master

    In v1, you used Line::Bot::Client and passed raw Hashes for messages. In v2, you use specialized API clients and request/message objects.

    v2 Recommended Pattern: Use Line::Bot::V2::MessagingApi::ApiClient combined with specific Request and Message classes (e.g., PushMessageRequest, TextMessage). This provides better type safety and structure.

    v2 Hash Pattern: While you can pass Hashes to request objects in v2 to make migration easier, it is not the recommended way for long-term usage.

    # v2 Recommended Pattern
    client = Line::Bot::V2::MessagingApi::ApiClient.new(
      channel_access_token: ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN")
    )
    
    message = Line::Bot::V2::MessagingApi::TextMessage.new(
      text: 'Hello, this is a test message!'
    )
    
    request = Line::Bot::V2::MessagingApi::PushMessageRequest.new(
      to: 'USER_ID',
      messages: [message]
    )
    
    response, status_code, response_headers = client.push_message_with_http_info(
      push_message_request: request
    )
  4. Migrate from v1 to v2

    master
    The line-bot-sdk-ruby project has two distinct implementations: v1 and v2. They are not compatible. Migration to v2 is strongly recommended. For the specific migration procedure, refer to the migration_from_v1_to_v2_guide.md file in the repository.
  5. Get started with the Rich Menu example

    master

    To run the Rich Menu example project, you must first set your LINE Messaging API credentials as environment variables. Then, install the required gems and execute the application.

    Prerequisites:

    • A LINE Channel Secret
    • A LINE Channel Access Token

    Steps:

    1. Export LINE_CHANNEL_SECRET and LINE_CHANNEL_ACCESS_TOKEN.
    2. Run bundle install to install dependencies.
    3. Run bundle exec ruby app.rb to start the example.
    $ export LINE_CHANNEL_SECRET=YOUR_CHANNEL_SECRET
    $ export LINE_CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN
    $ bundle install
    $ bundle exec ruby app.rb
  6. Install the LINE Messaging API SDK for Ruby

    master

    The SDK requires Ruby 3.3 or later. You can install it using Bundler by adding it to your Gemfile, or by installing the gem directly via the command line.

    # Add to Gemfile
    gem 'line-bot-api'

    Then run

    bundle

    Or install directly

    gem install line-bot-api
  7. Run the Echo Bot example

    master

    The Echo Bot is a simple example project that echoes received messages back to the user. To run it, you must provide your LINE Messaging API credentials via environment variables and set your base URL for the webhook callback. The application automatically attempts to set ${APP_BASE_URL}/callback as the webhook URL upon startup.

    $ 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
  8. Run the Audience example project

    master

    To run the Audience example, you must first set your LINE Messaging API credentials as environment variables. Then, install the dependencies and execute the application script.

    Prerequisites:

    • A LINE_CHANNEL_SECRET from your LINE Developers Console.
    • A LINE_CHANNEL_ACCESS_TOKEN from your LINE Developers Console.
    • Update the User ID in both app.rb and audience.txt with your own LINE User ID to test the functionality.
    $ export LINE_CHANNEL_SECRET=YOUR_CHANNEL_SECRET
    $ export LINE_CHANNEL_ACCESS_TOKEN=YOUR_CHANNEL_ACCESS_TOKEN
    $ bundle install
    $ bundle exec ruby app.rb
  9. Run the Channel Access Token example

    master

    To run the Channel Access Token example, you must first set your LINE credentials as environment variables. Then, install the dependencies and execute the application script.

    Prerequisites:

    • A LINE_CHANNEL_ID
    • A LINE_CHANNEL_SECRET

    Steps:

    1. Export your credentials.
    2. Install the required gems using Bundler.
    3. Run the app.rb script.
    $ export LINE_CHANNEL_ID=YOUR_CHANNEL_ID
    $ export LINE_CHANNEL_SECRET=YOUR_CHANNEL_SECRET
    $ bundle install
    $ bundle exec ruby app.rb
  10. Migrate from v1 to v2 of line-bot-api

    master

    The migration from v1 to v2 can be performed gradually. Follow these steps:

    1. Upgrade to v1.30.0: Upgrade the line-bot-api gem to version 1.30.0. This version is unique because it includes both the v1 and v2 codebases, allowing for a phased transition.
    2. Replace Deprecated Code: Run your application and look for deprecation warnings in your logs. These warnings (e.g., [DEPRECATION] Line::Bot::Client#push_message is deprecated...) will tell you exactly which v2 method to use instead. Migrate your code until all deprecation warnings are resolved.
    3. Upgrade to v2.0.0+: Once all v1 code has been replaced, upgrade the line-bot-api gem to 2.0.0 or higher. Note that starting from 2.0.0, the v1 codebase is no longer included.
    # Step 1: Upgrade to the bridge version
    gem install line-bot-api -v 1.30.0
    
    # Step 2: Migrate code (check logs for deprecation warnings)
    
    # Step 3: Final upgrade
    gem install line-bot-api -v 2.0.0
  11. Run the Kitchen Sink Bot example

    master

    The Kitchen Sink Bot is a comprehensive example demonstrating various features of the line-bot-api gem. To run it, you must provide your LINE Messaging API credentials via environment variables and set your base URL. The application automatically attempts to set ${APP_BASE_URL}/callback as the webhook URL upon startup.

    $ 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
  12. Use the local SDK for development

    master

    If you are contributing to the line-bot-sdk-ruby repository and want to test changes locally instead of using the published gem from RubyGems, set the USE_LOCAL_LINE_BOT_SDK_RUBY environment variable to 1 before running bundle install. This forces Bundler to resolve the line-bot-api dependency from the local checkout in the parent directory.

    $ USE_LOCAL_LINE_BOT_SDK_RUBY=1 bundle install