/
Slack-ChatGPT
18
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
- Create a Slack bot and configure the events and permissions required for the bot
- Use AirCode's "Get a copy" feature to implement the chat capabilities of the bot
- Integrate the bot with ChatGPT capabilities
Step 1: Create a Slack bot
- Go to the Slack API platform and create a Slack App.
- Configure the permissions of the Slack App and set the corresponding permission scopes (Scopes)
- app_mentions:read
- chat:write
- im:history
- Install the Slack App and obtain the Token for the bot
Step 2: Create an AirCode application
- 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.
- 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.
- 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
- 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.
- Add events to the Slack bot
- app_mention
- message.im
- Configure support for sending messages directly to the Slack bot
Step 4: Test the chatbot
- 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.
- 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
- 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.
- 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
- Discord, GitHub, and other user exchange groups, click https://docs.aircode.io/help/
Further Reading
- Step-by-step tutorials for integrating ChatGPT with iOS Siri, Slack, all source code, free hosting, click https://docs.aircode.io/chatgpt/
- chat.js
1// Import dependencies from AirCode.io, including database and file storage methods 2const aircode = require('aircode'); 3 4// Import axios for making http requests 5const axios = require('axios'); 6 7// Import the OpenAI SDK 8const openai = require("openai"); 9 10// Import the Slack SDK, related documentation https://slack.dev/node-slack-sdk/ 11const { WebClient } = require('@slack/web-api'); 12 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); 17 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); 24 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 }; 35} 36 37// Entry function for the Slack ChatGPT bot 38module.exports = async function(params, context) { 39 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 }; 43 44 // Slack bot will have a client_msg_id for every user message 45 const msgId = params.event.client_msg_id; 46 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'); 50 51 // Search the contents table for an entry with a msgId that matches the current one 52 const contentObj = await contentsTable.where({ msgId }).findOne(); 53 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; 58 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*/,''); 61 62 // Get the information of the person who sent the message 63 const senderId = params.event.user; 64 65 // The message to be returned to the user 66 let replyContent = ''; 67 68 // Determine if there are other types of files (e.g., images), as ChatGPT currently only supports text content 69 if (!params.event.files) { 70 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; 73 74 // Store the message body information in the database for subsequent query history or context support 75 await contentsTable.save({ msgId, senderId, message }); 76 77 // If the OpenAI Key is configured, let ChatGPT reply 78 if (OpenAISecret) { 79 80 // Send the user's specific message to ChatGPT 81 try { 82 const result = await chatGPT(message); 83 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 } 93 94 } else { 95 replyContent = 'Sorry, we currently do not support other types of files.'; 96 } 97 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 }); 105 106 // The entire function call is complete and needs to return 107 return null; 108}; 109 110
- 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