Building a Slack Bot with MindStudio: A Developer's Guide

Building a Slack Bot with MindStudio: A Developer's Guide

Use Case

Looking to enhance your Slack workspace with a custom-trained AI-powered assistant? This guide walks you through creating a smart Slack bot using a MindStudio AI Worker. With basic JavaScript knowledge and a few simple steps, you can build a bot that responds to questions and interacts with your team members whenever it's mentioned.

Here are some practical ways you could use your MindStudio-powered Slack bot:

  • Create a customer support assistant that answers common questions and troubleshoots issues
  • Build a project management helper that can track tasks and provide status updates
  • Develop an onboarding assistant to help new team members navigate company resources
  • Set up a meeting scheduler that can coordinate times and send reminders
  • Create a knowledge base assistant that can quickly retrieve and summarize documentation

We'll cover the complete process of setting up a scaffold, from setting up your Node.js environment to integrating MindStudio features with Slack's platform. Whether you're building a team assistant, creating an automated support system, or just experimenting with AI interactions, this tutorial provides everything you need to get started.

Ready to make your Slack workspace smarter? Let's begin building your custom AI assistant.

This guide is intended for developers, and requires basic JavaScript/NodeJS knowledge.

Create a fresh Node app

If you don’t already have a project, let’s create a new one. Create an empty directory and initialize a new project:

mkdir MindStudioSlackBot
cd MindStudioSlackBot
npm init

You’ll be prompted with a series of questions to describe your new project (you can accept the defaults by hitting Enter on each prompt if you aren’t picky). After you’re done, you’ll have a new package.json file in your directory.

Create a new file in your directory called .env  with the following empty keys:

SLACK_SIGNING_SECRET=
SLACK_BOT_TOKEN=
SLACK_APP_TOKEN=
MINDSTUDIO_KEY=

Important: Never commit this file to your git repo.

Let’s create the Slack App and MindStudio AI worker now to get these keys.

Create a Slack App

More info on Slack docs

1. Create a new Slack App here from scratch
2. Inside the Basic Information tab, find the Signing Secret, and assign it to SLACK_SIGNING_SECRET in your .env file.
3. Scroll down to App-Level Tokens , click on Generate Token and Scopes . Give it a name and choose all 3 scopes, then click Generate.
4. Assign the Token to the SLACK_APP_TOKEN in your .env file.
5. (Optional) Scroll down to Display Information and add some more details for your Slack bot.
6. Save changes.
7. Go into Socket Mode tab and Enable Socket Mode. For this guide we’ll use the socket mode instead of HTTP. More info here.
8. Go into Event Subscriptions  tab, toggle on Enable Events  and add the following to Subscribe to Bot Events
9. Install the App to your Slack workspace in the Install App tab.
10. Assign the Bot User OAuth Token into your SLACK_BOT_TOKEN variable in the .env file.

Create a MindStudio AI Worker

1. Inside MindStudio, navigate to the API Keys tab. Create a new API key, then assign it to the MINDSTUDIO_KEY variable in the .env file.

Your .env file should now look like this, with actual keys:

SLACK_SIGNING_SECRET=b65daa5c486***************
SLACK_BOT_TOKEN=xoxb-***************
SLACK_APP_TOKEN=xapp-***************
MINDSTUDIO_KEY=sku***************
2. Create a new MindStudio AI Worker that you will use for your assistant, or make a copy of this pre-made Assistant and make any edits you may need later.

The only edit you need to do right now is to add the API Function Name in the Details tab, to make it easier to invoke it via the NPM package in your app. We’ll use Assistant for now.

Back to your Node app

1. Install all required packages:
npm install mindstudio @slack/bolt dotenv

mindstudio is the official MindStudio npm package. More info

@slack/bolt handles the Slack bot behavior. More info

dotenv Allows you to read environment variables from process.env . More info

2. Run the MindStudio sync command:
npx mindstudio sync

This will generate a .mindstudio.json file at the root of your project which contains all the info about your AI Workers. Note that because you entered the MINDSTUDIO_KEY in your .env file already, it automatically detected it and fetched the appropriate workspace data. Check the NPM page for more info.

3. Create a new app.js file at the root of your project, with the following code:
import "dotenv/config";
import Slack from "@slack/bolt";
import { MindStudio, MindStudioError } from "mindstudio";

const { App } = Slack;

// Set up the Slack app with required credentials
const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  appToken: process.env.SLACK_APP_TOKEN,
  socketMode: true,
});

// Define the event listener for when the app is mentioned by a user
app.event("app_mention", async ({ event, say }) => {
  try {
    // Initialize the MindStudio client with the API key
    const client = new MindStudio(process.env.MINDSTUDIO_KEY);

    // Optionally, reply immediately with a "thinking" indicator to show that the message is being processed
    await say({ text: `Just a moment...`, thread_ts: event.ts });

    // Call The Assistants' API workflow that takes a prompt and returns a response
    // Note that "Assistant" is API Function Name we defined in MindStudio
    const { result: mindstudioResult, billingCost } =
      await client.workers.Assistant.api({
        prompt: event.text,
      });

    // Handle empty or undefined responses
    if (!mindstudioResult) {
      await say(`Error generating a response, please try again.`);
      return;
    }

    // Reply to the message
    await say({ text: `${mindstudioResult}`, thread_ts: event.ts });
  } catch (error) {
    if (error instanceof MindStudioError) {
      console.error("Workflow failed:", error.message);
    }
  }
});

(async () => {
  await app.start(process.env.PORT || 3000);
  console.log("⚡️ MindStudio Slack bot is running!");
})();

This code will do the following:

  • Initialize the Slack bot and wait for events
  • Detect if it was tagged in any user message
  • Send the user’s message to the MindStudio AI Worker and have it respond
  • Reply to the user’s message with the Worker’s response inside a thread
4. Make sure your package.json has the correct start command inside of scripts, as well as "type": "module" to make sure it can use the import statements.
{
  "type": "module",
  "name": "mindstudioslackbot",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@slack/bolt": "^4.1.1",
    "dotenv": "^16.4.7",
    "mindstudio": "^0.9.1"
  }
}
5. Run your app with:
npm start

You should now see the ⚡️ MindStudio Slack bot is running! message in the terminal.

Test your MindStudio Slack bot

With the Node app running, invite your new bot into any Slack channel.

Once invited, anyone inside the channel should be able to tag it and ask anything.

Next steps

This is just a basic flow that only takes the user’s message and passes it to the MindStudio Worker.An idea to expand this bot’s capabilities would be to use the whole thread as context (keeping in mind the AI model’s token limitations and cost).

Useful resources:

Sample project repo

Slack Developer Docs

MindStudio Docs (For creating AI workers)

MindStudio NPM Package