Get a copy
Build a Slack ChatGPT Bot with JavaScript, including full source code, free hosting, and step-by-step tutorial.
  • readme.md

    Build a Slack ChatGPT Bot with JavaScript, including full source code, free hosting, and step-by-step tutorial.

    This article helps you quickly implement a Slack chatbot and integrate ChatGPT capabilities into it. You can ask it questions directly or mention it in a group chat to get ChatGPT's answers. (The following are screenshots of the effect)

    What you will learn from this article

    1. Create a Slack bot and configure the events and permissions required for the bot
    2. Use AirCode's "Get a copy" feature to implement the chat capabilities of the bot
    3. Integrate the bot with ChatGPT capabilities

    Step 1: Create a Slack bot

    1. Go to the Slack API platform and create a Slack App.

    1. Configure the permissions of the Slack App and set the corresponding permission scopes (Scopes)
    • app_mentions:read
    • chat:write
    • im:history

    1. Install the Slack App and obtain the Token for the bot

    Step 2: Create an AirCode application

    1. Quickly generate your own AirCode Node.js application using the "Get a copy" button in the upper right corner of this page or the Slack ChatGPT Bot source code link. Note: Do not directly copy the code. If you paste the code directly, you need to manually install NPM dependencies. If you haven't logged in to AirCode, you need to log in first.

    1. Paste the bot token obtained earlier from the Slack API platform into the environment variables (Environments) of the newly created AirCode application. Fill in the Bot User OAuth Token value in SlackBotToken.

    1. After setting the environment variables (Environments), click the "Deploy" button at the top of the page to deploy the entire application and make all configurations effective.

    Step 3: Configure Slack Bot events

    1. After the AirCode application is deployed successfully, select the chat.js file to call, and you can see the calling URL of the current service. Copy it and paste it into the Request URL of the corresponding App event in the Slack API platform.

    1. Add events to the Slack bot
    • app_mention
    • message.im

    1. Configure support for sending messages directly to the Slack bot

    Step 4: Test the chatbot

    1. You can chat privately with the bot in the chat window, or add the bot to a group and chat by mentioning the bot. At this time, the bot can chat. Since the ChatGPT capability has not been configured yet, the bot will directly return your message, which means the bot has been configured successfully.

    1. You can view the complete request data in AirCode and use the "Mock by online requests" feature to debug the code directly with online data.

    Step 5: Integrate ChatGPT capabilities

    1. Go to OpenAI's console, click "Create new secret key" to generate and copy this newly generated key, and paste it into the environment variables (Environments) of the newly created AirCode application. Paste it into the value of OpenAISecret. If you don't have an OpenAI account, you can search the web for ways to get one and prepare in advance.

    1. After clicking Deploy again to deploy the service and testing, ChatGPT's reply will be supported. Currently, ChatGPT's service is relatively slow, especially when the model version is higher and the question is more complex, the longer it takes for ChatGPT's service to return.

    Problem Feedback

    Further Reading

  • chat.js
    1// Import dependencies from AirCode.io, including database and file storage methods
    2const aircode = require('aircode');
    4// Import axios for making http requests
    5const axios = require('axios');
    7// Import the OpenAI SDK
    8const openai = require("openai");
    10// Import the Slack SDK, related documentation https://slack.dev/node-slack-sdk/
    11const { WebClient } = require('@slack/web-api');
    13// Get the Slack bot Token from environment variables
    14const slackBotToken = process.env.SlackBotToken;
    15if (!slackBotToken) return { error: 'Please configure the Slack bot Token according to the tutorial.' };
    16const slackClient = new WebClient(slackBotToken);
    18// Get the OpenAI Secret from environment variables
    19const OpenAISecret = process.env.OpenAISecret;
    20let chatGPT = null;
    21if (OpenAISecret) {
    22  const configuration = new openai.Configuration({ apiKey: OpenAISecret });
    23  const client = new openai.OpenAIApi(configuration);
    25  // Method to chat with ChatGTP, pass in a string
    26  chatGPT = async (content) => {
    27    return await client.createChatCompletion({
    28      // Use the latest 3.5 model currently available from OpenAI, if GPT4 is released later, modify this parameter
    29      // OpenAI models parameter list https://platform.openai.com/docs/models
    30      model: 'gpt-3.5-turbo',
    31      // Set the role of ChatGPT as an assistant
    32      messages: [{ role: 'assistant', content }],
    33    });
    34  };
    37// Entry function for the Slack ChatGPT bot
    38module.exports = async function(params, context) {
    40  // All parameters for calling the current function can be obtained directly from params
    41  // For Slack event request validation, it is required to return directly when there is a challenge parameter
    42  if (params.challenge) return { challenge: params.challenge };
    44  // Slack bot will have a client_msg_id for every user message
    45  const msgId = params.event.client_msg_id;
    47  // You can easily write data to the database using the database
    48  // Instantiate a table called contents
    49  const contentsTable = aircode.db.table('contents');
    51  // Search the contents table for an entry with a msgId that matches the current one
    52  const contentObj = await contentsTable.where({ msgId }).findOne();
    54  // If contentObj has a value, it means this event has occurred before
    55  // Since the response time of ChatGPT is relatively long, this situation may be Slack retrying, return directly to prevent repeated calls
    56  // This does not take effect when the current environment is in DEBUG mode, which is convenient for debugging
    57  if (contentObj && context.trigger !== 'DEBUG') return;
    59  // Get the content of the message sent by the user to the bot, remove the at character part
    60  const message = params.event.text.replace(/<@.*?>\s*/,'');
    62  // Get the information of the person who sent the message
    63  const senderId = params.event.user;
    65  // The message to be returned to the user
    66  let replyContent = '';
    68  // Determine if there are other types of files (e.g., images), as ChatGPT currently only supports text content
    69  if (!params.event.files) {
    71    // By default, the content sent by the user is returned to the user, which is just a bot that directly returns the conversation
    72    replyContent = message;    
    74    // Store the message body information in the database for subsequent query history or context support
    75    await contentsTable.save({ msgId, senderId, message });
    77    // If the OpenAI Key is configured, let ChatGPT reply
    78    if (OpenAISecret) {
    80      // Send the user's specific message to ChatGPT
    81			try {
    82	      const result = await chatGPT(message);	
    84	      // Send the ChatGPT reply obtained to the user
    85	      replyContent = `${result.data.choices[0].message.content.trim()}`;    
    86			} catch (err) {
    87				err = err.toJSON();
    88				if (err.status === 429) return {
    89					error: 'You encounter a OpenAI ChatGPT 429 situation, need to go to OpenAI and pay for more quotas. ChatGPT Plus is only for web-based payments, the API is another channel that requires payment per token.' };
    90				return err.message;
    91			}
    92    }
    94  } else {
    95    replyContent = 'Sorry, we currently do not support other types of files.';
    96  }
    98  // Send the processed message to the user via the Slack bot
    99  await slackClient.chat.postMessage({
    100    channel: params.event.channel,
    101    text: `<@${senderId}> ${replyContent}`,
    102    thread_ts: params.event.ts,
    103    reply_broadcast: true,
    104  });
    106  // The entire function call is complete and needs to return
    107  return null;
  • Runtime
    • Node.js versionnode/v16
    • Function execution timeout60 s
  • Dependencies
    • @slack/web-api6.8.1
    • aircode0.3.0
    • axios1.3.5
    • openai3.2.1
  • Environments
    • SlackBotToken
    • OpenAISecret