slack-ruby-client

repository·master·Indexed 22 days ago

https://github.com/slack-ruby/slack-ruby-client

A Ruby client for interacting with Slack's Web and Events APIs. It provides tools for sending messages, verifying request signatures for events, handling cursor pagination and rate limiting, and formatting/parsing Slack messages. The library includes the Slack::Web::Client for Web API interaction and supports the files_upload_v2 functionality for file uploads.

Tokens
37.2K
Snippets
25
Records
437
Agent score
76%

What's inside slack-ruby-client

  1. Overview of Slack Ruby Client capabilities

    master

    The Slack Ruby Client is a Ruby library designed to interact with the Slack Web API and Events API.

    Key use cases include:

    • Sending messages to Slack via the Web API.
    • Facilitating integration with the Events API.
    • Verifying request signatures for events coming from Slack.
    • Calling Slack Web API methods from within a custom web application (e.g., to respond to slash commands or interactive components).

    Note: If you are building a complete bot, it is recommended to start with slack-ruby-bot-server-events.

  2. Handle pagination and rate limiting in the Web Client

    master

    The Web client supports automatic cursor pagination for methods like users_list. By providing a block, the client will automatically make subsequent requests using the cursor from the response until all items are retrieved.

    Pagination Example

    all_members = []
    client.users_list(presence: true, limit: 10) do |response|
      all_members.concat(response.members)
    end

    Rate Limiting

    When using pagination, the client automatically handles Slack rate limits by pausing and retrying based on the Retry-After header.

    You can tune this behavior using:

    • max_retries: The number of consecutive rate-limited responses to allow before giving up (default: 100).
    • sleep_interval: A proactive pause (in seconds) between each paginated request to avoid hitting limits.

    Configuring pagination parameters:

    client.users_list(presence: true, limit: 10, sleep_interval: 5, max_retries: 20) do |response|
      all_members.concat(response.members)
    end
  3. Verify Slack Events request signatures

    master

    To secure your application, you should verify that incoming HTTP requests actually come from Slack using your signing_secret.

    1. Configure the signing secret globally:
    Slack::Events.configure do |config|
      config.signing_secret = 'your_slack_signing_secret'
    end
    1. Verify the request in your controller/handler:
    # http_request is the object representing the incoming request
    slack_request = Slack::Events::Request.new(http_request)
    slack_request.verify!

    verify! may raise:

    • Slack::Events::Request::MissingSigningSecret
    • Slack::Events::Request::InvalidSignature
    • Slack::Events::Request::TimestampExpired

    You can also provide the secret per-request:

    Slack::Events::Request.new(http_request, signing_secret: 'secret', signature_expires_in: 300)
  4. Obtain a User OAuth Token via OAuth v2 flow

    master

    To obtain a token for a specific user (rather than using a pre-configured Bot token), you must implement the OAuth v2 flow. This involves creating a Slack app, configuring redirect URLs, and handling the authorization request via a browser.

    Prerequisites

    1. Create a Slack app at api.slack.com.
    2. For local development, use ngrok to expose your local server to the internet so Slack can send redirect requests to your machine.

    Setup Steps

    1. Expose local server: Run ngrok http 4242 (or your specific port).
    2. Configure Slack App: Add your ngrok URL to the "Redirect URLs" section under "OAuth & Permissions" in your Slack app settings.
    3. Environment Configuration: Create a .env file with the following keys:
      • SLACK_CLIENT_ID: Your App Client ID.
      • SLACK_CLIENT_SECRET: Your App Client Secret.
      • REDIRECT_URI: Your ngrok URL (e.g., https://...ngrok-free.app).
      • SCOPE: The Bot User OAuth Scopes you are requesting.
      • USER_SCOPE: The User OAuth Token Scopes you are requesting.

    Running the Example

    Install dependencies and run the OAuth script using dotenv to load your environment variables:

    bundle install
    bundle exec dotenv ruby oauth_v2.rb

    After running, a browser window will open to complete the Slack authorization flow.

    ngrok http 4242
  5. Migrate from RTM to Granular Permissions (>= 3.0.0)

    master

    Support for the RTM API has been removed in version 3.0.0. If your application uses RTM, you should migrate to granular permissions.

    For bots still using legacy/classic permissions, you should lock your slack-ruby-client version to 2.x. For new development, it is recommended to write a new bot using the Web API rather than attempting a complex RTM migration.

  6. Configure SSL settings for Faraday (>= 2.0.0)

    master

    Starting with version 2.0.0, default values for Faraday's SSL settings ca_file and ca_path have been removed. If your environment relies on default OpenSSL certificate files or directories, you must now set them explicitly in the configuration or during client initialization.

    # Via global configuration
    Slack::Web::Client.configure do |config|
      config.ca_file = OpenSSL::X509::DEFAULT_CERT_FILE
      config.ca_path = OpenSSL::X509::DEFAULT_CERT_DIR
    end
    
    # Or via client initialization
    client = Slack::Web::Client.new(ca_file: OpenSSL::X509::DEFAULT_CERT_FILE, ca_path: OpenSSL::X509::DEFAULT_CERT_DIR)
  7. Update error handling for ServerErrors (>= 1.0.0)

    master

    As of version 1.0.0, Slack::Web::Api::Errors::ServerError and its subclasses no longer inherit from Slack::Web::Api::Errors::InternalError or Slack::Web::Api::Errors::SlackError.

    If you want to catch both standard Slack errors and server-side errors, you must explicitly rescue both classes.

  8. Use the Slack Web Client

    master

    The Slack::Web::Client allows you to interact with the Slack Web API. You can initialize it with a specific token to override the global configuration, or use the global configuration if no token is provided.

    Common Tasks

    Test Authentication

    Verify your token is working:

    client = Slack::Web::Client.new
    client.auth_test

    Send Messages

    Use chat_postMessage to send text to a channel:

    client.chat_postMessage(channel: '#general', text: 'Hello World', as_user: true)

    List Channels

    Retrieve a list of channels using conversations_list:

    channels = client.conversations_list.channels
    general_channel = channels.detect { |c| c.name == 'general' }

    Upload Files

    Use the files_upload_v2 helper to handle the multi-step upload process required by the Slack API. This method supports uploading a single file or an array of files.

    Single file upload:

    client.files_upload_v2(
      filename: 'results.pdf',
      content: File.read('/users/me/results.pdf'),
      channels: ['C000000001'],
      initial_comment: 'Sharing results'
    )

    Multiple files upload:

    client.files_upload_v2(
      files: [
        { filename: 'report.pdf', content: File.read('/users/me/report.pdf'), title: 'Monthly Report' },
        { filename: 'data.csv', content: File.read('/users/me/data.csv'), title: 'Raw Data' }
      ],
      channels: ['#general'],
      initial_comment: 'Here are the monthly results!'
    )

    Note: Avoid using the files_upload method as it uses a deprecated endpoint that will be unsupported after 2025-03-11.

  9. Handle specific lookup errors in >= 3.2.0

    master

    In version 3.2.0 and later, looking up a nonexistent channel name or user handle raises specific error classes instead of a generic SlackError.

    • Nonexistent channel name: raises ChannelNotFound
    • Nonexistent user handle: raises UserNotFound

    Both classes inherit from SlackError, so rescue SlackError will continue to work. However, if your code relies on specific error types, you must update your rescue blocks to account for these new classes.