### Example Database Object for Installation Store Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md A simple in-memory database implementation for testing the installation store functionality. ```javascript const database = { store: {}, async get(key) { return this.store[key]; }, async delete(key) { delete this.store[key]; }, async set(key, value) { this.store[key] = value; }, }; ``` -------------------------------- ### Install Dependencies Source: https://github.com/slackapi/bolt-js/blob/main/AGENTS.md Run this command to install all project dependencies. ```bash npm install ``` -------------------------------- ### Initialize and Configure the Assistant Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/code-assistant.md Creates an instance of the Assistant, defining its behavior for when a thread starts (sending an initial greeting and suggested prompts) and when a user sends a message (processing the message, retrieving thread history, and getting a response from the LLM). ```javascript // Create the assistant const assistant = new Assistant({ threadStarted: async ({ logger, say, setSuggestedPrompts }) => { try { await say( "Hi! I'm your coding assistant. Ask me any questions about code!", ); const prompts = [ { title: "Code Example", message: "Show me an example of implementing a binary search tree in JavaScript.", }, { title: "Code Review", message: "What are best practices for writing clean, maintainable code?", }, { title: "Debug Help", message: "How do I debug memory leaks in Node.js applications?", }, ]; await setSuggestedPrompts({ prompts, title: "Here are some questions you can ask:", }); } catch (error) { logger.error("Error in threadStarted:", error); } }, userMessage: async ({ message, client, logger, say, setTitle, setStatus }) => { const { channel, thread_ts } = message; try { await setTitle(message.text); await setStatus("is thinking..."); // Retrieve the Assistant thread history for context of question being asked const thread = await client.conversations.replies ({ channel, ts: thread_ts, oldest: thread_ts, }); // Prepare and tag each message for LLM processing const userMessage = { role: "user", content: message.text }; const threadHistory = thread.messages.map((m) => { const role = m.bot_id ? "assistant" : "user"; return { role, content: m.text }; }); const messages = [ { role: "system", content: DEFAULT_SYSTEM_CONTENT }, ...threadHistory, userMessage, ]; const modelResponse = await hfClient.chatCompletion ({ model: "Qwen/Qwen2.5-Coder-32B-Instruct", messages, max_tokens: 2000, }); await setStatus("is typing..."); await say( convertMarkdownToSlack(modelResponse.choices[0].message.content), ); } catch (error) { logger.error("Error in userMessage:", error); await say( "I'm sorry, I ran into an error processing your request. Please try again.", ); } }, }); // Register the assistant with the app app.assistant(assistant); ``` -------------------------------- ### Installation Object Structure Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md This is the structure of the `installation` object passed to `storeInstallation` for single workspace installations. ```json { "team": { "id": "T012345678", "name": "example-team-name" }, "enterprise": undefined, "user": { "token": undefined, "scopes": undefined, "id": "U012345678" }, "tokenType": "bot", "isEnterpriseInstall": false, "appId": "A01234567", "authVersion": "v2", "bot": { "scopes": [ "chat:write", ], "token": "xoxb-244493-28*********-********************", "userId": "U001111000", "id": "B01234567" } } ``` -------------------------------- ### Org-wide Installation Object with Team Details Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Shows an installation object for an app installed to an individual workspace within an organization. ```javascript { team: { id: "T0000000001", name: "experimental-sandbox" }, enterprise: { id: "E0000000001", name: "laboratories" }, // ... isEnterpriseInstall: false, // ... } ``` -------------------------------- ### In-Memory Installation Store Implementation Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Implements a basic in-memory installation store with storeInstallation, fetchInstallation, and deleteInstallation handlers. Persistent storage is recommended for production. ```javascript const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, stateSecret: process.env.SLACK_STATE_SECRET, scopes: ["chat:write", "commands"], installationStore: { storeInstallation: async (installation) => { if (installation.team !== undefined) { return await database.set(installation.team.id, installation); } throw new Error("Failed to save installation data to installationStore"); }, fetchInstallation: async (installQuery) => { if (installQuery.teamId !== undefined) { return await database.get(installQuery.teamId); } throw new Error("Failed to fetch installation"); }, deleteInstallation: async (installQuery) => { if (installQuery.teamId !== undefined) { return await database.delete(installQuery.teamId); } throw new Error("Failed to delete installation"); }, }, }); ``` -------------------------------- ### Configure Direct Install Path Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Set `directInstall` to true to skip rendering a webpage before the authorization URL. Customize the install path with `installPath`. ```javascript const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, // ... installerOptions: { // highlight-start directInstall: true, installPath: "/slack/installations", // www.example.com/slack/installations // highlight-end }, }); ``` -------------------------------- ### Start the App with OAuth Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/adding-agent-features.md Run your Bolt application using the provided script to initiate the OAuth flow for installation. ```sh slack run app-oauth.js ``` -------------------------------- ### Run Slack App using npm start Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/getting-started.md Start your Bolt for JavaScript application using the npm start command. This is an alternative to using the Slack CLI for running the app locally. ```sh $ npm run start ... [INFO] bolt-app ⚡️ Bolt app is running! ``` -------------------------------- ### Install Bolt.js Source: https://github.com/slackapi/bolt-js/blob/main/README.md Install the Bolt.js package using npm. This is the first step to setting up your Slack application. ```bash npm install @slack/bolt ``` -------------------------------- ### Start Local Development Server Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/custom-steps-workflow-builder-new/custom-steps-workflow-builder-new.md Run this command in your terminal to start the local development server. You will see debug statements indicating a successful connection when the server is ready. ```sh npm start ``` -------------------------------- ### Custom Installation Store Implementation Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Implements a custom installation store for Bolt apps, handling both org-wide and team-specific installations. ```javascript const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, stateSecret: process.env.SLACK_STATE_SECRET, scopes: ["chat:write", "commands"], // highlight-start installationStore: { storeInstallation: async (installation) => { if ( installation.isEnterpriseInstall && installation.enterprise !== undefined ) { return await database.set(installation.enterprise.id, installation); } if (installation.team !== undefined) { return await database.set(installation.team.id, installation); } throw new Error("Failed to save installation data to installationStore"); }, fetchInstallation: async (installQuery) => { if ( installQuery.isEnterpriseInstall && installQuery.enterpriseId !== undefined ) { return await database.get(installQuery.enterpriseId); } if (installQuery.teamId !== undefined) { return await database.get(installQuery.teamId); } throw new Error("Failed to fetch installation"); }, deleteInstallation: async (installQuery) => { if ( installQuery.isEnterpriseInstall && installQuery.enterpriseId !== undefined ) { return await database.delete(installQuery.enterpriseId); } if (installQuery.teamId !== undefined) { return await database.delete(installQuery.teamId); } throw new Error("Failed to delete installation"); }, }, // highlight-end }); ``` -------------------------------- ### Example Authorization Function for Multiple Workspaces Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authorization.md This example demonstrates how to implement an `authorize` function that fetches credentials from a predefined list based on `teamId` and `enterpriseId`. In a real application, this data would typically come from a secure database. ```javascript const installations = [ { enterpriseId: 'E1234A12AB', teamId: 'T12345', botToken: 'xoxb-123abc', botId: 'B1251', botUserId: 'U12385', }, { teamId: 'T77712', botToken: 'xoxb-102anc', botId: 'B5910', botUserId: 'U1239', }, ]; const authorizeFn = async ({ teamId, enterpriseId }) => { // Fetch team info from database for (const team of installations) { // Check for matching teamId and enterpriseId in the installations array if ((team.teamId === teamId) && (team.enterpriseId === enterpriseId)) { // This is a match. Use these installation credentials. return { // You could also set userToken instead botToken: team.botToken, botId: team.botId, botUserId: team.botUserId }; } } throw new Error('No matching authorizations'); } ``` -------------------------------- ### Install Serverless Offline Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/aws-lambda.md Install the `serverless-offline` module as a development dependency to emulate a deployed Lambda function locally. ```bash npm install --save-dev serverless-offline ``` -------------------------------- ### Org-wide Installation Object Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Represents an app installation to an organization, including enterprise details and installation status. ```javascript { team: undefined, enterprise: { id: "E0000000001", name: "laboratories" }, user: { token: undefined, scopes: undefined, id: "U0000000001" }, tokenType: "bot", isEnterpriseInstall: true, appId: "A0000000001", authVersion: "v2", bot: { scopes: [ "chat:write", ], token: "xoxb-000001-00*********-********************", userId: "U0000000002", id: "B0000000001" } } ``` -------------------------------- ### Starting the App Source: https://github.com/slackapi/bolt-js/blob/main/README.md Start the Bolt app to begin listening for incoming requests from Slack. This should be called after initializing the app. ```APIDOC ## Starting the App ### Description Starts the Bolt application, making it ready to receive and process requests from Slack. ### Method `app.start(port)` ### Parameters #### Path Parameters - **port** (number | string) - Required - The port number or string to listen on. ### Request Example ```javascript (async () => { // Start the app await app.start(process.env.PORT || 3000); app.logger.info('⚡️ Bolt app is running!'); })(); ``` ``` -------------------------------- ### Check Node.js Version Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/random-fact-generator/random-fact-generator.md Verify that Node.js is installed and is a recent LTS version before proceeding with project setup. ```bash node -v ``` -------------------------------- ### Install Dependencies Source: https://github.com/slackapi/bolt-js/blob/main/examples/custom-receiver/README.md Run this script to link to the latest source code for the Bolt framework. ```bash ./link.sh ``` -------------------------------- ### Update Installation Store for V3 Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/migration/migration-v3.md Modify your installation store to handle both single team and organization-wide installations with a unified interface. This replaces the older `storeOrgInstallation` and `fetchOrgInstallation` methods. ```javascript installationStore: { storeInstallation: async (installation) => { // change the line below so it saves to your database return await database.set(installation.team.id, installation); }, fetchInstallation: async (installQuery) => { // change the line below so it fetches from your database return await database.get(installQuery.teamId); }, storeOrgInstallation: async (installation) => { // include this method if you want your app to support org wide installations // change the line below so it saves to your database return await database.set(installation.enterprise.id, installation); }, fetchOrgInstallation: async (installQuery) => { // include this method if you want your app to support org wide installations // change the line below so it fetches from your database return await database.get(installQuery.enterpriseId); }, } ``` ```javascript installationStore: { storeInstallation: async (installation) => { if (installation.isEnterpriseInstall && installation.enterprise !== undefined) { // support for org wide app installation return await database.set(installation.enterprise.id, installation); } if (installation.team !== undefined) { // single team app installation return await database.set(installation.team.id, installation); } throw new Error('Failed saving installation data to installationStore'); }, fetchInstallation: async (installQuery) => { // replace database.get so it fetches from your database if (installQuery.isEnterpriseInstall && installQuery.enterpriseId !== undefined) { // org wide app installation lookup return await database.get(installQuery.enterpriseId); } if (installQuery.teamId !== undefined) { // single team app installation lookup return await database.get(installQuery.teamId); } throw new Error('Failed fetching installation'); }, } ``` -------------------------------- ### Initialize a new project in the terminal Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/creating-an-app.md Set up a new project directory and initialize it with npm. This includes setting the project type to module and installing the Bolt for JavaScript package. ```bash $ mkdir first-bolt-app $ cd first-bolt-app $ npm init $ npm pkg set type=module $ npm install @slack/bolt ``` -------------------------------- ### Initialize App with Custom Installer Options Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Configure OAuth installation settings like authVersion, redirect paths, and custom callbacks when initializing the Bolt App. The state verification logic can be customized using a stateStore object. ```javascript const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, scopes: [ "channels:manage", "channels:read", "chat:write", "groups:read", "incoming-webhook", ], installerOptions: { authVersion: "v2", directInstall: false, installPath: "/slack/install", metadata: "", redirectUriPath: "/slack/oauth_redirect", stateVerification: "true", /** * Example user scopes to request during installation. */ userScopes: ["chat:write"], /** * Example pages to navigate to on certain callbacks. */ callbackOptions: { success: (installation, installUrlOptions, req, res) => { res.send("The installation succeeded!"); }, failure: (error, installUrlOptions, req, res) => { res.send("Something strange happened..."); }, }, /** * Example validation of installation options using a random state and an * expiration time between requests. */ stateStore: { generateStateParam: async (installUrlOptions, now) => { const state = randomStringGenerator(); const value = { options: installUrlOptions, now: now.toJSON() }; await database.set(state, value); return state; }, verifyStateParam: async (now, state) => { const value = await database.get(state); const generated = new Date(value.now); const seconds = Math.floor( (now.getTime() - generated.getTime()) / 1000, ); if (seconds > 600) { throw new Error("The state expired after 10 minutes!"); } return value.options; }, }, }, }); ``` -------------------------------- ### Install Local Development App Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/adding-agent-features.md Install your local development app using the Slack CLI. This command enables local development features. ```sh slack install -E local ``` -------------------------------- ### Deferring Bolt App Initialization Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/deferring-initialization.md Use the `deferInitialization: true` option in the App constructor to defer initialization. You must then manually call `await app.init()` before `await app.start()` within an async function. This pattern is useful when your app requires asynchronous setup steps before it can start listening for requests. ```javascript const { App } = require('@slack/bolt'); // deferInitialization is one of the options you can set in the constructor const app = new App({ token, signingSecret, deferInitialization: true, }); (async () => { try { // Must call init() before start() within an async function await app.init(); // Now safe to call start() await app.start(process.env.PORT || 3000); } catch (e) { app.logger.error(e); process.exit(1); } })() ``` -------------------------------- ### NPM Script Output Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/random-fact-generator/random-fact-generator.md Example console output when the Bolt app is successfully started using the 'npm run dev' command. It confirms the app is running and listening. ```bash > bolt-useless-facts@0.1.0 dev > node --env-file=.env --watch app.js [INFO] bolt-app ⚡️ Bolt app is running! ``` -------------------------------- ### InstallQuery Object Structure Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md The installQuery object is passed to fetchInstallation and deleteInstallation handlers, containing details about the installation. ```javascript { userId: "U012345678", isEnterpriseInstall: false, teamId: "T012345678", enterpriseId: undefined, conversationId: "D02345678" } ``` -------------------------------- ### Test Serverless CLI Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/aws-lambda.md Verify the Serverless Framework CLI installation by displaying the available commands. ```shell serverless help ``` -------------------------------- ### Clone Bolt Project and Install Dependencies Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/getting-started.md Clone a Bolt project starter template from a Git repository and install its Node.js dependencies using npm. This sets up the project locally for development. ```sh $ git clone https://github.com/slack-samples/bolt-js-getting-started-app first-bolt-app $ cd first-bolt-app $ npm install ``` -------------------------------- ### Run the App Source: https://github.com/slackapi/bolt-js/blob/main/examples/custom-receiver/README.md Start the Bolt.js application using the provided npm script. ```bash npm run koa ``` -------------------------------- ### Start App via Node.js Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/creating-an-app.md Run your Bolt application using Node.js. This command starts the server to listen for incoming requests. ```sh node app.js ``` -------------------------------- ### Start Local Server with Serverless Offline Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/aws-lambda.md Run this command in your terminal to start the Serverless Offline plugin, which will emulate your AWS Lambda function and listen for events locally. The `--noPrependStageInUrl` flag prevents the stage name from being prepended to the URL. ```zsh serverless offline --noPrependStageInUrl ``` -------------------------------- ### Org-wide Install Query Object Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md The installQuery object used for fetching or deleting installations, including enterprise and team identifiers. ```javascript { userId: "U0000000001", isEnterpriseInstall: true, teamId: "T0000000001", enterpriseId: "E0000000001", conversationId: "D0000000001" } ``` -------------------------------- ### Check Node.js Version Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/getting-started.md Verify that Node.js is installed and accessible. This command confirms Node.js is set up correctly. ```sh $ node --version ``` -------------------------------- ### Check Git Version Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/getting-started.md Verify that Git is installed and accessible. This command confirms Git is set up correctly. ```sh $ git --version ``` -------------------------------- ### Deploy to Heroku Source: https://github.com/slackapi/bolt-js/blob/main/examples/deploy-heroku/README.md Push your project code to Heroku and scale the web process to start the server. ```zsh # Deploy to Heroku git push heroku main # Start web server on Heroku heroku ps:scale web=1 ``` -------------------------------- ### Setup Environment Variables Source: https://github.com/slackapi/bolt-js/blob/main/examples/custom-receiver/README.md Set these environment variables with your Slack app credentials before running the application. ```bash export SLACK_CLIENT_ID=YOUR_SLACK_CLIENT_ID export SLACK_CLIENT_SECRET=YOUR_SLACK_CLIENT_SECRET export SLACK_SIGNING_SECRET=YOUR_SLACK_SIGNING_SECRET ``` -------------------------------- ### Initialize and Start Bolt App Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/ai-assistant.md Initialize the Bolt app with your Slack API credentials and socket mode enabled. This snippet also includes starting the app and basic error handling. ```javascript // Initialize the Bolt app const app = new App({ token: process.env.SLACK_BOT_TOKEN, appToken: process.env.SLACK_APP_TOKEN, socketMode: true, logLevel: LogLevel.DEBUG, clientOptions: { slackApiUrl: process.env.SLACK_API_URL || 'https://slack.com/api', }, }); // Register the action and event listeners registerListeners(app); // Start the Bolt app (async () => { try { await app.start(); app.logger.info('⚡️ Bolt app is running!'); } catch (error) { app.logger.error('Failed to start the app', error); } })(); ``` -------------------------------- ### Scale Heroku App Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/heroku.md Start a web server instance for your Heroku app by scaling the 'web' process to one instance. ```shell heroku ps:scale web=1 ``` -------------------------------- ### Display Heroku CLI Help Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/heroku.md Verify the Heroku CLI installation by displaying available commands. ```shell heroku help ``` -------------------------------- ### Check Slack CLI Version Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/getting-started.md Verify that the Slack CLI is installed and accessible. This command confirms the CLI is set up correctly. ```sh $ slack version ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/custom-steps-workflow-builder-new/custom-steps-workflow-builder-new.md Change your current directory to the cloned project folder. This is a necessary step before installing dependencies or opening the project in an editor. ```sh cd boltstep ``` -------------------------------- ### Setup Environment Variables Source: https://github.com/slackapi/bolt-js/blob/main/examples/socket-mode/README.md Configure these environment variables with your Slack API credentials. SLACK_BOT_TOKEN and SLACK_APP_TOKEN are essential for Socket Mode. CLIENT_ID, CLIENT_SECRET, and STATE_SECRET are required if you are implementing OAuth. ```bash // can get this from OAuth & Permission page in app configuration export SLACK_BOT_TOKEN=YOUR_SLACK_BOT_TOKEN // can generate the app level token from basic information page in app configuration export SLACK_APP_TOKEN=YOUR_SLACK_APP_TOKEN // if using OAuth, also export the following export CLIENT_ID=YOUR_SLACK_CLIENT_ID export CLIENT_SECRET=YOUR_SLACK_CLIENT_SECRET export STATE_SECRET=YOUR_STATE_SECRET ``` -------------------------------- ### Navigate to the App Directory Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/heroku.md Change into the cloned application's directory to begin preparation. ```shell cd bolt-js-getting-started-app/ ``` -------------------------------- ### Clone a Bolt.js Getting Started App Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/heroku.md Use this command to clone the template Bolt app if you don't have an existing one. ```shell git clone https://github.com/slack-samples/bolt-js-getting-started-app.git ``` -------------------------------- ### Example Database Object for Testing Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md A simple in-memory database object for quick testing purposes, implementing delete, get, and set methods. ```javascript const database = { store: {}, async delete(key) { delete this.store[key]; }, async get(key) { return this.store[key]; }, async set(key, value) { this.store[key] = value; }, }; ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/random-fact-generator/random-fact-generator.md Rename the .env.sample file to .env and paste your Slack bot and app tokens into the respective placeholders. ```txt SLACK_BOT_TOKEN={your-bot-token-xoxb-1234} SLACK_APP_TOKEN={your-app-token-xapp-1234} ``` -------------------------------- ### Create Project Directory Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/random-fact-generator/random-fact-generator.md Create a new directory for your project and navigate into it. Use 'md' for Windows. ```bash mkdir useless-fact-app cd useless-fact-app ``` ```powershell md useless-fact-app ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/code-assistant.md Set up your Slack and Hugging Face API tokens by renaming the .env.sample file to .env and filling in your specific credentials. Ensure all tokens are correctly entered for the application to authenticate properly. ```dotenv SLACK_APP_TOKEN=xapp-1-example-token SLACK_BOT_TOKEN=xoxb-example-token HUGGINGFACE_API_KEY=hf_exampletoken ``` -------------------------------- ### Configure Bolt App with OAuth and FileInstallationStore Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md This snippet shows how to initialize a Bolt App with the necessary OAuth credentials and a `FileInstallationStore` for development and testing. Ensure you replace placeholder environment variables with your actual Slack app credentials. ```javascript const { App } = require("@slack/bolt"); const { FileInstallationStore } = require("@slack/oauth"); const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, stateSecret: process.env.SLACK_STATE_SECRET, scopes: ["channels:history", "chat:write", "commands"], installationStore: new FileInstallationStore(), }); ``` -------------------------------- ### Install Bolt v4 RC Source: https://github.com/slackapi/bolt-js/wiki/Bolt-v3-‐--v4-Migration-Guide Install the release candidate version of @slack/bolt v4.0.0. ```bash npm install @slack/bolt@4.0.0-rc.4 ``` -------------------------------- ### Install Heroku CLI on macOS Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/deployments/heroku.md Install the Heroku Command Line Interface using Homebrew on macOS. ```shell brew install heroku/brew/heroku ``` -------------------------------- ### Initialize InstallProvider for Token Rotation Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/token-rotation.md Instantiate the `InstallProvider` with your Slack app's client ID, client secret, and state secret. This setup is necessary for managing token rotation on a custom schedule. ```javascript const { InstallProvider } = require("@slack/oauth"); const installer = new InstallProvider({ clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, stateSecret: process.env.SLACK_STATE_SECRET, }); ``` -------------------------------- ### Start Bolt-JS App Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/code-assistant.md This code snippet starts the Bolt-JS application and logs a success message or an error if the startup fails. ```javascript // Start the app (async () => { try { await app.start(); app.logger.info("⚡️ Code Assistant app is running!"); } catch (error) { app.logger.error("Failed to start app:", error); } })(); ``` -------------------------------- ### Disabling State Verification for Org-Wide Installations Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/authenticating-oauth.md Disables Bolt's state verification for org-wide installations where the state parameter is not supplied by default. ```javascript const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, clientId: process.env.SLACK_CLIENT_ID, clientSecret: process.env.SLACK_CLIENT_SECRET, scopes: ["chat:write"], installerOptions: { // highlight-next-line stateVerification: false, }, }); ``` -------------------------------- ### Install a new Slack app using Slack CLI Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/creating-an-app.md Create a new 'local' Slack app and select a workspace for development using the Slack CLI. This command utilizes the manifest.json file within the scaffolded project. ```bash $ slack install ``` -------------------------------- ### Install Hugging Face Inference Package Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/code-assistant.md Install the @huggingface/inference npm package to enable interaction with pre-trained models. This is a required dependency for AI-powered features. ```bash npm install @huggingface/inference ``` -------------------------------- ### Initialize Bolt App and Hugging Face Client Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/code-assistant.md Sets up the Bolt application with Slack credentials and initializes the Hugging Face Inference client using environment variables. Ensure SLACK_BOT_TOKEN, SLACK_APP_TOKEN, and HUGGINGFACE_API_KEY are set. ```javascript const { App, LogLevel, Assistant } = require("@slack/bolt"); const { config } = require("dotenv"); const { InferenceClient } = require("@huggingface/inference"); config(); /** Initialization */ const app = new App({ token: process.env.SLACK_BOT_TOKEN, appToken: process.env.SLACK_APP_TOKEN, socketMode: true, logLevel: LogLevel.DEBUG, }); // HuggingFace configuration const hfClient = new InferenceClient(process.env.HUGGINGFACE_API_KEY); ``` -------------------------------- ### Listen for a Shortcut and Open a Modal Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/shortcuts.md Use the `shortcut()` method with a `callback_id` to listen for specific shortcut events. Acknowledge the request with `ack()` and use `client.views.open()` to display a modal. This example opens a simple modal when the 'open_modal' shortcut is invoked. ```javascript app.shortcut('open_modal', async ({ shortcut, ack, client, logger }) => { try { // Acknowledge shortcut request await ack(); // Call the views.open method using one of the built-in WebClients const result = await client.views.open({ trigger_id: shortcut.trigger_id, view: { type: "modal", title: { type: "plain_text", text: "My App" }, close: { type: "plain_text", text: "Close" }, blocks: [ { type: "section", text: { type: "mrkdwn", text: "About the simplest modal you could conceive of :smile:\n\nMaybe or ." } }, { type: "context", elements: [ { type: "mrkdwn", text: "Psssst this modal was designed using " } ] } ] } }); logger.info(result); } catch (error) { logger.error(error); } }); ``` -------------------------------- ### Start ngrok Tunnel Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/adding-agent-features.md Use ngrok to start an HTTP tunnel to your local development server. This is required for enabling the Slack MCP Server in HTTP mode. ```sh ngrok http 3000 ``` -------------------------------- ### Clone Bolt.js Starter Template Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/code-assistant.md Clone the Bolt.js starter template repository to begin your project. This command initializes the project in the current directory. ```bash mkdir code-assistant cd code-assistant # Clone this project onto your machine git clone https://github.com/slack-samples/bolt-js-starter-template.git . ``` -------------------------------- ### Handle Command with Contextual Logic Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/concepts/context.md This example demonstrates how to use the `context.tz_offset` added by a previous middleware to determine the local time and conditionally schedule or post a message. It requires `ack`, `client`, `context`, and `logger` to be available. ```javascript app.command('/request', addTimezoneContext, async ({ command, ack, client, context, logger }) => { // Acknowledge command request await ack(); // Get local hour of request const localHour = (Date.UTC(2020, 3, 31) + context.tz_offset).getHours(); // Request channel ID const requestChannel = 'C12345'; const requestText = ":large_blue_circle: *New request from <@${command.user_id}>*: ${command.text}"; // If request not in between 9AM and 5PM, send request tomorrow if (localHour > 17 || localHour < 9) { // Assume function exists to get local tomorrow 9AM from offset const localTomorrow = getLocalTomorrow(context.tz_offset); try { // Schedule message const result = await client.chat.scheduleMessage({ channel: requestChannel, text: requestText, post_at: localTomorrow }); } catch (error) { logger.error(error); } } else { try { // Post now const result = await client.chat.postMessage({ channel: requestChannel, text: requestText }); } catch (error) { logger.error(error); } } }); ``` -------------------------------- ### Initialize OpenAI Client Source: https://github.com/slackapi/bolt-js/blob/main/docs/english/tutorials/ai-assistant.md Initialize the OpenAI client using your API key. Ensure the OPENAI_API_KEY is set in your environment variables. ```javascript // OpenAI LLM client export const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/slackapi/bolt-js/blob/main/examples/deploy-heroku/README.md Initialize a Git repository and commit the project files. Optionally rename the master branch to main. ```zsh # Initialize Git repository git init # Commit this project git add . git commit -am "Initial commit" # Rename master to main (optional) git branch -m main ``` -------------------------------- ### Initialize Bolt App Source: https://github.com/slackapi/bolt-js/blob/main/README.md Create a new Bolt app instance using the App constructor. Ensure your SLACK_SIGNING_SECRET and SLACK_BOT_TOKEN environment variables are set. ```javascript import { App } from '@slack/bolt'; const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, token: process.env.SLACK_BOT_TOKEN, }); /* Add functionality here */ (async () => { // Start the app await app.start(process.env.PORT || 3000); app.logger.info('⚡️ Bolt app is running!'); })(); ``` -------------------------------- ### App Initialization Source: https://github.com/slackapi/bolt-js/blob/main/README.md Initialize a new Bolt app instance with your Slack app credentials. This is the first step to building your Slack application. ```APIDOC ## App Initialization ### Description Create an app by calling the constructor, which is a top-level export. This initializes the Bolt app with necessary credentials. ### Method `new App(options)` ### Parameters #### Constructor Options - **signingSecret** (string) - Required - Your Slack app's signing secret. - **token** (string) - Required - Your Slack app's bot token. ### Request Example ```javascript import { App } from '@slack/bolt'; const app = new App({ signingSecret: process.env.SLACK_SIGNING_SECRET, token: process.env.SLACK_BOT_TOKEN, }); ``` ```