### Initialize and Manage Slack Apps with Slack CLI Source: https://context7.com/context7/tools_slack_dev/llms.txt The Slack CLI is a command-line tool for creating, managing, and deploying Slack applications. It supports app initialization from templates, authentication, local development with hot reloading, and deployment. Ensure you have curl installed for the initial installation script. ```bash # Install the Slack CLI curl -fsSL https://downloads.slack-edge.com/slack-cli/install.sh | bash # Create a new Slack app from a template slack create my-app --template deno-blank # Authenticate with your Slack workspace slack login # Start local development server with hot reloading slack run # Deploy app to Slack slack deploy # View app logs in real-time slack activity --tail ``` -------------------------------- ### Slack OAuth Installation with Bolt.js Source: https://context7.com/context7/tools_slack_dev/llms.txt Implements a multi-workspace Slack app installation flow using the Bolt.js framework and an Express receiver. It handles storing and fetching installation data from a database, including enterprise and team-specific installations. Dependencies include '@slack/bolt' and a custom database connection module. ```javascript const { App, ExpressReceiver } = require('@slack/bolt'); const { createConnection } = require('./database'); // Create custom receiver for OAuth handling const receiver = new ExpressReceiver({ signingSecret: process.env.SLACK_SIGNING_SECRET, clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, stateSecret: 'my-state-secret', scopes: [ 'channels:read', 'chat:write', 'commands', 'users:read', 'app_mentions:read' ], installationStore: { storeInstallation: async (installation) => { // Store installation data in database const db = await createConnection(); if (installation.isEnterpriseInstall && installation.enterprise) { await db.query( 'INSERT INTO installations (enterprise_id, team_id, bot_token, bot_id, installed_at) VALUES (?, ?, ?, ?, NOW())', [ installation.enterprise.id, installation.team.id, installation.bot.token, installation.bot.userId, ] ); return; } if (installation.team) { await db.query( 'INSERT INTO installations (team_id, bot_token, bot_id, installed_at) VALUES (?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE bot_token = VALUES(bot_token), bot_id = VALUES(bot_id)', [ installation.team.id, installation.bot.token, installation.bot.userId, ] ); } await db.end(); }, fetchInstallation: async (installQuery) => { const db = await createConnection(); let query; let params; if (installQuery.isEnterpriseInstall && installQuery.enterpriseId) { query = 'SELECT * FROM installations WHERE enterprise_id = ? AND team_id = ?'; params = [installQuery.enterpriseId, installQuery.teamId]; } else if (installQuery.teamId) { query = 'SELECT * FROM installations WHERE team_id = ?'; params = [installQuery.teamId]; } const [rows] = await db.query(query, params); await db.end(); if (rows.length === 0) { throw new Error('Installation not found'); } const row = rows[0]; return { team: { id: row.team_id }, enterprise: row.enterprise_id ? { id: row.enterprise_id } : undefined, bot: { token: row.bot_token, userId: row.bot_id, scopes: ['channels:read', 'chat:write', 'commands', 'users:read', 'app_mentions:read'] } }; }, deleteInstallation: async (installQuery) => { const db = await createConnection(); if (installQuery.teamId) { await db.query('DELETE FROM installations WHERE team_id = ?', [installQuery.teamId]); } await db.end(); } } }); const app = new App({ receiver }); // Custom installation landing page receiver.router.get('/slack/install', (req, res) => { res.send(`
Click the button below to install the app to your workspace.
`);
});
// Success page after installation
receiver.router.get('/slack/oauth_redirect', async (req, res) => {
res.send(`
The app has been installed to your workspace.
`); }); // Start server (async () => { await app.start(3000); console.log('⚡️ App is running with OAuth support!'); console.log('Install URL: http://localhost:3000/slack/install'); })(); ``` -------------------------------- ### Build Slack Home Tab and Modal with Bolt for Java Source: https://context7.com/context7/tools_slack_dev/llms.txt This snippet demonstrates creating a Slack application using Bolt for Java. It includes code to publish a Home tab view with interactive elements and to open a modal view in response to a slash command. Dependencies include the Bolt for Java library and Slack API client. Input is handled via events and command payloads, and output is sent back to Slack via the client. This example focuses on UI interactions and does not include backend logic for data persistence. ```java import com.slack.api.bolt.App; import com.slack.api.bolt.jetty.SlackAppServer; import com.slack.api.model.view.View; import static com.slack.api.model.block.Blocks.*; import static com.slack.api.model.block.composition.BlockCompositions.*; import static com.slack.api.model.view.Views.*; public class SlackApp { public static void main(String[] args) throws Exception { var app = new App(); // Handle home tab app.event(AppHomeOpenedEvent.class, (event, ctx) -> { try { var homeView = view(view -> view .type("home") .blocks(asBlocks( section(section -> section .text(markdownText("*Welcome to the Dashboard* :tada:")) ), divider(), section(section -> section .text(markdownText("*Recent Activity*")) ), section(section -> section .fields(asFields( markdownText("*Tasks:* 5 pending"), markdownText("*Status:* All systems operational") )) ), actions(actions -> actions .elements(asElements( button(b -> b .text(plainText("View Tasks")) .actionId("view_tasks") .style("primary") ), button(b -> b .text(plainText("Create Task")) .actionId("create_task") ) )) ) )) ); ctx.client().viewsPublish(r -> r .userId(event.getUser()) .view(homeView) ); return ctx.ack(); } catch (Exception e) { ctx.logger.error("Error publishing home view", e); return ctx.ack(); } }); // Handle slash command app.command("/create-ticket", (req, ctx) -> { var view = view(v -> v .type("modal") .callbackId("ticket_modal") .title(viewTitle(title -> title.text("Create Ticket"))) .submit(viewSubmit(submit -> submit.text("Create"))) .close(viewClose(close -> close.text("Cancel"))) .blocks(asBlocks( input(input -> input .blockId("title_block") .element(plainTextInput(pti -> pti .actionId("title_input") .placeholder(plainText("Enter ticket title")) )) .label(plainText("Title")) ), input(input -> input .blockId("description_block") .element(plainTextInput(pti -> pti .actionId("description_input") .multiline(true) .placeholder(plainText("Describe the issue")) )) .label(plainText("Description")) ), input(input -> input .blockId("priority_block") .element(staticSelect(ss -> ss .actionId("priority_select") .placeholder(plainText("Select priority")) .options(asOptions( option(plainText("Low"), "low"), option(plainText("Medium"), "medium"), option(plainText("High"), "high"), option(plainText("Critical"), "critical") )) )) .label(plainText("Priority")) ) )) ); ctx.client().viewsOpen(r -> r .triggerId(req.getPayload().getTriggerId()) .view(view) ); return ctx.ack(); }); // Handle modal submission app.viewSubmission("ticket_modal", (req, ctx) -> { var stateValues = req.getPayload().getView().getState().getValues(); var title = stateValues.get("title_block").get("title_input").getValue(); ``` -------------------------------- ### Handle Events and Commands with Bolt for JavaScript Source: https://context7.com/context7/tools_slack_dev/llms.txt Bolt for JavaScript simplifies building Slack apps by providing interfaces for events, commands, and interactions. It requires the `@slack/bolt` package and environment variables for token, signing secret, and app token. This example demonstrates listening for messages and handling slash commands. ```javascript const { App } = require('@slack/bolt'); // Initialize app with credentials const app = new App({ token: process.env.SLACK_BOT_TOKEN, signingSecret: process.env.SLACK_SIGNING_SECRET, socketMode: true, appToken: process.env.SLACK_APP_TOKEN }); // Listen for message events containing "hello" app.message('hello', async ({ message, say }) => { try { await say({ text: `Hey there <@${message.user}>!`, blocks: [ { type: "section", text: { type: "mrkdwn", text: `Hello <@${message.user}>, how can I help you today?` } } ] }); } catch (error) { console.error('Error posting message:', error); } }); // Handle slash commands app.command('/ticket', async ({ command, ack, respond }) => { await ack(); await respond(`Creating ticket: ${command.text}`); }); // Start the app (async () => { await app.start(3000); console.log('⚡️ Bolt app is running!'); })(); ``` -------------------------------- ### Manage Interactive Components with Bolt for Python Source: https://context7.com/context7/tools_slack_dev/llms.txt Bolt for Python facilitates handling interactive Slack components such as buttons, modals, and select menus. It requires the `slack_bolt` library and environment variables for the bot token and app token. This example shows handling button clicks, opening a modal via a slash command, and processing modal submissions. ```python from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler import os app = App(token=os.environ.get("SLACK_BOT_TOKEN")) # Handle button clicks @app.action("approve_button") def handle_approval(ack, body, client): ack() user_id = body["user"]["id"] channel_id = body["channel"]["id"] try: client.chat_postMessage( channel=channel_id, text=f"<@{user_id}> approved the request!" ) except Exception as e: print(f"Error: {e}") # Open a modal when slash command is invoked @app.command("/feedback") def open_modal(ack, body, client): ack() client.views_open( trigger_id=body["trigger_id"], view={ "type": "modal", "callback_id": "feedback_modal", "title": {"type": "plain_text", "text": "Feedback Form"}, "submit": {"type": "plain_text", "text": "Submit"}, "blocks": [ { "type": "input", "block_id": "feedback_block", "element": { "type": "plain_text_input", "action_id": "feedback_input", "multiline": True }, "label": {"type": "plain_text", "text": "Your feedback"} } ] } ) # Handle modal submission @app.view("feedback_modal") def handle_submission(ack, body, client, view): feedback = view["state"]["values"]["feedback_block"]["feedback_input"]["value"] user_id = body["user"]["id"] ack() client.chat_postMessage( channel=user_id, text=f"Thank you for your feedback: {feedback}" ) if __name__ == "__main__": handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]) handler.start() ``` -------------------------------- ### Design Slack Messages with Block Kit Builder (JavaScript) Source: https://context7.com/context7/tools_slack_dev/llms.txt Example of Block Kit JSON structure for designing Slack messages. This JSON can be used with the Block Kit Builder for visual design and then integrated into applications using the Web API or frameworks like Bolt. ```javascript // Example Block Kit JSON from the builder // Use at https://app.slack.com/block-kit-builder const messageBlocks = { "blocks": [ { "type": "header", "text": { "type": "plain_text", "text": "New Support Ticket #1234" } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Priority:* High" }, { "type": "mrkdwn", "text": "*Status:* Open" }, { "type": "mrkdwn", "text": "*Assigned to:* <@U123456>" }, { "type": "mrkdwn", "text": "*Created:* 2024-01-15 10:30 AM" } ] }, { "type": "section", "text": { "type": "mrkdwn", "text": "*Description* Customer reports login issues on mobile app. Unable to authenticate with SSO." } }, { "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": "Assign to me" }, "style": "primary", "action_id": "assign_ticket" }, { "type": "button", "text": { "type": "plain_text", "text": "Close ticket" }, "action_id": "close_ticket" }, { "type": "button", "text": { "type": "plain_text", "text": "View details" }, "url": "https://tickets.example.com/1234", "action_id": "view_ticket" } ] } ] }; // Use with Web API or Bolt const { WebClient } = require('@slack/web-api'); const client = new WebClient(process.env.SLACK_BOT_TOKEN); client.chat.postMessage({ channel: 'C1234567890', text: 'New support ticket', blocks: messageBlocks.blocks }); ``` -------------------------------- ### GitHub Actions Workflow: Deploy and Notify (YAML) Source: https://context7.com/context7/tools_slack_dev/llms.txt This YAML workflow defines the steps for testing, building, deploying an application, and sending Slack notifications. It uses standard GitHub Actions steps and the slackapi/slack-github-action. Dependencies include npm for build and test commands. Inputs are the GitHub repository context and secrets. Outputs include the deployment URL on success. ```yaml name: Deploy and Notify on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Run tests id: tests run: npm test - name: Deploy application id: deploy run: | npm run build npm run deploy echo "deployment_url=https://app-${{ github.sha }}.example.com" >> $GITHUB_OUTPUT - name: Send Slack notification on success if: success() uses: slackapi/slack-github-action@v1.24.0 with: payload: | { "text": "Deployment successful! :rocket:", "blocks": [ { "type": "header", "text": { "type": "plain_text", "text": "Deployment Successful" } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Repository:* ${{ github.repository }}" }, { "type": "mrkdwn", "text": "*Branch:* ${{ github.ref_name }}" }, { "type": "mrkdwn", "text": "*Commit:* <${{ github.event.head_commit.url }}|${{ github.sha }}>" }, { "type": "mrkdwn", "text": "*Author:* ${{ github.event.head_commit.author.name }}" } ] }, { "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": "View Deployment" }, "url": "${{ steps.deploy.outputs.deployment_url }}" }, { "type": "button", "text": { "type": "plain_text", "text": "View Commit" }, "url": "${{ github.github.event.head_commit.url }}" } ] } ] } env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} - name: Send Slack notification on failure if: failure() uses: slackapi/slack-github-action@v1.24.0 with: payload: | { "text": "Deployment failed! :x:", "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": ":x: *Deployment Failed*\nRepository: ${{ github.repository }}\nBranch: ${{ github.ref_name }}\n<${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}|View workflow run>" } } ] } env: SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} ``` -------------------------------- ### Python Slack SDK: Async Message Posting and Channel Archiving Source: https://context7.com/context7/tools_slack_dev/llms.txt Demonstrates asynchronous operations using the Python Slack SDK, enabling concurrent message posting to multiple channels and efficient channel management, including listing and archiving inactive channels. Requires the SLACK_BOT_TOKEN environment variable. ```python import asyncio from slack_sdk.web.async_client import AsyncWebClient from slack_sdk.errors import SlackApiError import os client = AsyncWebClient(token=os.environ["SLACK_BOT_TOKEN"]) async def post_multiple_messages(channels): """Post messages to multiple channels concurrently""" tasks = [] for channel in channels: task = client.chat_postMessage( channel=channel, text=f"Notification for {channel}", blocks=[ { "type": "section", "text": { "type": "mrkdwn", "text": f"*Alert*: System maintenance in 1 hour" } } ] ) tasks.append(task) try: results = await asyncio.gather(*tasks, return_exceptions=True) for i, result in enumerate(results): if isinstance(result, Exception): print(f"Error posting to {channels[i]}: {result}") else: print(f"Posted to {channels[i]}: {result['ts']}") return results except Exception as e: print(f"Error in batch operation: {e}") raise async def list_and_archive_channels(): """List all channels and archive inactive ones""" try: # Get all channels response = await client.conversations_list( types="public_channel,private_channel", limit=200 ) channels = response["channels"] archived_count = 0 for channel in channels: # Archive channels with no messages in 90 days if channel.get("num_members", 0) == 0 and not channel["is_archived"]: try: await client.conversations_archive(channel=channel["id"]) archived_count += 1 print(f"Archived: {channel['name']}") except SlackApiError as e: print(f"Could not archive {channel['name']}: {e.response['error']}") print(f"Total archived: {archived_count}") return archived_count except SlackApiError as e: print(f"Error: {e.response['error']}") raise # Run async operations asyncio.run(post_multiple_messages(['C111', 'C222', 'C333'])) asyncio.run(list_and_archive_channels()) ``` -------------------------------- ### Create Slack Ticket and Post Message (Java) Source: https://context7.com/context7/tools_slack_dev/llms.txt This snippet demonstrates how to create a new ticket in a Slack application. It retrieves ticket details, saves the ticket to a database, and then posts a formatted message to a '#support' channel including the ticket ID, description, and priority. It utilizes the Slack API for message posting. ```java var description = stateValues.get("description_block").get("description_input").getValue(); var priority = stateValues.get("priority_block").get("priority_select").getSelectedOption().getValue(); // Save ticket to database String ticketId = saveTicket(title, description, priority); // Post message ctx.client().chatPostMessage(r -> r .channel("#support") .text("New ticket created: " + title) .blocks(asBlocks( section(s -> s.text(markdownText("*Ticket #" + ticketId + "*\n" + description))), context(c -> c.elements(asContextElements( markdownText("Priority: *" + priority + "*")))) )) ); return ctx.ack(); }); var server = new SlackAppServer(app); server.start(); } private static String saveTicket(String title, String description, String priority) { // Database logic here return "TICKET-" + System.currentTimeMillis(); } ``` -------------------------------- ### Create Workflow Functions with Deno Slack SDK (TypeScript) Source: https://context7.com/context7/tools_slack_dev/llms.txt Defines a Slack function using the Deno SDK for sending approval requests. This function takes parameters like requestor, approver, reason, and channel, and uses Slack's chat.postMessage to send interactive messages. ```typescript // functions/send_approval.ts import { DefineFunction, Schema, SlackFunction } from "deno-slack-sdk/mod.ts"; export const SendApprovalFunction = DefineFunction({ callback_id: "send_approval", title: "Send approval request", source_file: "functions/send_approval.ts", input_parameters: { properties: { requestor: { type: Schema.slack.types.user_id }, approver: { type: Schema.slack.types.user_id }, reason: { type: Schema.types.string }, channel: { type: Schema.slack.types.channel_id }, }, required: ["requestor", "approver", "reason", "channel"], }, output_parameters: { properties: { approved: { type: Schema.types.boolean }, timestamp: { type: Schema.types.string }, }, required: ["approved"], }, }); export default SlackFunction( SendApprovalFunction, async ({ inputs, client }) => { try { // Send approval request to approver const result = await client.chat.postMessage({ channel: inputs.approver, text: `Approval request from <@${inputs.requestor}>`, blocks: [ { type: "section", text: { type: "mrkdwn", text: `*Approval Request*\n<@${inputs.requestor}> needs approval for:\n>${inputs.reason}`, }, }, { type: "actions", elements: [ { type: "button", text: { type: "plain_text", text: "Approve" }, style: "primary", action_id: "approve_request", value: inputs.requestor, }, { type: "button", text: { type: "plain_text", text: "Deny" }, style: "danger", action_id: "deny_request", value: inputs.requestor, }, ], }, ], }); // Post confirmation in channel await client.chat.postMessage({ channel: inputs.channel, text: `Approval request sent to <@${inputs.approver}>`, }); return { outputs: { approved: false, timestamp: result.ts || new Date().toISOString(), }, }; } catch (error) { console.error("Error sending approval:", error); return { error: `Failed to send approval: ${error.message}` }; } }, ); ``` -------------------------------- ### Node.js Slack SDK: Post Message and Upload File Source: https://context7.com/context7/tools_slack_dev/llms.txt Utilizes the Node.js Slack SDK to interact with Slack's Web API. It demonstrates how to post messages with rich block content and upload files. Requires the SLACK_BOT_TOKEN environment variable for authentication. ```javascript const { WebClient } = require('@slack/web-api'); const client = new WebClient(process.env.SLACK_BOT_TOKEN); async function postMessage() { try { // Post a message to a channel const result = await client.chat.postMessage({ channel: 'C1234567890', text: 'Hello from the Slack SDK!', blocks: [ { type: 'section', text: { type: 'mrkdwn', text: '*Important Update*\nDeployment completed successfully.' } }, { type: 'actions', elements: [ { type: 'button', text: { type: 'plain_text', text: 'View Details' }, action_id: 'view_details', url: 'https://example.com/deployment/123' } ] } ] }); console.log('Message sent:', result.ts); return result; } catch (error) { console.error('Error posting message:', error); throw error; } } async function uploadFile() { try { const result = await client.files.uploadV2({ channel_id: 'C1234567890', file: './report.pdf', filename: 'weekly-report.pdf', initial_comment: 'Here is this week\'s report' }); console.log('File uploaded:', result.file.id); return result; } catch (error) { console.error('Error uploading file:', error); throw error; } } async function getUserInfo(userId) { try { const result = await client.users.info({ user: userId }); console.log('User:', result.user.real_name); return result.user; } catch (error) { console.error('Error fetching user:', error); throw error; } } // Execute functions postMessage(); uploadFile(); getUserInfo('U1234567890'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.