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:

对于此程序,我将使用:

  • BotkitBotkit
  • Node JS节点JS
  • Express ServerExpress服务器
  • MongoDBMongoDB
  • Slack API & of courseSlack 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 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
});

解锁第一种情况:对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 processedslack.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 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!

还有……多田!

结论 (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 使用说明

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

  1. slack 使用说明_如何使用Node.js为Slack构建Meetupbot

    slack 使用说明 by premprakashsingh 通过premprakashsingh 如何使用Node.js为Slack构建Meetupbot (How to build a Meetu ...

  2. slack 使用说明_使用Reacji自动将Slack消息移至其他渠道

    slack 使用说明 Creating hyper-focused channels in Slack makes it easy to stay on topic but hard to see a ...

  3. slack 使用说明_我如何使用Slack作为自己的个人助理

    slack 使用说明 Slack is most known as a glorified chatroom app for workplaces, but it's also a great too ...

  4. slack 使用说明_如何使用Slack中的向上箭头选择和编辑消息

    slack 使用说明 If you're a new Slack user and press the Up arrow key on your keyboard, the productivity ...

  5. slack 使用说明_开发人员应使用的7个Slack集成

    slack 使用说明 如何使用集成和机器人自定义Slack来增强您的开发工作流程 毫无疑问,Slack正在逐渐成为现代办公通信的标准. 尽管您可能会说Slack从技术上讲与IRC没什么不同,但是精湛的 ...

  6. slack 使用说明_如何使用Slack远程扮演桌面角色扮演游戏

    slack 使用说明 PollyW/Shutterstock PollyW /快门 The infinite realms of tabletop role-playing games that ar ...

  7. meetup_如何使用标准库和Node.js构建Meetup Slack机器人

    meetup by Janeth Ledezma 简妮丝·莱德兹玛(Janeth Ledezma) 如何使用标准库和Node.js构建Meetup Slack机器人 (How to build a M ...

  8. 注销slack账号_如何从您的Slack帐户中注销所有设备

    注销slack账号 If you're worried someone has access to your Slack account, or you want to make sure old d ...

  9. node mongoose_如何使用Express,Mongoose和Socket.io在Node.js中构建实时聊天应用程序

    node mongoose by Arun Mathew Kurian 通过阿伦·马修·库里安(Arun Mathew Kurian) 如何使用Express,Mongoose和Socket.io在N ...

最新文章

  1. 集合对象的数据绑定(1)
  2. Linux源码手机,Linux操作系统源代码详细分析
  3. 解决Button在IE6、7下的自适应宽度问题
  4. 零食嘴----美食领域的美丽说
  5. 收藏功能_微软Edge获得了新的收藏夹菜单、PDF功能等
  6. Linux命令之感叹号 !
  7. 计组之中央处理器:8、五段式指令流水线
  8. 自动驾驶:蛇形曲线跟踪(Stanley Model)
  9. fpga结构主体_两大FPGA公司的“AI技术路线”
  10. 理解函数:对象(this,arguments),方法(apply(),call(),bind())。
  11. live2d手机制作软件_Live2d( 动画制作软件 )中文版分享
  12. java报错stderr_struts2 文件上传路径错误 ERROR [STDERR] java.io.FileNotFoundException:
  13. 通过dSYM文件分析crash日志
  14. h5截长图(html2canvas保存图片)
  15. 7步轻松设置授权管理器License Manager
  16. BW随手记-项目上零碎总结(SAP销售,开票,获利能力分析)
  17. 关于系统安装之U盘制作【install.wim】
  18. 查看设备序列号和设备标识的方式(有三种方法)
  19. 网络视频服务器与数字硬盘录像机的区别
  20. 三角形外接球万能公式_外接球半径常见的求法

热门文章

  1. mysql shell 回车换行_【shell mysql 导出数据到csv脚本,完美解决乱码转义符等问题】-费元星...
  2. border-image图片边框
  3. vue 源码学习(一) 目录结构和构建过程简介
  4. winfrom 点击按钮button弹框显示颜色集
  5. .h .dll .lib
  6. Android RecyclerView (一) 使用完全解析
  7. 企业日志分析 五大问题需重点注意
  8. laravel5 centos6.4下的配置体验
  9. 自定义配置节与配置节的读取
  10. 字符串编辑距离(转载)