### Install and Run Files Upload Example Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/examples/files_upload_v2/README.md Instructions for installing dependencies and running the files_upload_v2 example script. ```bash bundle install bundle exec dotenv ruby files_upload_v2.rb ``` -------------------------------- ### Install Dependencies and Run OAuth Example Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/examples/oauth_v2/README.md Install project dependencies using Bundler and then run the OAuth v2 example script. This will initiate the OAuth flow in your browser. ```sh bundle install bundle exec dotenv ruby oauth_v2.rb ``` -------------------------------- ### Run Example Application Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/CONTRIBUTING.md Install dependencies and run a sample application from the examples directory using a Slack API token. ```bash cd examples/hi_web bundle install SLACK_API_TOKEN=... bundle exec ruby hi.rb ``` -------------------------------- ### Complete Slack Message Example Setup Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-messages-formatting.md Sets up the Slack client with a token for sending messages. Ensure your SLACK_API_TOKEN environment variable is set. ```ruby require 'slack-ruby-client' Slack.configure { |c| c.token = ENV['SLACK_API_TOKEN'] } client = Slack::Web::Client.new ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/RELEASING.md Install project dependencies and run all tests locally before proceeding with a release. ```bash bundle install rake ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/CONTRIBUTING.md Install project dependencies using Bundler and run the test suite. ```bash bundle install bundle exec rake ``` -------------------------------- ### Channel Info Response Example Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/types.md This snippet demonstrates a successful response when retrieving information about a specific channel. ```ruby response = client.conversations_info(channel: 'C123456') response.ok # true response.channel # channel object response.channel.id # "C123456" response.channel.name # "general" ``` -------------------------------- ### User List Response Example Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/types.md This snippet illustrates a successful response when fetching a list of users, including pagination details. ```ruby response = client.users_list(limit: 100) response.ok # true response.members # array of user objects response.members.first.name # first user's name response.response_metadata.next_cursor # for pagination ``` -------------------------------- ### Configure RTM client start method Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/UPGRADING.md To restore the previous behavior of always using rtm.start, configure the start_method in Slack::RealTime::Client. ```ruby Slack::RealTime::Client.config do |config| config.start_method = :rtm_start end ``` -------------------------------- ### Summarize Channel Activity Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md This example demonstrates how to configure the client, fetch channel information, and retrieve and display recent messages from a specified channel. Ensure you have your SLACK_API_TOKEN set as an environment variable. ```ruby require 'slack-ruby-client' require 'time' Slack.configure { |c| c.token = ENV['SLACK_API_TOKEN'] } client = Slack::Web::Client.new channel_name = ARGV[0] || 'general' # Get channel info channel = client.conversations_info(channel: "##{channel_name}").channel puts "Channel: #{channel.name}" puts "Created: #{Time.at(channel.created)}" puts "Members: #{channel.num_members}" puts "Topic: #{channel.topic&.value}" puts # Get recent messages puts "Last 50 messages:" puts "-" * 60 client.conversations_history( channel: channel.id, limit: 50 ) do |response| response.messages.reverse.each do |msg| user = client.users_info(user: msg.user).user time = Time.at(msg.ts.to_i) text = Slack::Messages::Formatting.unescape(msg.text || '[no text]') puts "#{time.strftime('%H:%M')} #{user.name}: #{text}" end end ``` -------------------------------- ### Add Gem to Gemfile Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Add the slack-ruby-client gem to your project's Gemfile for installation. ```ruby gem 'slack-ruby-client' ``` -------------------------------- ### Post Message in a Thread Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/chat-endpoints.md This example demonstrates how to post a parent message and then reply to it within a thread using the `thread_ts` parameter. ```ruby response = client.chat_postMessage( channel: '#general', text: 'Parent message' ) client.chat_postMessage( channel: '#general', text: 'Reply in thread', thread_ts: response.ts ) ``` -------------------------------- ### Accessing API response properties before 0.6.0 Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/UPGRADING.md Example showing how API response properties were accessed using hash-like syntax before version 0.6.0. ```ruby puts "Welcome '#{client.self['name']}' to the '#{client.team['name']}' team." ``` -------------------------------- ### Upload Multiple Files using files_upload_v2 Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md This example demonstrates uploading multiple files simultaneously. Each file in the `files` array can have its own filename, content, and title. Specify channels and an initial comment for the share. ```ruby response = client.files_upload_v2( files: [ { filename: 'data.csv', content: csv_data, title: 'Data Export' }, { filename: 'chart.png', content: image_data, title: 'Chart' } ], channels: ['#general', '#reports'], initial_comment: 'Monthly results attached' ) ``` -------------------------------- ### Troubleshooting Rate Limits with Increased Sleep Interval and Retries Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/pagination.md Provides an example of how to increase the `sleep_interval` and `max_retries` parameters to further mitigate rate limiting issues. ```ruby client.users_list( limit: 50, sleep_interval: 2, # Increased delay max_retries: 200 # More retries ) { |response| ... } ``` -------------------------------- ### Accessing API response properties after 0.6.0 Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/UPGRADING.md Example showing the new method access for API response properties in versions 0.6.0 and later. ```ruby puts "Welcome #{client.self.name} to the #{client.team.name} team." ``` -------------------------------- ### Get Channel Info with Slack CLI Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Retrieve information about a specific Slack channel using the command-line client. Specify the channel name or ID. ```bash $ slack conversations info --channel=#general {"ok":true,"channel":{"id":"C04KB5X4D","name":"general", ...}} ``` -------------------------------- ### Send a message using Attachments (Legacy) Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/chat-endpoints.md This example shows how to send a message using legacy attachments. It includes fields like fallback text, color, title, text, image URL, and footer. ```ruby client.chat_postMessage( channel: '#general', attachments: [ { fallback: 'Required plain-text summary', color: '#36a64f', title: 'Attachment Title', text: 'Optional text that appears within the attachment', image_url: 'http://example.com/image.png', thumb_url: 'http://example.com/image_thumb.png', footer: 'footer text', footer_icon: 'http://example.com/icon.png', ts: Time.now.to_i } ] ) ``` -------------------------------- ### Search Users by Name Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Searches for users by name using the picky gem for fuzzy matching. Requires the 'picky' gem to be installed. ```ruby require 'picky' # Search for users by name results = client.users_search(user: 'alice') results.each do |user| puts "#{user.name} (#{user.real_name})" end ``` -------------------------------- ### Get Channel Details Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/conversations-endpoints.md Retrieves detailed information about a specific channel, including its name, creation date, member count, and topic. ```ruby channel = client.conversations_info(channel: '#general').channel puts "Name: #{channel.name}" puts "Created: #{Time.at(channel.created)}" puts "Members: #{channel.num_members}" puts "Topic: #{channel.topic&.value}" ``` -------------------------------- ### Successful Message Post Response Example Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/types.md This snippet shows the typical structure of a successful response after posting a message, including 'ok' status, channel ID, and timestamp. ```ruby response = client.chat_postMessage(channel: '#general', text: 'Hello') response.ok # true response.channel # "C123456" response.ts # "1234567890.123456" response.message # message object with full details response.message.text # "Hello" ``` -------------------------------- ### Paginated Results with Rate Limit Handling Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md This example shows how to handle API pagination with built-in rate limiting and retry mechanisms. Configure `sleep_interval` and `max_retries` to manage API request frequency and resilience. ```ruby # Iterate through paginated results client.users_list(limit: 100) do |response| response.members.each do |user| puts "#{user.name}: #{user.real_name}" end end # With rate limit handling and pausing client.conversations_list( limit: 50, sleep_interval: 2, max_retries: 20 ) do |response| response.channels.each { |channel| process(channel) } end ``` -------------------------------- ### Find User by Name and Get Info Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Lists up to 100 users and finds a specific user by name. Displays the found user's real name and email. ```ruby # List all users and find by name user = nil client.users_list(limit: 100) do |response| user = response.members.find { |u| u.name == 'alice' } break if user end if user puts "Found: #{user.real_name} (#{user.email})" end ``` -------------------------------- ### Get Channel Info by ID Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/conversations-endpoints.md Fetches detailed information about a channel using its ID. The channel's name, topic, and creation date are then printed. ```ruby channel = client.conversations_info(channel: 'C123456').channel puts channel.name puts channel.topic puts channel.created ``` -------------------------------- ### Get Channel Info by Name Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/conversations-endpoints.md Fetches detailed information about a channel using its name. The channel's name, topic, and creation date are then printed. The client automatically looks up the channel by name. ```ruby channel = client.conversations_info(channel: '#general').channel puts channel.name puts channel.topic puts channel.created ``` -------------------------------- ### files_getUploadURLExternal Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/files-endpoints.md Get an upload URL for a file. This is used internally by files_upload_v2. ```APIDOC ## files_getUploadURLExternal ### Description Get an upload URL for a file (used internally by `files_upload_v2`). ### Method POST (inferred) ### Endpoint /files.getUploadURLExternal (inferred) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filename** (String) - Yes - Name of file to upload - **length** (Integer) - Yes - File size in bytes - **snippet_type** (String) - No - Code snippet type - **alt_txt** (String) - No - Alt text for images ### Response #### Success Response (200) - **upload_url** (String) - URL to POST file to - **file_id** (String) - File ID for completion - **ok** (Boolean) - Indicates success of the operation. #### Response Example ```json { "upload_url": "https://files.slack.com/upload/...", "file_id": "F1234567890", "ok": true } ``` ``` -------------------------------- ### Basic Slack Client Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/README.md Sets up the Slack client with a token from environment variables. This is the most basic configuration. ```ruby Slack.configure do |config| config.token = ENV['SLACK_API_TOKEN'] end client = Slack::Web::Client.new ``` -------------------------------- ### Initialize Slack::Web::Client Using Global Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Instantiate the client without arguments to use a globally configured token. Ensure Slack.configure is called beforehand. ```ruby Slack.configure { |c| c.token = ENV['SLACK_API_TOKEN'] } client = Slack::Web::Client.new ``` -------------------------------- ### Initialize Slack Client with Token Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/index.md Create a new Slack::Web::Client instance, providing the API token directly. ```ruby client = Slack::Web::Client.new(token: ENV['SLACK_API_TOKEN']) ``` -------------------------------- ### Get Signature Version Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-events-request.md Returns the signature version, which is always 'v0' for the current implementation. ```ruby def version ``` ```ruby slack_request = Slack::Events::Request.new(request) puts slack_request.version # => "v0" ``` -------------------------------- ### Get User Information Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Retrieve detailed information about a specific user using their ID. ```ruby user = client.users_info(user: 'U123456').user puts "Name: #{user.real_name}" puts "Email: #{user.profile.email}" ``` -------------------------------- ### Create, Set Topic, and Invite to Channel Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Demonstrates creating a new channel, setting its topic, and inviting users. ```ruby # Create channel = client.conversations_create(name: 'project-2024').channel # Set topic client.conversations_setTopic(channel: channel.id, topic: 'Project planning') # Add members client.conversations_invite( channel: channel.id, users: 'U123,U456,U789' ) ``` -------------------------------- ### users_info Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Get detailed information about a specific user by their ID or username. The user parameter is required. ```APIDOC ## users_info ### Description Get detailed information about a specific user. The `user` parameter is required and can be a User ID or username. ### Method POST ### Endpoint /users.info ### Parameters #### Query Parameters - **user** (String) - Yes - User ID or username (e.g., `U123456` or `@alice`) - **include_locale** (Boolean) - No - Include user locale ### Request Example ```ruby # By ID user = client.users_info(user: 'U123456').user # By username (triggers automatic lookup) user = client.users_info(user: '@alice').user puts user.name puts user.real_name puts user.email puts user.title ``` ### Response #### Success Response (200) - **user** (Object) - User object with full profile information ### Errors - `ArgumentError` - Missing `user` - `Slack::Web::Api::Errors::UserNotFound` - User does not exist ``` -------------------------------- ### Initialize Web Client with Options Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Initializes a new Slack Web client instance with specific options, such as the user agent. ```ruby client = Slack::Web::Client.new(user_agent: 'Slack Ruby Client/3.0') ``` -------------------------------- ### Get Request Timestamp Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-events-request.md Retrieves the Unix timestamp from the `X-Slack-Request-Timestamp` header. Returns nil if the header is missing. ```ruby def timestamp ``` ```ruby slack_request = Slack::Events::Request.new(request) puts slack_request.timestamp # => "1688150386" ``` -------------------------------- ### Create and Configure a New Channel Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/conversations-endpoints.md Demonstrates the process of creating a new channel, setting its topic and purpose, and inviting members. ```ruby # Create channel ch = client.conversations_create(name: 'new-project').channel # Set topic client.conversations_setTopic( channel: ch.id, topic: 'Documentation and status updates' ) # Set purpose client.conversations_setPurpose( channel: ch.id, purpose: 'Central hub for project coordination' ) # Add team members client.conversations_invite( channel: ch.id, users: 'U123,U456,U789' ) ``` -------------------------------- ### Get Channel History with Message Iteration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Retrieve and process messages from a channel's history, iterating through each message. ```ruby client.conversations_history( channel: 'C123456', limit: 100 ) do |response| response.messages.each do |msg| puts "#{msg.user}: #{msg.text}" end end ``` -------------------------------- ### Cursor Class Initialization Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/pagination.md Demonstrates the initialization of the `Slack::Web::Api::Pagination::Cursor` class, which allows for manual control over pagination. It takes the client, API verb, and pagination parameters. ```ruby class Cursor include Enumerable attr_reader :client, :verb, :sleep_interval, :max_retries, :params def initialize(client, verb, params = {}) # verb: method name as symbol (:users_list, :conversations_history, etc.) # params: options hash (limit, cursor, sleep_interval, max_retries, etc.) end def each # Yields each page response end end ``` -------------------------------- ### Get File Details and Comments Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/files-endpoints.md Retrieves detailed information about a specific file, including its metadata and associated comments. ```APIDOC ## GET /files.info ### Description Retrieves detailed information about a specific file, including its metadata, permalink, and any comments associated with it. ### Method GET ### Endpoint /files.info ### Parameters #### Query Parameters - **file** (string) - Required - The ID of the file to retrieve information for. ### Request Example ```ruby response = client.files_info(file: 'F123456') file = response.file puts "File: #{file.name}" puts "Size: #{file.size} bytes" puts "URL: #{file.permalink}" puts "Comments: #{response.comments.length}" response.comments.each do |comment| user = client.users_info(user: comment.user).user puts " #{user.name}: #{comment.comment}" end ``` ### Response #### Success Response (200) - **file** (object) - The file object containing detailed information. - **comments** (array) - An array of comment objects associated with the file. #### Response Example ```json { "file": { "id": "F123456", "name": "example.txt", "size": 512, "permalink": "https://slack.com/files/T123456/F123456/example.txt" // ... other file properties }, "comments": [ { "id": "Fc123456", "comment": "This is a test comment.", "user": "U123456" // ... other comment properties } ] } ``` ``` -------------------------------- ### users_getPresence Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Get the presence status (online, away, offline) of a user. Defaults to the authenticated user if no user is specified. ```APIDOC ## users_getPresence ### Description Get user presence status (online, away, offline). Defaults to the authenticated user if no user is specified. ### Method POST ### Endpoint /users.getPresence ### Parameters #### Query Parameters - **user** (String) - No - User ID or username. Defaults to authenticated user ### Response #### Success Response (200) - **presence** (String) - Presence status: `'active'` or `'away'` - **online** (Boolean) - true if active - **auto_away** (Boolean) - true if auto-away - **manual_away** (Boolean) - true if manually set away - **connection_count** (Integer) - Number of active connections - **last_activity** (Integer) - Unix timestamp of last activity ### Request Example ```ruby # Get authenticated user's presence presence = client.users_getPresence.presence # Get another user's presence presence = client.users_getPresence(user: 'U123456') puts presence # => 'active' or 'away' ``` ``` -------------------------------- ### Instantiate Slack Web Client with Custom Options Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/configuration.md Create a new Slack Web client instance with specific configuration options that override global or client-level settings. This allows for per-instance customization. ```ruby client = Slack::Web::Client.new( token: 'xoxb-token', user_agent: 'Custom Agent/1.0', timeout: 60, proxy: 'http://proxy:8080' ) ``` -------------------------------- ### Initialize Slack Client and Test Auth Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/index.md Instantiate the main client and perform an authentication test. Requires the 'slack-ruby-client' gem. ```ruby require 'slack-ruby-client' client = Slack::Web::Client.new(token: 'xoxb-...') client.auth_test ``` -------------------------------- ### Get a message permalink Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/chat-endpoints.md Retrieves a permanent URL for a specific message. Requires the channel ID and the message's timestamp. ```ruby response = client.chat_postMessage(channel: '#general', text: 'Share this') permalink = client.chat_getPermalink( channel: '#general', message_ts: response.ts ) puts permalink.permalink # => 'https://workspace.slack.com/archives/C123456/p1234567890123456' ``` -------------------------------- ### Automatic Configuration with Environment Variables Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Instantiate the Slack client without arguments when environment variables are set for automatic token loading. ```ruby require 'slack-ruby-client' # Token and signing secret are automatically loaded client = Slack::Web::Client.new ``` -------------------------------- ### Get All Active Admin Users Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Retrieves a list of all active administrators in the workspace. Prints the real name of each admin user. ```ruby admins = [] client.users_list do |response| response.members.each do |user| admins << user if user.is_admin && user.is_active end end admins.each { |admin| puts admin.real_name } ``` -------------------------------- ### Initialize and Access Slack Web Client Attributes Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Demonstrates how to initialize a Slack Web Client with a token and access its configuration attributes. You can also modify attributes like timeout at runtime. ```ruby client = Slack::Web::Client.new(token: 'xoxb-...') puts client.endpoint # => 'https://slack.com/api/' puts client.default_page_size # => 100 # Modify at runtime client.timeout = 60 ``` -------------------------------- ### users_identity Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Get the identity of the authenticated user, including their user ID, team ID, and user/team objects if scopes permit. ```APIDOC ## users_identity ### Description Get the identity of the authenticated user. ### Method POST ### Endpoint /users.identity ### Response #### Success Response (200) - **user_id** (String) - ID of authenticated user - **team_id** (String) - ID of user's team - **user** (Object) - User object (with app_user scope) - **team** (Object) - Team object (with team:read scope) ### Request Example ```ruby identity = client.users_identity puts "Authenticated user: #{identity.user_id}" puts "Team: #{identity.team_id}" ``` ``` -------------------------------- ### Slack::Web::Client Constructor Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Initializes a new Slack Web API client instance. You can provide an explicit token or rely on global configuration. Various options are available to customize the client's behavior, such as user agent, proxy, SSL settings, endpoint, timeouts, logging, pagination, and retry mechanisms. ```APIDOC ## initialize(options = {}) ### Description Creates a new Slack Web API client instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters - **token** (String) - Optional - Slack API token for authentication. Defaults to `Slack::Web.config.token` or `Slack.config.token`. - **user_agent** (String) - Optional - HTTP User-Agent header. Defaults to `"Slack Ruby Client/3.2.0"`. - **proxy** (String) - Optional - HTTP proxy URL. Defaults to config. - **ca_path** (String) - Optional - SSL certificates path. Defaults to config. - **ca_file** (String) - Optional - SSL certificate file. Defaults to config. - **endpoint** (String) - Optional - Slack API endpoint. Defaults to `'https://slack.com/api/'`. - **timeout** (Integer) - Optional - HTTP timeout in seconds. Defaults to config. - **open_timeout** (Integer) - Optional - Connection open timeout in seconds. Defaults to config. - **logger** (Logger) - Optional - Logger instance. Defaults to default logger. - **default_page_size** (Integer) - Optional - Default page size for pagination. Defaults to `100`. - **conversations_id_page_size** (Integer) - Optional - Page size for channel lookups. Defaults to config. - **users_id_page_size** (Integer) - Optional - Page size for user lookups. Defaults to config. - **default_max_retries** (Integer) - Optional - Max retries for rate-limited requests. Defaults to `100`. - **adapter** (Symbol/Object) - Optional - Faraday HTTP adapter. Defaults to `Faraday.default_adapter`. ### Returns `Slack::Web::Client` - New client instance ### Example ```ruby # With explicit token client = Slack::Web::Client.new(token: 'xoxb-1234567890-abcdefgh') # Using global configuration Slack.configure { |c| c.token = ENV['SLACK_API_TOKEN'] } client = Slack::Web::Client.new # With custom options client = Slack::Web::Client.new( token: 'xoxb-...', timeout: 60, user_agent: 'MyApp/1.0', logger: Logger.new('slack.log') ) ``` ``` -------------------------------- ### Get Channel Info by ID Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Retrieves information about a specific channel using its ID with the conversations_info method. This is the recommended approach for performance. ```ruby client.conversations_info(channel: 'C04KB5X4D') # calls conversations_info ``` -------------------------------- ### Slack Event Handling with Generic HTTP Server (Net::HTTP) Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-events-request.md Demonstrates how to handle Slack events using a generic HTTP server with Net::HTTP. It sets up a WEBrick server to listen for events, verifies requests, and responds to challenges or callbacks. ```ruby require 'webrick' server = WEBrick::HTTPServer.new(Port: 3000) server.mount_proc '/slack/events' do |req, res| slack_request = Slack::Events::Request.new(req) unless slack_request.verify! res.status = 401 res.body = 'Unauthorized' next end body = JSON.parse(slack_request.body) case body['type'] when 'url_verification' res.body = body['challenge'] when 'event_callback' # Handle event res.status = 200 end end server.start ``` -------------------------------- ### Access Slack::Web::Client Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Retrieve the current global configuration settings for the Slack Web Client. ```ruby puts Slack::Web::Client.config.timeout ``` -------------------------------- ### Upload Code Snippet Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/files-endpoints.md Uploads a code snippet to a specific channel, specifying the snippet type. Useful for sharing scripts or code examples. ```ruby code = File.read('deploy.rb') client.files_upload_v2( filename: 'deploy.rb', content: code, snippet_type: 'ruby', channel_id: 'C123456', initial_comment: 'Deployment script' ) ``` -------------------------------- ### Configure Client with Custom SSL Certificates Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/configuration.md Initializes the Slack client with custom SSL certificate paths. Use `ca_path` for a directory of certificates or `ca_file` for a single certificate file. ```ruby client = Slack::Web::Client.new( token: 'xoxb-...', ca_path: '/etc/ssl/certs', ca_file: '/path/to/custom-cert.pem' ) ``` -------------------------------- ### Global Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.md Configure the Slack client globally. This is the primary method for setting up default client options. ```ruby Slack.configure do |config| config.token = "YOUR_SLACK_API_TOKEN" end ``` -------------------------------- ### Get Request Signature Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-events-request.md Retrieves the request signature from the `X-Slack-Signature` header. The signature is in the format `v0=`. Returns nil if the header is missing. ```ruby def signature ``` ```ruby slack_request = Slack::Events::Request.new(request) puts slack_request.signature # => "v0=abcd1234efgh5678..." ``` -------------------------------- ### Web Client Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/DOCUMENTATION_SUMMARY.md Configure specific options for the Web client. Use this for advanced settings not covered by global configuration. ```ruby Slack::Web::Client.configure do |config| config.logger = Logger.new(STDOUT) end ``` -------------------------------- ### Get Authenticated User Presence Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Retrieve the presence status (active or away) of the authenticated user. Defaults to the current user if no user is specified. ```ruby # Get authenticated user's presence presence = client.users_getPresence.presence ``` -------------------------------- ### Configure Slack::Web::Client Globally Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Set global configuration options that will apply to all future Slack::Web::Client instances. This is useful for setting default user agent, timeout, and page sizes. ```ruby Slack::Web::Client.configure do |config| config.user_agent = 'MyApp/1.0' config.timeout = 30 config.default_page_size = 50 end ``` -------------------------------- ### Get User Info by ID Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Retrieve detailed information for a specific user using their User ID. Requires the user ID as a parameter. ```ruby # By ID user = client.users_info(user: 'U123456').user puts user.name puts user.real_name puts user.email puts user.title ``` -------------------------------- ### Enable Logging with a Logger Instance Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Enable detailed logging for the Slack client by providing a Logger instance during client initialization. ```ruby require 'logger' logger = Logger.new(STDOUT) logger.level = Logger::DEBUG client = Slack::Web::Client.new( token: ENV['SLACK_API_TOKEN'], logger: logger ) ``` -------------------------------- ### Slack Client Configuration with Custom Options Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/README.md Configures the Slack client with a token, timeout, and user agent. Useful for controlling client behavior. ```ruby client = Slack::Web::Client.new( token: ENV['SLACK_API_TOKEN'], timeout: 30, user_agent: 'MyApp/1.0' ) ``` -------------------------------- ### Fork and Clone Project Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/CONTRIBUTING.md Clone the forked project and set up the upstream remote for future updates. ```bash git clone https://github.com/contributor/slack-ruby-client.git cd slack-ruby-client git remote add upstream https://github.com/slack-ruby/slack-ruby-client.git ``` -------------------------------- ### List All Users with Pagination Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Fetch all users in the workspace, handling pagination by iterating through responses. Useful for retrieving a complete user list. ```ruby # Fetch all users with pagination all_users = [] client.users_list do |response| all_users.concat(response.members) end puts "Workspace has #{all_users.length} users" ``` -------------------------------- ### Set Environment Variables for Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/quick-start.md Set SLACK_API_TOKEN and SLACK_SIGNING_SECRET environment variables for automatic configuration. ```bash export SLACK_API_TOKEN="xoxb-1234567890-1234567890-abcdefghijklmnop" export SLACK_SIGNING_SECRET="abcd1234efgh5678ijkl9012mnop3456" ``` -------------------------------- ### Convert Paginated Results to Array Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/pagination.md Demonstrates two ways to get all paginated results: by collecting them in a block or by fetching a single page without a block. ```ruby # Get all results as an array all_users = [] client.users_list(limit: 100) do |response| all_users.concat(response.members) end # Or fetch without block for single page response = client.users_list(limit: 100) first_page_users = response.members ``` -------------------------------- ### Preserve start_options when updating Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/UPGRADING.md When explicitly setting start_options, merge new settings instead of replacing the entire value to preserve existing configurations like request timeouts. ```ruby Slack::RealTime::Client.config do |config| config.start_options[:no_unreads] = true # keeps config.start_options[:request] intact end ``` -------------------------------- ### Get Authenticated User Identity Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Fetch the identity of the currently authenticated user, including their user ID and team ID. Requires appropriate scopes. ```ruby identity = client.users_identity puts "Authenticated user: #{identity.user_id}" puts "Team: #{identity.team_id}" ``` -------------------------------- ### Send a message using Blocks (Recommended) Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/chat-endpoints.md This snippet demonstrates sending a message with rich content using Slack's Blocks Kit. It includes header, section, and action elements. ```ruby client.chat_postMessage( channel: '#general', blocks: [ { type: 'header', text: { type: 'plain_text', text: 'My Header' } }, { type: 'section', text: { type: 'mrkdwn', text: '*Bold text* and _italic text_' } }, { type: 'section', fields: [ { type: 'mrkdwn', text: '*Priority*\nHigh' }, { type: 'mrkdwn', text: '*Status*\nOpen' } ] }, { type: 'actions', elements: [ { type: 'button', text: { type: 'plain_text', text: 'Click me' }, value: 'click_me' } ] } ] ) ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/CONTRIBUTING.md Stage all changes and prepare for a commit. The commit message will be prompted interactively. ```bash git add ... git commit ``` -------------------------------- ### Get Raw Request Body Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-events-request.md Retrieves the raw request body, which is essential for signature verification. The body stream is read and then rewound for potential repeated access. ```ruby def body ``` ```ruby slack_request = Slack::Events::Request.new(request) event_data = JSON.parse(slack_request.body) ``` -------------------------------- ### Slack::Web::Client Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Allows configuring global settings for all future `Slack::Web::Client` instances. You can access and modify these configurations using `configure` or `config` methods. ```APIDOC ## Configuration ### self.configure ### Description Configure all future `Slack::Web::Client` instances. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Example ```ruby Slack::Web::Client.configure do |config| config.user_agent = 'MyApp/1.0' config.timeout = 30 config.default_page_size = 50 end ``` ### self.config ### Description Access the current configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Example ```ruby puts Slack::Web::Client.config.timeout ``` ``` -------------------------------- ### Get File Information Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/files-endpoints.md Retrieve detailed information about a specific file using its ID. This method also supports pagination for retrieving comments associated with the file. ```ruby response = client.files_info(file: 'F123456') file = response.file puts "Name: #{file.name}" puts "Size: #{file.size}" puts "Created: #{Time.at(file.created)}" puts "URL: #{file.permalink}" ``` -------------------------------- ### Get User Info by Username Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Retrieve detailed information for a specific user using their username (e.g., '@alice'). The API will automatically look up the user by name. ```ruby # By username (triggers automatic lookup) user = client.users_info(user: '@alice').user puts user.name puts user.real_name puts user.email puts user.title ``` -------------------------------- ### Configure Web Client User Agent and Timeout Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/index.md Customize the user agent and request timeout for the Slack::Web::Client. ```ruby Slack::Web::Client.configure do |config| config.user_agent = 'My App/1.0' config.timeout = 30 end ``` -------------------------------- ### Catching SlackError Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/errors.md Catch the base SlackError to handle any API-related error response from Slack. This example shows how to access the error code, response status, and response body. ```ruby begin client.chat_postMessage(channel: 'C123', text: 'Hello') rescue Slack::Web::Api::Errors::SlackError => e puts "Error: #{e.error}" puts "Status: #{e.response.status}" puts "Body: #{e.response.body}" end ``` -------------------------------- ### List Users and Format with jq Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md List all users in Slack and process the JSON output with jq to extract and format user IDs and names. This demonstrates combining the Slack CLI with powerful JSON processing tools. ```bash $ slack users list | jq '.members | map({(.id): .name})' [ { "U04KB5WQR": "dblock" }, { "U07518DTL": "rubybot" } ] ``` -------------------------------- ### Get Another User's Presence Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Retrieve the presence status (active or away) of a specific user by providing their User ID. Useful for monitoring other users' availability. ```ruby # Get another user's presence presence = client.users_getPresence(user: 'U123456') puts presence # => 'active' or 'away' ``` -------------------------------- ### Get File Details and Comments Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/files-endpoints.md Retrieves detailed information about a specific file, including its name, size, permalink, and associated comments. Useful for inspecting file content and history. ```ruby response = client.files_info(file: 'F123456') file = response.file puts "File: #{file.name}" puts "Size: #{file.size} bytes" puts "URL: #{file.permalink}" puts "Comments: #{response.comments.length}" response.comments.each do |comment| user = client.users_info(user: comment.user).user puts " #{user.name}: #{comment.comment}" end ``` -------------------------------- ### Configure Client with Custom HTTP Adapter Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/configuration.md Sets a custom HTTP adapter for the Slack client. This allows using alternative HTTP libraries like `:httpclient` instead of the default. ```ruby client = Slack::Web::Client.new( token: 'xoxb-...', adapter: :httpclient ) ``` -------------------------------- ### Configure Global Slack Client Settings Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/configuration.md Set global configuration options like API token and logger for all client instances. This is useful for setting up default behaviors across your application. ```ruby Slack.configure do |config| config.token = ENV['SLACK_API_TOKEN'] config.logger = Logger.new(STDOUT) end ``` -------------------------------- ### Configure Web Client Globally Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Configures the Slack Web client globally using a block to set options like the user agent. ```ruby Slack::Web::Client.configure do |config| config.user_agent = 'Slack Ruby Client/3.0' end ``` -------------------------------- ### Channel Object Attributes Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/types.md Provides an example of a Channel object obtained from a conversations_info API call. It shows how to access common fields like ID, name, creation details, and membership information. ```ruby channel = client.conversations_info(channel: 'C123456').channel channel.id # "C123456" channel.name # "general" channel.created # 1234567890 channel.creator # "U123456" channel.is_archived # false channel.is_general # true channel.is_member # true channel.is_private # false channel.is_mpim # false channel.topic # { value: "Project discussion", creator: "U123", last_set: 1234567890 } channel.purpose # { value: "Team collaboration", creator: "U123", last_set: 1234567890 } channel.num_members # 42 channel.members # ["U123", "U456", "U789"] channel.last_read # "1234567890.123456" channel.latest # { text: "...", user: "U123", ts: "1234567890.123456" } ``` -------------------------------- ### Configure Client with Request Logging Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/configuration.md Initializes the Slack client with a logger to capture all outgoing HTTP requests. Useful for debugging and monitoring API interactions. ```ruby require 'logger' logger = Logger.new(STDOUT) logger.level = Logger::DEBUG client = Slack::Web::Client.new( token: 'xoxb-...', logger: logger ) ``` -------------------------------- ### Expose Local Server with ngrok Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/examples/oauth_v2/README.md Use ngrok to expose your local server to the internet for testing OAuth flows. Ensure your local server is running on the specified port. ```sh ngrok http 4242 ``` -------------------------------- ### Get User Info by Name Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Retrieves information about a user using their name (prefixed with '@'). This method internally calls users_list to find the user ID, which may incur costs if you have many users. ```ruby client.users_info(user: '@dblock') # calls users_list followed by users_info ``` -------------------------------- ### Global Default Page Size Configuration Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/pagination.md Configure global defaults for `default_page_size` and `default_max_retries` that will be used by all clients unless overridden. ```ruby Slack::Web::Client.configure do |config| config.default_page_size = 50 config.default_max_retries = 50 end # All clients will use these defaults client = Slack::Web::Client.new client.users_list { |response| ... } # Uses limit: 50 ``` -------------------------------- ### Get Channel Info by Name Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Retrieves information about a channel using its name (prefixed with '#'). This method internally calls conversations_list to find the channel ID, which may incur costs if you have many channels. ```ruby client.conversations_info(channel: '#general') # calls conversations_list followed by conversations_info ``` -------------------------------- ### Commit Release Preparation Changes Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/RELEASING.md Stage and commit the changes made to README.md and CHANGELOG.md for the release preparation. ```bash git add README.md CHANGELOG.md git commit -m "Preparing for release, 0.2.2." git push origin master ``` -------------------------------- ### Simplified File Uploads Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/README.md Use the `files_upload_v2` method for a streamlined file upload process. Ensure the file content and channel ID are provided. ```ruby client.files_upload_v2( filename: 'report.pdf', content: File.read('report.pdf'), channel_id: 'C123456' ) ``` -------------------------------- ### Get User Profile Information Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/users-endpoints.md Retrieves detailed profile information for a specific user ID. Prints the user's real name, title, email, phone, avatar, and status text. ```ruby user = client.users_info(user: 'U123456').user puts "Name: #{user.profile.real_name}" puts "Title: #{user.profile.title}" puts "Email: #{user.profile.email}" puts "Phone: #{user.profile.phone}" puts "Avatar: #{user.profile.image_72}" puts "Status: #{user.profile.status_text}" ``` -------------------------------- ### Format URL Link Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Create a Slack-formatted URL link with custom display text. ```ruby text = 'party time' url = 'https://media.giphy.com/media/AcfTF7tyikWyroP0x7/giphy.gif' Slack::Messages::Formatting.url_link(text, url) # => "" ``` -------------------------------- ### Configure Slack Events Globally Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/README.md Configure Slack Events support globally by setting the signing secret. ```ruby Slack::Events.configure do |config| config.signing_secret = 'secret' end ``` -------------------------------- ### Upload Code Snippet using files_upload_v2 Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/slack-web-client.md Upload a code snippet by specifying the filename, content, snippet type (e.g., 'python'), channel, and title. This is useful for sharing code examples directly within Slack. ```ruby response = client.files_upload_v2( filename: 'script.py', content: python_code, snippet_type: 'python', channel_id: 'C123456', title: 'Data Processing Script' ) ``` -------------------------------- ### List All Files in Workspace Source: https://github.com/slack-ruby/slack-ruby-client/blob/master/_autodocs/api-reference/files-endpoints.md Use this method to retrieve a list of all files in your Slack workspace. It supports pagination to handle large numbers of files. The response includes file objects and pagination metadata. ```ruby all_files = [] client.files_list(limit: 100) do |response| all_files.concat(response.files) end puts "Workspace has #{all_files.length} files" ```