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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393768.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux 监听数据包,linux下网络监听与发送数据包的方法(即libpcap、libnet两种类库的使用方法)...

linux下可以用libpcap函数库实现监听数据包,使用libnet 函数库发送数据包安装:在命令行下apt-get install 就可以了libpcap的使用:/*author hjjdate 2011-1-21function:capture packet with the ruler and output the packet informationmodify 2011-1-23function:g…

命令模式(Command Pattern)

1命令模式是一个高内聚的模式。定义如下:将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。 2.角色说明: ● Receive接收者角色 该角色就…

BZOJ 3270: 博物馆

传送门 显然可以状态转移: 设 $f[k][x][y]$ 表示第 $k$ 时刻,第一个人在 $x$ ,第二个人在 $y$ 时的概率 那么转移显然: $f[k][x][y]\sum_{u}\sum_{v}f[k-1][u][v]*(1-P_u)(1-P_v)/du[u]/du[v]$ 其中 $u$ 和 $x$ 有边相连&#xff…

graphpad7.04多组比较p值_同是折线图为何你却这么优秀,这才是多组数据作图应该有的样子...

相信大家对Excel做折线图应该不陌生,在展示数据的时候,图表是一种最好的展示方法。但是经常会碰到一种尴尬的事情就是,当数据维多比较多的时候,做出的图表就会显得非常难看。今天我们就来学习一下,多组数据怎么做折线图…

Logic-算法-八个箱子找一个最轻的

ylbtech-Arithmetic:Logic-算法-八个箱子找一个最轻的-- -- ylb:算法-- Type:算法[logic]-- munu:八个箱子-找一个最轻的-- thankyou:gaoZhimin -- 7:11 2012/3/17-- 有八个正方形的箱子,外观大小都一样,其中七个是50斤的,一个是…

由衷的信来激励有抱负的开发人员

by Logan Wright洛根赖特(Logan Wright) 由衷的信来激励有抱负的开发人员 (A heartfelt letter to inspire the aspiring developer) I’m writing a letter to my friend. You should read it. He studies Computer Science, and he hates it. I build React Apps and I love…

linux 运行 chom,Hadoop安装-单节点/伪分布(2.7.3)

1,下载Hadoop目前在Ubuntu的软件库里面 没有发现Hadoop的压缩包,没猜错Hadoop不是可执行文件 只是一个压缩包吧!所以我们只能自己到官网下载(http://hadoop.apache.org/releases.html);在Apache社区中,下载软件的时候…

leetcode944. 删列造序

给定由 N 个小写字母字符串组成的数组 A,其中每个字符串长度相等。 你需要选出一组要删掉的列 D,对 A 执行删除操作,使 A 中剩余的每一列都是 非降序 排列的,然后请你返回 D.length 的最小可能值。 删除 操作的定义是&#xff1…

python学习:re模块

常用正则表达式符号 123456789101112131415161718192021. 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行^ 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee&qu…

app之---豆果美食

1.抓包 2.代码 抓取: #!/usr/bin/env python # -*- coding: utf-8 -*- #author tom import requests from multiprocessing import Queue from handle_pymongo import mongo from concurrent.futures import ThreadPoolExecutorclass Douguo():def __init__(self):s…

语言坐标度分秒的换算_测量位置度说明

测量位置度说明位置度是限制被测要素的实际位置对理想位置变动量的指标。它的定位尺寸为理论正确尺寸。位置度公差在评定实际要素位置的正确性, 是依据图样上给定的理想位置。位置度包括点的位置度、线的位置度和面的位置度。[1] 点的位置度:如公差带前加S¢&#xf…

OpenStack创建win7实例遇到的问题(尚未解决,求帮助)

原地址在这里:(作者也是我,害羞)http://www.aboutyun.com/forum.php?modviewthread&tid22898 小白经过两天尝试,用fuel部署好了OpenStack的云平台,接下来想在Compute节点上创建一个win7 实例&#xff…

VMware使两台windows虚拟机能够互相ping通

如果以下内容测试无效,可参考另一篇:VMware虚拟机配置内网电脑能访问 1.关闭防火墙 cmd命令行里输入:netsh firewall set opmode disable 2.测试如果还不能ping通,就把网络类型选nat类型 3.测试:vmware网关默认是.2 转…

linux账号前有个base,安装 aconda 后Linux的终端界面前部出现(base)字样

aconda 是做什么用的这里就不说了,一般玩Python的都知道这东西,最早接触这东西是因为它把NVIDIA中cuda计算和Python互连的一个库拿下了,是买下来了还是专业,还是唯一合作的也就记不清了,那就是 numba , 那些年头Python…

回复邮件时如何不要邮件头_如何为阅读,点击和回复率达到100%的CEO设计一封冷邮件...

回复邮件时如何不要邮件头by Theo Strauss由西奥斯特劳斯(Theo Strauss) 如何为阅读,点击和回复率达到100%的CEO设计一封冷邮件 (How to design a cold email for a CEO with a 100% read, click, and response rate) 银河电子邮件指南:第二…

leetcode1007. 行相等的最少多米诺旋转(贪心)

在一排多米诺骨牌中,A[i] 和 B[i] 分别代表第 i 个多米诺骨牌的上半部分和下半部分。(一个多米诺是两个从 1 到 6 的数字同列平铺形成的 —— 该平铺的每一半上都有一个数字。) 我们可以旋转第 i 张多米诺,使得 A[i] 和 B[i] 的值…

Spring 学习教程(一): 认识 Spring 框架

Spring 框架是 Java 应用最广的框架,它的成功来源于理念,而不是技术本身,它的理念包括 IoC (Inversion of Control,控制反转) 和 AOP(Aspect Oriented Programming,面向切面编程)。 Spring 的框架结构 Data Access/Int…

小米网关控制空调伴侣_小米有品上架移动空调,支持语音控制

近日小米有品商城上架了一款互联网可移动空调,机身仅有小米空气净化器一般大小,底部安装了万向轮,支持多方位自由移动,拥有三大功能,兼顾去暑除湿能力,产品售价1599元,有需求的用户可以在小米有…

错误: 找不到符号

Error:(31, 29) 错误: 找不到符号 符号: 类 OnLaunchPluginCallback 位置: 类 IreaderPlugApi 明明我都可以ctrl 单击点过去,但是就是运行的时候报错。说错误: 找不到符号。 我试了两遍,把工程clearn, 删除build下面的文件夹,弄了两遍&am…

leetcode910. 最小差值 II(贪心)

给定一个整数数组 A,对于每个整数 A[i],我们可以选择 x -K 或是 x K,并将 x 加到 A[i] 中。 在此过程之后,我们得到一些数组 B。 返回 B 的最大值和 B 的最小值之间可能存在的最小差值。 示例 1: 输入&#xff1…