Home > Article > Web Front-end > Create a Node.js-based Slack bot
Slack is Quickly becoming the new industry standard for team communication. exist In fact, it's so popular that when I type slack When I entered Google, as I expected, the first result was the definition of this word. from the dictionary. Slack’s website is a close second!
This is Almost unheard of for the most common word in the English dictionary. Typically, Google's definitions are followed by links to several top dictionaries website.
In its At its most basic, Slack is a messaging system. It allows direct messaging to teams Membership and create channels (private or public) to facilitate real-time Team communication and collaboration. learn more For information about Slack, you can view Slack’s Features.
at this time At one point, you might be wondering where Node.js comes in. As I mentioned, at its most basic level, Slack is a messaging system; However, it can be infinitely expanded custom made. Slack offers a very flexible system to customize your Team integration, including:
at this In this article, I will demonstrate how to create a Slack bot using Node.js Can be added to your team's Slack configuration.
relaxation The Bot's job is to receive events sent by Slack and process them. A large number of events will be sent to your bot, this is where Node.js comes in. we must decide not to Just care about which events to handle and how to handle each individual event.
for For example, some common events that the bot will handle are:
member_joined_channel
member_left_channel
information
at this In this article, I will create a Node.js application and a Slack Bot that can be added to your team project to perform specific actions based on events receive.
First, I need to create a bot on Slack. Two types of bots can be created:
This article will create a custom bot because if you plan to write and publish applications on Slack, the Appbot user would be more appropriate. Given that I want this bot to be private to my team, a custom bot will suffice.
Custom bots can be created here: https://my.slack.com/apps/A0F7YS25R-bots. If you are already logged in to your Slack account, select the Add Configuration button on the left; otherwise, please log in to your Slack account before continuing. If you don't have a Slack account, you can sign up for free.
This will take you to a new page asking you for your bot's username. Enter your username now, making sure to follow Slack's naming guidelines. After choosing a great bot name, press Add Bot Configuration.
After successfully creating the bot, Slack will redirect you to a page that allows further customization of the bot. I'll leave this part to your creative self. The only thing this page requires is an API token
starting with xoxb-. I can copy this token to a safe location for later use, or I can simply keep this page open until we need the token for our Node.js application.
Before we continue writing code, we need two more Slack configurations:
Now that I have configured the Slack Bot, it’s time to move on to the Node.js application. If you already have Node.js installed, you can proceed to the next step. If you don't have Node.js installed yet, I recommend that you first visit the Node.js download page and select the appropriate installer for your system.
For my Slack Bot, I am going to create a new Node.js application by running through the npm init
process. With a command prompt that is set to where you wish your application to be installed, you can run the following commands:
mkdir slackbot cd slackbot npm init
If you are unfamiliar with npm init
, this starts a utility to help you configure your new project. The first thing it asks for is a name. It defaults mine to slackbot
and I'm happy with that. If you want to change your application name, now is your chance; otherwise, press Enter to continue to the next configuration step. The next options are Version and Description. I left both options as default and just pressed Enter to continue selecting both options.
The next requirement is the entry point. The default is index.js
; however, many people prefer to use app.js
. I don't want to get into this debate, and considering that my application doesn't require a dense project structure, I'm going to leave my application with the default index.js
.
After you recover from an argument that may have been as heated as tabs vs. spaces, configuration will continue with a few questions:
For the purposes of this article, I've left all options as their default. Finally, once all options have been configured, a confirmation of the package.json
file is displayed prior to creating it. Press Enter to complete the configuration.
To make it easier to interact with Slack, I will also install the Slack Developer Kit as follows:
npm install @slack/client --save
Are you finally ready to write some code? Of course I am. First, I'll use the sample code from the Slack Developer Kit website that publishes a Slack message using the Real-Time Messaging API (RTM), with a few tweaks.
Given that the entry point I chose is index.js
, it’s time to create this file. The example on the Slack Developer Toolkit website is about 20 lines of code. I'm going to break it down a few lines at a time just to explain what the lines do. But please note that all these lines should be included in your index.js
file.
The code first contains two modules from the Slack developer toolkit:
var RtmClient = require('@slack/client').RtmClient; var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
RtmClient
Once instantiated, becomes a robot object that references the RTM API. CLIENT_EVENTS
are the events that the bot will listen for.
After including these modules, you can instantiate and start the robot:
var rtm = new RtmClient('xoxb-*************************************'); rtm.start();
Be sure to replace the obfuscated API token above with the token you obtained during the Slack Bot creation process.
Calling the start
function on my RtmClient
will initialize the robot's session. This will try to authenticate my bot. When my bot successfully connects to Slack, an event is sent, allowing my application to continue. These events will be displayed immediately.
After instantiating the client, a channel
variable will be created, which will be immediately populated within one of the CLIENT_EVENTS
events.
let channel;The
channel
variable will be used to perform specific actions, such as sending a message to the channel the bot is connected to.
When the RTM session is started (rtm.start();
) and the bot is given a valid API token, a RTM.AUTHENTICATED# will be sent ## information. The next few lines listen for this event:
rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => { for (const c of rtmStartData.channels) { if (c.is_member && c.name ==='jamiestestchannel') { channel = c.id } } console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`); });When the
RTM.AUTHENTICATED event is received, the preceding code executes a
for loop in the Slack team channel list. In my case, I specifically looked for
jamiestestchannel and made sure my bot was a member of that channel. When this condition is met, the channel ID is stored in the channel variable.
${rtmStartData.self.name}) and team name (
${rtmStartData.team.name}) It belongs.
RTM.RTM_CONNECTION_OPENED), which indicates that the bot is fully connected and can start interacting with Slack. The following lines of code create the event listener; upon success, a
Hello! The message will be sent to that channel (in my case, jamiestestchannel).
rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function () { rtm.sendMessage("Hello!", channel); });At this point, I can now run my Node application and watch my bot automatically post a new message to my channel:
node index.jsThe results of running this command (when successful) are two:
RTM.AUTHENTICATED
。RTM.RTM_CONNECTION_OPENED
事件消息时,会发生这种情况。在继续和进一步增强我的应用程序之前,现在是回顾一下我到目前为止所做的工作的好时机:
index.js
文件,该文件使用我的自定义机器人中的 API 令牌 创建 RtmClient
。RTM.AUTHENTICATED
创建了一个事件侦听器,用于查找我的机器人所属的 Slack 频道。RTM.RTM_CONNECTION_OPENED
创建了一个事件侦听器,用于向我的 Slack 频道发送Hello!消息。现在是真正的乐趣开始的时候了。 Slack 提供(我没有数)至少 50 个不同的事件可供我的自定义机器人监听和选择性处理。正如您从 Slack 事件列表中看到的,某些事件是 RTM API(我们正在使用的)自定义的,而其他事件是 Events API 自定义的。在撰写本文时,我的理解是 Node.js SDK 仅支持 RTM。
为了完成我的机器人,我将处理 message
事件;当然,这可能是最复杂的事件之一,因为它支持大量子类型,我稍后将探讨这些子类型。
以下是 Slack 中最基本的 message
事件的示例:
{ "type": "message", "channel": "C2147483705", "user": "U2147483697", "text": "Hello world", "ts": "1355517523.000005" }
在这个 basic object, the three most important things I care about are:
频道
。我希望确保此消息属于我的机器人所属的频道。用户
。这将使我能够直接与用户交互或根据用户身份执行特定操作。text
。这可能是最重要的部分,因为它包含消息的内容。我的机器人只想响应某些类型的消息。有些消息更为复杂。它们可以包含许多子属性,例如:
edited
:一个子对象,描述哪个用户编辑了消息以及消息发生的时间。subtype
:定义多种不同类型之一的字符串,例如channel_join、channel_leave等。
is_starred
:一个布尔值,指示此消息是否已加星标。
pinned_to
:已固定此消息的通道数组。
reactions
:一组反应对象,定义反应是什么(例如捂脸)、反应发生的次数以及对消息做出这种反应的用户数组。
我将扩展之前创建的 index.js
来监听 message
事件。为了减少代码冗余,以下示例将仅包含与 message
事件增强相关的部分代码。
必须做的第一件事是为我将要收听的 RTM_EVENTS
添加一个新模块。我已将其放置在我之前的两个模块下方:
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
处理 message
事件的代码我将放置在文件的底部。为了测试 message
事件是否正常工作,我创建了一个新的事件侦听器,它将 message
对象记录到控制台,如下所示:
rtm.on(RTM_EVENTS.MESSAGE, function(message) { console.log(message); });
我现在可以重新运行我的 Node 应用程序 (node index.js
)。当我在频道中输入消息时,以下内容将记录到我的控制台:
{ type: 'message', channel: 'C6TBHCSA3', user: 'U17JRET09', text: 'hi', ts: '1503519368.000364', source_team: 'T15TBNKNW', team: 'T15TBNKNW' }
到目前为止,一切都很好。我的机器人已成功接收消息。下一个增量步骤是确保消息属于我的机器人所在的频道:
rtm.on(RTM_EVENTS.MESSAGE, function(message) { if (message.channel === channel) console.log(message); });
现在,当我运行我的应用程序时,如果 message
事件适用于我的机器人所属的 channel
,我只会看到调试消息。
我现在将扩展应用程序以向频道发送自定义消息,演示如何在消息中标记用户:
rtm.on(RTM_EVENTS.MESSAGE, function(message) { if (message.channel === channel) rtm.sendMessage("Stop, everybody listen, <@" + message.user + "> has something important to say!", message.channel); });
现在,当任何人在频道中输入消息时,我的机器人都会发送自己的消息,如下所示:“停下来,大家听着,@endyourif 有重要的事情要说!”
好吧,不是很有用。相反,我将通过增强 message
事件侦听器以响应特定命令来完成我的机器人。这将通过执行以下操作来完成:
message
的 text
部分拆分为一个数组。为了轻松检测我的机器人是否被提及,我需要创建一个新变量来存储我的机器人用户 ID。下面是更新的代码部分,我之前在其中设置了 channel
变量。现在,它还将我的机器人的用户 ID 存储在名为 bot
的变量中。
let channel; let bot; rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => { for (const c of rtmStartData.channels) { if (c.is_member && c.name ==='jamiestestchannel') { channel = c.id } } console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`); bot = '<@' + rtmStartData.self.id + '>'; });
通过设置 bot
变量,我通过充实之前创建的 message
事件监听器来完成我的机器人,如下所示:
rtm.on(RTM_EVENTS.MESSAGE, function(message) { if (message.channel === channel) { if (message.text !== null) { var pieces = message.text.split(' '); if (pieces.length > 1) { if (pieces[0] === bot) { var response = '<@' + message.user + '>'; switch (pieces[1].toLowerCase()) { case "jump": response += '"Kris Kross will make you jump jump"'; break; case "help": response += ', currently I support the following commands: jump'; break; default: response += ', sorry I do not understand the command "' + pieces[1] + '". For a list of supported commands, type: ' + bot + ' help'; break; } rtm.sendMessage(response, message.channel); } } } } });
以下代码将数组中的 text
对象的 message
属性基于空格进行拆分。接下来,我确保数组中至少有两个元素,最好是我的机器人和要执行的命令。
当数组中的第一个元素与我的机器人匹配时,我对数组中的第二个元素执行 switch
语句:命令。当前支持的命令有jump 和help。当一条消息发送到看起来像“@jamiestest跳转”的频道时,我的机器人将向原始用户回复一条特殊消息。
如果该命令未被识别,它将落入我的 switch
的默认 case 语句中,并使用如下所示的通用命令进行响应:“@endyourif,抱歉,我不明白命令“hi”。有关受支持命令的列表,请键入:@jamiestest help"。
此时 point, my bot is complete! If you are interested in further enhancing your bot, here's a list of ideas:
team_join
事件来处理新团队成员的加入。当新团队成员加入时,最好向他们发送各种入职信息和/或文件,欢迎他们加入您的团队。The above is the detailed content of Create a Node.js-based Slack bot. For more information, please follow other related articles on the PHP Chinese website!