Table of contents

Slack integration has become an essential part of modern workflows, allowing seamless communication and collaboration within teams. Leveraging Slack’s API Events and Web API opens up a myriad of possibilities for customizing and automating interactions. This comprehensive guide will walk you through the process of integrating Slack into your applications, harnessing the power of API Events and Web API to enhance productivity and efficiency.

Step 1: Log in to your Slack account

  • Now, In another tab, type Slack API and click on the “Slack API”
  • On the top right, click on Your App, then create your app.
  • Give your app a good name and select the workspace (You must have already created)

Click on Create App.

  • In the Basic Information, scroll down, and in App Credential Copy, App ID
  • Now, click on OAuth & Permission
  • As highlighted in the picture below, add two scope
  • Now scroll up and install this created Bot app to the workspace as shown in the picture below
  • It will ask permission, click on allow
  • Once you install it successfully, it will generate one OAuth Token copy that
  • Now, paste App-Id and OAuth Token in the Lucifer-AI as shown in the below image
  • You can see, that I’ve added App-Id and Auth-Token and have stored them in the database.
  • Now inside the Event Subscription, add the following URL inside the Request URL “https://b19c-125-20-216-178.ngrok-free.app/chatbot/dashboard/slack-botintegration/webhook”
    this above URL is generated on ngrok and my

Here is the code, take a look at it.

import { NextRequest, NextResponse } from "next/server";
const { WebClient, LogLevel } = require("@slack/web-api");
import { ObjectId } from "mongodb";
import {
  encodeChat,
  encode,
  decode,
  isWithinTokenLimit,
} from 'gpt-tokenizer'
import moment from 'moment';


export async function POST(req: NextRequest) {
  try {

    let retryNum = req.headers.get('X-Slack-Retry-Num');
    //if retryNum is available then return the response with status 200
    if (retryNum) {
      return new NextResponse('', { status: 200 });
    }
    //read the incomming parameter from webhook
    let resData: any = await req.json();
    // return the challenge on first time verification
    if (resData.challenge) {
      return new NextResponse(JSON.stringify({ challenge: resData.challenge }), { status: 200 });
    }
    else {
      if (resData.event.type === 'app_mention') {

        // setImmediate(async () => {
        await writeInDataBase(resData);
        // });

        return new NextResponse('', { status: 200 });
      }
      else {
        //handle else part here.
      }
    }

  }
  catch (error: any) {
    console.log('error', error);
  }
}

// Asynchronous function to write data into the database
async function writeInDataBase(data: any) {

  // Define the token limit for different models
  const tokenLimit = [
    {
      model: "gpt-3.5-turbo",
      tokens: 15385,
    },
    {
      model: "gpt-4",
      tokens: 8000
    }
  ]

  let step = 1;

  try {
    // Extract the app ID and channel ID from the data
    const appId = data.api_app_id;
    const channelId = data.event.channel;

    // Connect to the database
    const db = (await clientPromise!)?.db();
    let slackCollection = db.collection('slack-app-details');

    // Find the app details in the database
    let appDetails: SlackAppData = await slackCollection.findOne({
      appId: appId,
    });

    // If app details are found
    if (appDetails) {
      // Extract the auth token, chat bot ID, and user ID from the app details
      const authOToken = appDetails.authOToken;
      const chatBotId = appDetails.chatBotId;
      const message = data.event.text.replace(/<@.*?>\s*\n?/, "");
      const userID = appDetails.userId;

      // Create a new Slack client with the auth token
      const client = new WebClient(authOToken, {
        // LogLevel can be imported and used to make debugging simpler
        logLevel: LogLevel.DEBUG,
      });

      // If the message is empty, return a message
      if (message.length === 0) {
        await client.chat.postMessage({
          channel: channelId,
          text: "I guess you sent me an empty message.",
          threadId: data.event.ts,
        });

        return new NextResponse('', { status: 200 });
      }
      else {
        // Send a POST request to the OpenAI API
        const responseOpenAI: any = await fetch(
          "https://api.openai.com/v1/chat/completions",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_KEY}`,
            },
            body: JSON.stringify({
              model: userChatBotModel.model,
              temperature: userChatBotModel.temperature,
              top_p: 1,
              messages: [
                {
                  role: "system",
                  content: `Use the following pieces of context to answer the users question.
                  If you don't know the answer, just say that you don't know, don't try to make up an answer.
                  ----------------
                  context:
                  ${similaritySearchResults}
                  
                  Answer user query and include images write respect to each line if available`,
                },
                // ...messages,
                {
                  role: "user",
                  content: `Answer user query and include images in response if available in the given context 
                
                            query: ${message} `,
                },
              ],
            }),
          }
        );

        // Parse the response from OpenAI
        const openaiBody = JSON.parse(await responseOpenAI.text());

        // If the response from OpenAI contains content, post it to the Slack channel
        if (openaiBody.choices[0].message.content) {
          await client.chat.postMessage({
            channel: channelId,
            text: openaiBody.choices[0].message.content,
            thread_ts: data.event.ts,
          });
          return new NextResponse('', { status: 200 });

        }
        else {

        }
      }
    }
  }
  catch (error: any) {
    // If an error occurs with the OpenAI or Slack API, log the error
    console.log('error', error);
  }

}
  • Once the URL is verified you are now ready to chat with your Bot through Slack
  • Now subscribe to Bot Event, “app_mention” and then click on save, as shown in the picture

Step 2: Go back to your Slack and you will see your app on the left side

  • Now, add your app to the channel you created

Step 3: Ask your bot a question, and it will respond based on logic.

Conclusion

In conclusion, the integration of Slack into applications through the use of API Events and Web API is a powerful tool for enhancing team communication and collaboration. It allows for a high degree of customization and automation, enabling teams to tailor their workflows to their specific needs. This guide has provided a comprehensive overview of how to leverage these capabilities to improve productivity and efficiency. As technology continues to evolve, the potential for further integration and automation only increases, making it an exciting area for future exploration and development.


Open AI
Rudresh Sisode
Rudresh Sisode

Software Engineer

Launch your MVP in 3 months!
arrow curve animation Help me succeed img
Hire Dedicated Developers or Team
arrow curve animation Help me succeed img
Flexible Pricing
arrow curve animation Help me succeed img
Tech Question's?
arrow curve animation
creole stuidos round ring waving Hand
cta

Book a call with our experts

Discussing a project or an idea with us is easy.

client-review
client-review
client-review
client-review
client-review
client-review

tech-smiley Love we get from the world

white heart