slack 使用说明_我如何使用Node和Botkit构建HR Slack Bot

slack 使用说明

为什么要创建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.

我是人力资源专业人员。 更具体地说,我是人力资源信息系统(HRIS)顾问。 我使用应用程序跟踪系统,学习管理系统和核心HR。 但是我从来没有机会与人力资源Bot合作。 这可能是人力资源的未来。

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.

我阅读了很多有关Slack和Messenger的机器人的信息,并在我的日常生活中使用了其中的一些机器人-Product Hunt,GitHub和Trello。 但是出于人力资源的目的,我从来没有机会使用针对我的需求量身定制的工具。

That’s why I decided to work on my own bot.

这就是为什么我决定使用自己的机器人的原因。

我的目标 (My Goals)

My bot should be able to manage all the needs a small company could have on Slack:

我的机器人应该能够管理小公司对Slack的所有需求:

  • Onboarding

    入职
  • Putting people in touch

    与人们保持联系
  • Reminders

    提醒事项
  • Announcements

    公告内容
  • Birthdays /Anniversary

    生日/周年纪念
  • And many more

    还有很多

复习基础 (Reviewing the basics)

For this program, I’ll use:

对于此程序,我将使用:

  • Botkit

    Botkit
  • Node JS

    节点JS
  • Express Server

    Express服务器
  • MongoDB

    MongoDB
  • Slack API & of course

    Slack API&当然

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.

建立机器人用户的一种简单方法是Howdy的Botkit ,尤其是如果您已经使用Node.js 。 Botkit是负责处理大多数这些API体操的框架,因此您可以专注于机器人的行为。

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的样板。 但是我选择从头开始,以更好地了解我的机器人。 但是,最好使用在Glitch上创建的机器人来训练自己。

Slack机器人如何工作? (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:

我不是专家。 我一遍又一遍地阅读了Slack和Botkit的官方文档。 我仍然不确定我是否了解一切。 这是我对Slack机器人行为的理解:

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上的每个应用程序都有一个“范围”,范围是应用程序可以读取或执行操作的范围。 机器人是Slack上创建并安装的应用程序的一部分。

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上安装应用程序时,您可以访问某些信息和权限。 对于您的漫游器,您至少希望它能够发送和回复其他用户的消息。

There are then two cases:

然后有两种情况:

  1. You want your bot to react to events happening directly in Slack

    您希望您的机器人对直接在Slack中发生的事件做出React

  2. You want your bot to react to events happening on your server

    您希望机器人对服务器上发生的事件做出React

We will view both of them in this post!

我们将在这篇文章中同时查看它们!

入门 (Getting Started)

Before anything else, you will need a server. In my case, Express.

首先,您需要一台服务器。 就我而言,快递。

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.

此端口必须是公共的并且可以访问,而不仅仅是在本地主机上。

For the moment, this server is a blank page, showing and processing nothing.

目前,该服务器是空白页,什么也没有显示和处理。

You’ll then need a Slack App: just follow this link to create one.

然后,您将需要一个Slack应用程序:只需点击此链接即可创建一个。

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

然后,您必须配置控制器。 控制器是您的机器人的大脑。 它包含所有技能和配置。 以下是我的botkit.js文件。 它具有与Botkit入门工具包中可用内容几乎相同的内容: 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 Slack

controller.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
});
解锁第一种情况:对Slack上发生的事件做出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.

当您为应用程序授予正确的权限时,每次在通道上发送消息时,Slacks都会向服务器发送请求,其中包含一些信息-通道ID,用户,时间戳,最重要的是消息的内容。

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.

如果我们希望我们的机器人对诸如“ Hi”这样的简单消息做出React,我们必须给Slack一个地址来发送信息。

In a routes.js file write:

在routes.js文件中编写:

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 processed
    slack.controller.handleWebhookPayload(req, res)
  })
}

We now have a webhook : http://your-ip-or-domain:port/slack/receive

现在,我们有了一个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.

一旦通过Slack应用程序的“事件订阅”页面将此路由通知给Slack,它将能够向其发送JSON。 由于上面的server.js文件的解析部分,您将能够收到它。

Here is a (simple) schema to explain the process behind it:

这是一个(简单的)模式来说明其背后的过程:

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-服务器«很好,我将其发送给Botkit»

3- BOTKIT «Here is a temporary answer, wait a second»

3- BOTKIT«这是暂时的答案,请稍等»

4- BOTKIT « Yeah! I hear a keyword, here is a JSON object with the action to perform »

4- BOTKIT«是的! 我听到一个关键字,这是一个JSON对象,具有要执行的操作»

If we want our bot to react every time it hears “Hello”, we can simply add this .hears() function to our controller:

如果我们希望我们的机器人在每次听到“ Hello”时做出React,我们可以简单地将此.hears()函数添加到我们的控制器中:

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与市场上几乎所有可用的数据库系统兼容。 我决定使用MongoDB,因为它在我的学习清单上已经很长时间了。 此外,还详细介绍了Botkit的文档。

Now, we have to let our imagination do the work and find some fun features to create.

现在,我们必须让我们的想象力完成工作,并找到一些有趣的功能来创建。

第二种情况:与您的机器人进行对话 (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.

对于此功能,我希望我的机器人对未在Slack上启动的事件做出React。 例如,做一个日常工作。 如果是公司的周年纪念日,请向他们发送一份调查表,询问他们对头几个月/几周的感觉。

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.

以下是每个工作日上午9:00触发的cronjob。 借助Date()方法,该机器人可以获取今天的日期并将其与用户的“ joinedDate”进行比较。

To get only the right users and avoid a forEach loop, we can use a query on our Database:

为了只获取合适的用户并避免forEach循环,我们可以对数据库使用查询:

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 date
        let 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!

还有……多田!

结论 (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!

在成为一名露营者并学习编码超过一年之后,我非常高兴能够启动和完成这样的项目。 现在,我有一个机器人正在工作,并执行我在设计阶段想到的几乎所有动作。 而且我还有很多想法!

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. :-)

我仍在研究这个机器人。 GitHub存储库可在此处找到: https : //github.com/alexandrobin/hrbot 。 一些提交使用法语,但是代码库用英语注释。 :-)

Besides, it’s quite easy to deploy it on Heroku with a Mongolab database if you don’t have a server!

此外,如果没有服务器,使用Mongolab数据库在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.

如果您有任何建议或对本文和项目感兴趣,请随时发表评论! 我很乐意与您讨论。

翻译自: https://www.freecodecamp.org/news/how-i-built-an-hr-slack-bot-with-node-and-botkit-6b23b81531bb/

slack 使用说明

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值