slack 使用说明_我如何使用Node和Botkit构建HR Slack Bot
slack 使用說(shuō)明
為什么要?jiǎng)?chuàng)建Slack Bot? (Why create a Slack Bot ?)
I am an HR professional. More specifically I am a Human Resources Information System (HRIS) Consultant. I work with Application Tracking Systems, Learning Management Systems, and Core HR. But I have never had the opportunity to work with an HR Bot. Which may be the Future of HR.
我是人力資源專(zhuān)業(yè)人員。 更具體地說(shuō),我是人力資源信息系統(tǒng)(HRIS)顧問(wèn)。 我使用應(yīng)用程序跟蹤系統(tǒng),學(xué)習(xí)管理系統(tǒng)和核心HR。 但是我從來(lái)沒(méi)有機(jī)會(huì)與人力資源Bot合作。 這可能是人力資源的未來(lái)。
I read a lot about bots on Slack and Messenger, and used some of them in my daily life — Product Hunt, GitHub and Trello. But for HR purposes, I have never had the opportunity to work with a tool tailored for my needs.
我閱讀了很多有關(guān)Slack和Messenger的機(jī)器人的信息,并在我的日常生活中使用了其中的一些機(jī)器人-Product Hunt,GitHub和Trello。 但是出于人力資源的目的,我從來(lái)沒(méi)有機(jī)會(huì)使用針對(duì)我的需求量身定制的工具。
That’s why I decided to work on my own bot.
這就是為什么我決定使用自己的機(jī)器人的原因。
我的目標(biāo) (My Goals)
My bot should be able to manage all the needs a small company could have on Slack:
我的機(jī)器人應(yīng)該能夠管理小公司對(duì)Slack的所有需求:
- Onboarding 入職
- Putting people in touch 與人們保持聯(lián)系
- Reminders 提醒事項(xiàng)
- Announcements 公告內(nèi)容
- Birthdays /Anniversary 生日/周年紀(jì)念
- And many more 還有很多
復(fù)習(xí)基礎(chǔ) (Reviewing the basics)
For this program, I’ll use:
對(duì)于此程序,我將使用:
- Botkit Botkit
- Node JS 節(jié)點(diǎn)JS
- Express Server Express服務(wù)器
- MongoDB MongoDB
- Slack API & of course Slack API&當(dāng)然
Botkit is:
Botkit是:
One easy way to build bot users, especially if you already work with Node.js, is Howdy’s Botkit. Botkit is a framework that takes care of most these API gymnastics, so you can focus on your bot’s behavior.
建立機(jī)器人用戶(hù)的一種簡(jiǎn)單方法是Howdy的Botkit ,尤其是如果您已經(jīng)使用Node.js的話 。 Botkit是負(fù)責(zé)處理大多數(shù)這些API體操的框架,因此您可以專(zhuān)注于機(jī)器人的行為。
Exactly what I was looking for :-)
正是我在找什么:-)
Botkit provides a boilerplate for Slack. But I have chosen to start from scratch to have a better understanding of my bot. However, it’s a good idea to train yourself with a bot created on Glitch.
Botkit提供了Slack的樣板。 但是我選擇從頭開(kāi)始,以更好地了解我的機(jī)器人。 但是,最好使用在Glitch上創(chuàng)建的機(jī)器人來(lái)訓(xùn)練自己。
Slack機(jī)器人如何工作? (How do Slack bots work?)
I am not an expert. I have read again and again Slack and Botkit’s official documentation. I’m still not sure I understood everything. Here is my understanding of a Slack bot’s behavior:
我不是專(zhuān)家。 我一遍又一遍地閱讀了Slack和Botkit的官方文檔。 我仍然不確定我是否了解一切。 這是我對(duì)Slack機(jī)器人行為的理解:
Every App on Slack has a “scope” which is a perimeter on which an app can read or perform actions. A bot is part of an application created and installed on Slack.
Slack上的每個(gè)應(yīng)用程序都有一個(gè)“范圍”,范圍是應(yīng)用程序可以讀取或執(zhí)行操作的范圍。 機(jī)器人是Slack上創(chuàng)建并安裝的應(yīng)用程序的一部分。
Therefore, when you install an app on Slack, you give access to some information and permissions to it. For your bot, you want it to be, at least, able to send and reply to messages of other users.
因此,在Slack上安裝應(yīng)用程序時(shí),您可以訪問(wèn)某些信息和權(quán)限。 對(duì)于您的漫游器,您至少希望它能夠發(fā)送和回復(fù)其他用戶(hù)的消息。
There are then two cases:
然后有兩種情況:
You want your bot to react to events happening directly in Slack
您希望您的機(jī)器人對(duì)直接在Slack中發(fā)生的事件做出React
You want your bot to react to events happening on your server
您希望機(jī)器人對(duì)服務(wù)器上發(fā)生的事件做出React
We will view both of them in this post!
我們將在這篇文章中同時(shí)查看它們!
入門(mén) (Getting Started)
Before anything else, you will need a server. In my case, Express.
首先,您需要一臺(tái)服務(wù)器。 就我而言,快遞。
Below you’ll find my server.js file:
在下面,您可以找到我的server.js文件:
var express = require('express'); var app = express(); var http = require('http').Server(app); var dotenv = require('dotenv');// configuration =========================================== //load environment variables, dotenv.load();// public folder for images, css,... app.use(express.static(__dirname + '/public'))//parsing app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({extended: true })); //for parsing url encoded// view engine ejs app.set('view engine', 'ejs');// routes require('./routes/routes')(app);//botkit require('./controllers/botkit')//START =================================================== http.listen(app.get('port'), function() {console.log('listening on port ' + app.get('port')); });This port must be public and accessible, not just on a localhost.
此端口必須是公共的并且可以訪問(wèn),而不僅僅是在本地主機(jī)上。
For the moment, this server is a blank page, showing and processing nothing.
目前,該服務(wù)器是空白頁(yè),什么也沒(méi)有顯示和處理。
You’ll then need a Slack App: just follow this link to create one.
然后,您將需要一個(gè)Slack應(yīng)用程序:只需點(diǎn)擊此鏈接即可創(chuàng)建一個(gè)。
Then, you’ll have to configure your controller. The controller is the brain of your bot. It contains every skill and configuration. Below is my botkit.js file. It has almost the same content found in Botkit’s Starter kit available here: https://github.com/howdyai/botkit-starter-slack
然后,您必須配置控制器。 控制器是您的機(jī)器人的大腦。 它包含所有技能和配置。 以下是我的botkit.js文件。 它具有與Botkit入門(mén)工具包中可用內(nèi)容幾乎相同的內(nèi)容: https : //github.com/howdyai/botkit-starter-slack
var mongoUri = 'mongodb://localhost:27017/nameofyourDB' var database = require('../config/database')({mongoUri: mongoUri }) var request = require('request')if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.PORT) {console.log('Error: Specify SLACK_ID SLACK_SECRET and PORT in environment');process.exit(1); }var controller = Botkit.slackbot({storage: database,clientVerificationToken: process.env.SLACK_TOKEN })exports.controller = controller//CONNECTION FUNCTIONS=====================================================exports.connect = function(team_config) {var bot = controller.spawn(team_config);controller.trigger('create_bot', [bot, team_config]);}// just a simple way to make sure we don't// connect to the RTM twice for the same team var _bots = {};function trackBot(bot) {_bots[bot.config.token] = bot; }controller.on('create_bot', function(bot, team) {if (_bots[bot.config.token]) {// already online! do nothing.console.log("already online! do nothing.")} else {bot.startRTM(function(err) {if (!err) {trackBot(bot);console.log("RTM ok")controller.saveTeam(team, function(err, id) {if (err) {console.log("Error saving team")} else {console.log("Team " + team.name + " saved")}})} else {console.log("RTM failed")}bot.startPrivateConversation({user: team.createdBy}, function(err, convo) {if (err) {console.log(err);} else {convo.say('I am a bot that has just joined your team');convo.say('You must now /invite me to a channel so that I can be of use!');}});});} });//REACTIONS TO EVENTS========================================================== // Handle events related to the websocket connection to Slackcontroller.on('rtm_open', function(bot) {console.log('** The RTM api just connected!') });controller.on('rtm_close', function(bot) {console.log('** The RTM api just closed');// you may want to attempt to re-open });解鎖第一種情況:對(duì)Slack上發(fā)生的事件做出React (Unlocking the first case: react to the events happening on Slack)
When you give the right permissions to your app, every time a message is sent on a channel, Slacks sends a request to your server with some information — the channel ID, the user, the timestamp and most importantly, the content of the message.
當(dāng)您為應(yīng)用程序授予正確的權(quán)限時(shí),每次在通道上發(fā)送消息時(shí),Slacks都會(huì)向服務(wù)器發(fā)送請(qǐng)求,其中包含一些信息-通道ID,用戶(hù),時(shí)間戳,最重要的是消息的內(nèi)容。
If we want our bot to react to a simple message like “Hi”, we have to give Slack an address to send the information to.
如果我們希望我們的機(jī)器人對(duì)諸如“ Hi”這樣的簡(jiǎn)單消息做出React,我們必須給Slack一個(gè)地址來(lái)發(fā)送信息。
In a routes.js file write:
在routes.js文件中編寫(xiě):
var Request = require('request') var slack = require('../controllers/botkit') module.exports = function(app) {app.post('/slack/receive', function(req,res){ //respond to Slack that the webhook has been received.res.status(200); // Now, pass the webhook into be processedslack.controller.handleWebhookPayload(req, res)}) }We now have a webhook : http://your-ip-or-domain:port/slack/receive
現(xiàn)在,我們有了一個(gè)Webhook: http:// your-ip-or-domain:port / slack / receive
Once Slack is informed of this route via the Event Subscriptions page of your Slack App, it will be able to send it JSON. You will be able to receive it thanks to the parsing part of the server.js file above.
一旦通過(guò)Slack應(yīng)用程序的“事件訂閱”頁(yè)面將此路由通知給Slack,它將能夠向其發(fā)送JSON。 由于上面的server.js文件的解析部分,您將能夠收到它。
Here is a (simple) schema to explain the process behind it:
這是一個(gè)(簡(jiǎn)單的)模式來(lái)說(shuō)明其背后的過(guò)程:
1- SLACK ? Here is a JSON file with the latest event on your Slack Channel ?
1- SLACK?這是Slack頻道上具有最新事件的JSON文件?
2- SERVER ? Okay well received, I send it to Botkit?
2-服務(wù)器?很好,我將其發(fā)送給Botkit?
3- BOTKIT ?Here is a temporary answer, wait a second?
3- BOTKIT?這是暫時(shí)的答案,請(qǐng)稍等?
4- BOTKIT ? Yeah! I hear a keyword, here is a JSON object with the action to perform ?
4- BOTKIT?是的! 我聽(tīng)到一個(gè)關(guān)鍵字,這是一個(gè)JSON對(duì)象,具有要執(zhí)行的操作?
If we want our bot to react every time it hears “Hello”, we can simply add this .hears() function to our controller:
如果我們希望我們的機(jī)器人在每次聽(tīng)到“ Hello”時(shí)做出React,我們可以簡(jiǎn)單地將此.hears()函數(shù)添加到我們的控制器中:
controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', function(bot, message) { controller.storage.users.get(message.user, function(err, user) {if (user && user.name) {bot.reply(message, 'Hello ' + user.name + '!!');} else {bot.reply(message, 'Hello.');}}); });Notice the storage.users.get() part in this snippet. Botkit is compatible with almost all the database systems available on the market. I have decided to use MongoDB because it was on my learning list for a long time. Plus the documentation with Botkit is detailed.
注意此片段中的storage.users.get()部分。 Botkit與市場(chǎng)上幾乎所有可用的數(shù)據(jù)庫(kù)系統(tǒng)兼容。 我決定使用MongoDB,因?yàn)樗谖业膶W(xué)習(xí)清單上已經(jīng)很長(zhǎng)時(shí)間了。 此外,還詳細(xì)介紹了Botkit的文檔。
Now, we have to let our imagination do the work and find some fun features to create.
現(xiàn)在,我們必須讓我們的想象力完成工作,并找到一些有趣的功能來(lái)創(chuàng)建。
第二種情況:與您的機(jī)器人進(jìn)行對(duì)話 (Second Case: initiate a conversation with your bot)
For this feature, I wanted my bot to react to events which were not initiated on Slack. For example, do a daily routine. If it’s someone’s anniversary in the company, send them a survey asking their feelings about their first months/weeks.
對(duì)于此功能,我希望我的機(jī)器人對(duì)未在Slack上啟動(dòng)的事件做出React。 例如,做一個(gè)日常工作。 如果是公司的周年紀(jì)念日,請(qǐng)向他們發(fā)送一份調(diào)查表,詢(xún)問(wèn)他們對(duì)頭幾個(gè)月/幾周的感覺(jué)。
I have decided to use node-cron: https://github.com/kelektiv/node-cron to manage the daily check.
我決定使用node-cron: https : //github.com/kelektiv/node-cron管理日常檢查。
Here is below a cronjob firing every weekday at 9:00 am. Thanks to the Date() method, the bot gets today’s date and can compare it to the “joinedDate” of the user.
以下是每個(gè)工作日上午9:00觸發(fā)的cronjob。 借助Date()方法,該機(jī)器人可以獲取今天的日期并將其與用戶(hù)的“ joinedDate”進(jìn)行比較。
To get only the right users and avoid a forEach loop, we can use a query on our Database:
為了只獲取合適的用戶(hù)并避免forEach循環(huán),我們可以對(duì)數(shù)據(jù)庫(kù)使用查詢(xún):
var dailyCheck = new CronJob('00 00 9 * * 1-5', function() {/** Runs every weekday (Monday through Friday)* at 09:00:00 AM. It does not run on Saturday* or Sunday.*/console.log(`DailyCheck triggered ${new Date()}`)//Gets today's datelet d = new Date()d.setUTCHours(0, 0, 0, 0)let threeMonthsAgo = new Date()threeMonthsAgo.setUTCMonth(d.getUTCMonth() - 3)threeMonthsAgo.setUTCHours(0, 0, 0, 0)let sevenDaysAgo = new Date()sevenDaysAgo.setUTCDate(d.getUTCDate() - 7)sevenDaysAgo.setUTCHours(0, 0, 0, 0)controller.storage.users.find({"joinedDate": {"$eq": +sevenDaysAgo}}, function(err, user) {user.forEach(function(member) {console.log(`Message was sent to ${member.name}(${member.id})`)bot.startPrivateConversation({user: member.id}, Conversations.sendSurvey7)})})}, function() {/* This function is executed when the job stops */}, true,/* Start the job right now */timeZone = 'Europe/Paris' /* Time zone of this job. */ )And… Tada!
還有……多田!
結(jié)論 (Conclusion)
After more than a year of being a camper and learning to code, I am really happy to be able to start and finish a project like this one. I now have a bot working and performing almost all the actions I had in mind at the design phase. And I still have a lot of ideas!
在成為一名露營(yíng)者并學(xué)習(xí)編碼超過(guò)一年之后,我非常高興能夠啟動(dòng)和完成這樣的項(xiàng)目。 現(xiàn)在,我有一個(gè)機(jī)器人正在工作,并執(zhí)行我在設(shè)計(jì)階段想到的幾乎所有動(dòng)作。 而且我還有很多想法!
I am still working on this bot. The GitHub repository is available here: https://github.com/alexandrobin/hrbot. Some of the commits are in French, but the codebase is commented in English. :-)
我仍在研究這個(gè)機(jī)器人。 GitHub存儲(chǔ)庫(kù)可在此處找到: https : //github.com/alexandrobin/hrbot 。 一些提交使用法語(yǔ),但是代碼庫(kù)用英語(yǔ)注釋。 :-)
Besides, it’s quite easy to deploy it on Heroku with a Mongolab database if you don’t have a server!
此外,如果沒(méi)有服務(wù)器,使用Mongolab數(shù)據(jù)庫(kù)在Heroku上部署它也很容易!
If you have some suggestions or are interested by this article and project, feel free to leave a comment ! I would be happy to discuss with you.
如果您有任何建議或?qū)Ρ疚暮晚?xiàng)目感興趣,請(qǐng)隨時(shí)發(fā)表評(píng)論! 我很樂(lè)意與您討論。
翻譯自: https://www.freecodecamp.org/news/how-i-built-an-hr-slack-bot-with-node-and-botkit-6b23b81531bb/
slack 使用說(shuō)明
總結(jié)
以上是生活随笔為你收集整理的slack 使用说明_我如何使用Node和Botkit构建HR Slack Bot的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 电子设计速成_Web设计速成课程:从一个
- 下一篇: 由衷的信来激励有抱负的开发人员