构建node.js基础镜像
Slack is an American cloud-based set of proprietary team collaboration software tools and online services, developed by Slack Technologies. Slack is a workspace where teams can communicate and collaborate.
Slack是由Slack Technologies开发的一套基于美国云的专有团队协作软件工具和在线服务。 Slack是团队可以交流和协作的工作空间。
Teamwork in Slack happens in channels — a single place for messaging, tools and files — helping everyone save time and collaborate.
Slack中的团队合作发生在渠道(用于消息传递,工具和文件的单个位置)中,可帮助每个人节省时间并进行协作。
One of the awesome features of Slack is Slack Apps, integrations and Slack Bots.
Slack的令人敬畏的功能之一是Slack应用程序 ,集成和Slack Bot 。
A Slack bot is a type of Slack App designed to interact with users via conversation. Your bot can send DMs, it can be mentioned by users, it can post messages or upload files, and it can be invited to channels. Cool right?
Slack机器人是一种Slack应用程序,旨在通过对话与用户进行交互。 您的机器人可以发送DM,可以被用户提及,可以发布消息或上传文件,还可以被邀请加入渠道。 酷吧?
If you use Slack already, you should be familiar with some creative Slack bots like Standupbot, Birthdaybot and more.
如果您已经使用过Slack,则应该熟悉一些创新的Slack机器人,例如Standupbot , Birthdaybot等。
In this article, I'll walk you through building your first Slack bot from start to finish with Node.js and SlackBots.js
在本文中,我将引导您使用Node.js和SlackBots.js从头到尾构建您的第一个Slack机器人。
PS: This article was published on my blog first.
PS:本文首先发表在我的博客上 。
We're going to build a simple Slackbot that displays random inspiring techie quotes and jokes for developers/designers.
我们将构建一个简单的Slackbot,为开发人员/设计人员显示随机启发的技术报价和笑话。
I built a chrome extension that displays random inspiring techie quotes for developers/designers on your new tab (you can download it here). We'll be using the quotes JSON from this extension as our quotes API and the Chuck Norris Jokes API for the jokes.
我构建了一个chrome扩展程序 ,该扩展程序在新标签上为开发人员/设计师显示随机启发的技术人员报价(您可以在此处下载)。 我们将使用此扩展程序中的引号JSON作为引号API和用于笑话的Chuck Norris Jokes API 。
When a user mentions our bot and adds inspire me, the bot returns a random quote from inspireNuggets. When the user types random joke, it returns a random joke from the Chuck Norris API. And when the user types help, it returns the instruction guide.
当用户提及我们的机器人并添加启发我时 ,该机器人会从inspireNuggets返回随机报价。 当用户键入随机笑话时 ,它将从Chuck Norris API返回一个随机笑话。 当用户键入帮助时,它会返回说明指南。
@inspirenuggets inspire me
@inspirenuggets激励我
@inspirenuggets inspire me
@inspirenuggets激励我
@inspirenuggets random joke
@inspirenuggets随机的笑话
@inspirenuggets random joke
@inspirenuggets随机的笑话
This article is not really about what we'll be building - it's just to show you the concept behind Slack bots and how to build yours. After you go through it, you can think about something else and build a different bot, as there're many possibilities.
本文并不是关于我们将要构建的内容,它只是向您展示Slack机器人背后的概念以及如何构建您的机器人。 完成之后,您可以考虑其他事情并构建其他机器人,因为这里有很多可能性。
You can clone or fork the final project here.
您可以在此处克隆或创建最终项目。
Pretty interesting right? Let's get started.
很有趣吧? 让我们开始吧。
We'll build this bot with Node.js and SlackBots.js. You don't need to know how to write Node.js, since I'll walk you through it. Still, knowing it is an advantage. You should also have
我们将使用Node.js和SlackBots.js构建该机器人。 您无需知道如何编写Node.js,因为我将逐步指导您。 不过,知道这是一个优势。 你还应该有
Let's set up and install Node.js and Npm first.
让我们首先设置和安装Node.js和Npm。
Download node here. If you have it installed already, skip this step. If you prefer to use a package manager to install, read this for all operating systems.
node -v
npm -v
Now that we have Node.js setup, let's initialize our project.
现在我们已经安装了Node.js,让我们初始化项目。
Create your project directory (I called mine Slackbot) and initialize git:
创建您的项目目录(我叫我的Slackbot)并初始化git:
git init
Next, create an index.js
file:
接下来,创建一个index.js
文件:
touch index.js
And initialize Npm:
并初始化Npm:
npm init
Simply answer all questions that come afterwards. If you're having issues, here's my own package.json
:
只需回答随后出现的所有问题。 如果您遇到问题,这里是我自己的package.json
:
{
"name": "slackbot",
"version": "1.0.0",
"description": "A simple Slackbot that displays random inspiring techie quotes for developers/designers.",
"main": "index.js",
"scripts": {
"start": "index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/BolajiAyodeji/slackbot.git"
},
"author": "Bolaji Ayodeji",
"license": "MIT",
"bugs": {
"url": "https://github.com/BolajiAyodeji/slackbot/issues"
},
"homepage": "https://github.com/BolajiAyodeji/slackbot#readme"
}
Now let's install and setup all the libraries we need.
现在,让我们安装和设置我们需要的所有库。
SlackBots.js is a Node.js library for easy operation with the Slack API.
SlackBots.js是一个Node.js库,可轻松使用Slack API进行操作。
npm install slackbots
In index.js
:
在index.js
:
const SlackBot = require('slackbots');
Axios is a promise-based HTTP client for the browser and node.js. If you know Fetch or AJAX, this is just a library that does the same thing with way cooler features. You can see them here.
Axios是用于浏览器和node.js的基于Promise的HTTP客户端。 如果您知道Fetch或AJAX,那么这只是一个使用更酷的功能完成相同操作的库。 您可以在这里看到它们。
npm install axios
In index.js
:
在index.js
:
const axios = require('axios')
To run a script in Node.js, you have to run node index.js
. Whenever you make changes to this file, you have to rerun node index.js
. This sucks when you're making so many changes like we'll be doing. That's why we need nodemon, a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
要在Node.js中运行脚本,您必须运行node index.js
。 每当您对此文件进行更改时,都必须重新运行node index.js
。 当您像我们一样进行许多更改时,这很糟糕。 这就是为什么我们需要nodemon的原因,该工具可通过在检测到目录中的文件更改时自动重启节点应用程序来帮助开发基于node.js的应用程序。
npm install -g nodemon
In package.json
, locate the scripts section and add a new start script:
在package.json
,找到脚本部分并添加一个新的启动脚本:
"scripts": {
"start": "node index.js"
}
If you run npm start
, the file will run but won't restart on change. To fix this, use the nodemon we installed instead of node like so:
如果您运行npm start
,则文件将运行,但不会在更改后重新启动。 要解决此问题,请使用我们安装的nodemon代替如下所示的node:
"scripts": {
"start": "nodemon index.js"
}
I won't explain this in-depth. In a few days, I'll publish an article around environmental variables, but for now just know that we use this to hide secret keys and tokens like the Slack Access Token we would be using. This way you don't have to push your secret keys to GitHub.
我不会深入解释。 再过几天,我将发表有关环境变量的文章,但现在我们只知道我们使用它来隐藏秘密密钥和令牌,例如我们将要使用的Slack Access Token。 这样,您不必将密钥推送到GitHub。
There are several ways to do this, but I prefer using dotenv. Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.
有几种方法可以做到这一点,但是我更喜欢使用dotenv。 Dotenv是一个零依赖模块,可将环境变量从.env文件加载到process.env中。
npm install dotenv
In index.js
:
在index.js
:
const dotenv = require('dotenv')
dotenv.config()
After all installation, your package.json
should look like this:
安装完成后,您的package.json
应该如下所示:
{
"name": "inspireNuggetsSlackBot",
"version": "1.0.0",
"description": "A simple Slackbot that displays random inspiring techie quotes and jokes for developers/designers.",
"main": "index.js",
"scripts": {
"start": "nodemon index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/BolajiAyodeji/inspireNuggetsSlackBot.git"
},
"author": "Bolaji Ayodeji",
"license": "MIT",
"bugs": {
"url": "https://github.com/BolajiAyodeji/inspireNuggetsSlackBot/issues"
},
"homepage": "https://github.com/BolajiAyodeji/inspireNuggetsSlackBot#readme",
"devDependencies": {
"dotenv": "^8.0.0"
},
"dependencies": {
"axios": "^0.19.0",
"slackbots": "^1.2.0"
}
}
Now that we have that all set up, we need a Slack workspace to run our bot in development. Creating a workspace is pretty easy, read this to learn more.
现在我们已经完成了所有设置,我们需要一个Slack工作区来在开发中运行我们的机器人。 创建工作区非常简单,请阅读此内容以了解更多信息。
Now that you have a workspace, you should have a Slack URL with your workspace name. Mine is mekafindteam.slack.com
.
现在您已经有了一个工作空间,您应该有了一个带有工作空间名称的Slack URL。 我的是mekafindteam.slack.com
。
Now you'll need to create a Slack App. Create one here.
现在,您需要创建一个Slack App。 在此处创建一个。
Enter your App name and ensure you're in the workspace you created if you're in multiple workspaces.
输入您的应用程序名称,如果您在多个工作区中,请确保您在创建的工作区中。
Now you'll see the settings > Basic Information page. Click the first tab Add features and functionality
:
现在,您将看到设置>基本信息页面。 点击第一个标签Add features and functionality
:
Since we're building a bot, select the Bots field.
由于我们正在构建机器人,因此请选择“ 机器人”字段。
Now you'll see the Bot user page:
现在,您将看到Bot用户页面:
Click the Add a Bot User
button.
单击Add a Bot User
按钮。
Your display name will automatically be filled in from your already chosen App name. You can update it, but I'll advise you use the same name everywhere with the same alphabet case to avoid errors.
您的显示名称将从您已经选择的应用名称中自动填写。 您可以对其进行更新,但我建议您在任何地方都使用相同的名称,并使用相同的字母大小写,以免出现错误。
Now, toggle the Always Show My Bot as Online
switch to always show your bot as Online. Remember this bot is just like a user in your workspace. Afterwards, click the Add Bot User
button.
现在,切换“ Always Show My Bot as Online
开关以始终将机器人显示为“在线”。 请记住,该机器人就像您工作区中的用户一样。 然后,单击Add Bot User
按钮。
Save all changes now:
立即保存所有更改:
Next, return to the Basic Information
page and select the Install your app to your workspace
tab.
接下来,返回“ Basic Information
页面,然后选择“ Install your app to your workspace
选项卡。
Click the Install App to Workspace
:
单击Install App to Workspace
:
Click allow and wait to be redirected back to the Basic Information
page.
单击允许,然后等待重定向回“ Basic Information
页面。
Note the Manage distribution
tab: this section is needed when you want to make your Bot available for installation by others. For now we're just building in development and I won't be covering distribution in this article. In my next article, I'll show you how to deploy your Slack bot and make it available as an App to other workspaces.
请注意“ Manage distribution
选项卡:当您想让Bot供其他人安装时,需要使用此部分。 现在,我们只是在开发中,而在本文中我将不讨论发行。 在我的下一篇文章中,我将向您展示如何部署Slack机器人并将其作为应用程序提供给其他工作区。
If you check your Slack workspace now, you should see the App installed in the Apps section.
如果现在检查您的Slack工作区,则应在“应用程序”部分中看到已安装的应用程序。
For now, it's offline - once we start building the bot, we'll turn this on.
目前,它处于离线状态-一旦我们开始构建bot,就将其打开。
Now we've created our bot, let's do some customization.
现在我们已经创建了机器人,让我们进行一些自定义。
Still, on the Basic Information
page, scroll down to the Display Information
section:
仍然,在“ Basic Information
页面上,向下滚动到“ Display Information
部分:
This is basic stuff: just upload a logo, change your background color, and add a short description.
这是基本的内容:只需上传徽标,更改背景颜色并添加简短说明即可。
Your icon should be 512x512px
or bigger and your background color should be in HEX. Read more on the App guidelines here.
您的图标应为512x512px
或更大,并且背景颜色应为十六进制。 在此处阅读有关应用指南的更多信息 。
Here's what mine looks like after customization:
定制后的情况如下所示:
Now that we have our Slack bot setup, let's grab out token keys.
现在我们有了Slack机器人程序,让我们获取令牌密钥。
In the navigation bar, locate the Features section and click the OAuth & Permission
tab:
在导航栏中,找到“功能”部分,然后单击“ OAuth & Permission
标签:
You'll see two Access Tokens:
您将看到两个访问令牌:
Copy the Bot User OAuth Access Token.
复制Bot用户OAuth访问令牌。
This will change every time you re-install this app or when you install it in another workspace. The token should start with xoxb-
.
每次您重新安装此应用程序或将其安装在另一个工作区中时,这种情况都会改变。 令牌应以xoxb-
。
Keeping credentials secure is important whether you're developing open source libraries and tools, internal integrations for your workspace, or Slack apps for distribution to workspaces across the world. - Slack
无论您是在开发开放源代码库和工具,工作空间的内部集成还是要分发到全球工作空间的Slack应用程序,确保凭据安全都是重要的。 -松弛
This is why we have installed Dotenv - we'll set that up in the next section.
这就是我们安装Dotenv的原因-我们将在下一部分中进行设置。
Now let's build our bot :).
现在,让我们构建我们的机器人:)。
Create a .env
file and add this:
创建一个.env
文件并添加以下内容:
BOT_TOKEN=YOUR_SLACK_ACCESS_TOKEN_HERE
Now let's start our SlackBot.js:
现在让我们开始我们的SlackBot.js:
const bot = new SlackBot({
token: `${process.env.BOT_TOKEN}`,
name: 'inspirenuggets'
})
We've just created a bot variable that initializes a new SlackBot instance which has two values, our token and app name.
我们刚刚创建了一个bot变量,用于初始化一个新的SlackBot实例,该实例具有两个值,即令牌和应用名称。
I used the ES6 template string syntax to bring in our token key from our .env
file. dotenv has this covered for us.
我使用ES6模板字符串语法从.env
文件中引入了令牌密钥。 dotenv为我们提供了此服务。
Make sure you use the same name you used while creating your Slack app, or else you'll have authentication errors.
确保使用与创建Slack应用程序时使用的名称相同的名称,否则会出现身份验证错误。
Now start the app:
现在启动应用程序:
npm start
nodemon should be running now and our Slack app should be online too.
nodemon应该现在正在运行,我们的Slack应用程序也应该在线。
Our Bot does nothing now even though it's running. Let's return a message.
即使运行,我们的机器人现在也什么也不做。 让我们返回一条消息。
bot.on('start', () => {
const params = {
icon_emoji: ':robot_face:'
}
bot.postMessageToChannel(
'random',
'Get inspired while working with @inspirenuggets',
params
);
})
The bot.on
handler sends the welcome message. We passed two parameters, the 'start'
and a function which holds a params variable which also holds the slack emoji. Slack emoji have codes, and you can find them here. I used :robot_face:
, but you can change this to your preferred emoji.
bot.on
处理程序发送欢迎消息。 我们传递了两个参数: 'start'
和一个包含params变量的函数,该函数还包含松弛的表情符号。 松弛表情符号包含代码,您可以在此处找到它们。 我使用了:robot_face:
但是您可以将其更改为您喜欢的表情符号。
We also initialized the bot.postMessageToChannel
function which is a SlackBot.js method to post a message to a channel. In this function, we pass the channel name we want to post to, the message in a string, and the params variable we declared earlier for the emoji. I used the #random channel and sent Get inspired while working with @inspirenuggets
to it. Your app should restart automatically and your bot should do this:
我们还初始化了bot.postMessageToChannel
函数,该函数是一种SlackBot.js方法,用于将消息发布到通道。 在此函数中,我们传递要发布到的频道名称,字符串中的消息以及我们先前为表情符号声明的params变量。 我使用#random频道, Get inspired while working with @inspirenuggets
一起Get inspired while working with @inspirenuggets
发送了Get inspired while working with @inspirenuggets
。 您的应用程序应自动重启,而您的机器人应执行以下操作:
Cool right?You can also post messages to users and groups.
不错吧?您还可以向用户和组发布消息。
// define existing username instead of 'user_name'
bot.postMessageToUser('user_name', 'Hello world!', params);
// define private group instead of 'private_group', where bot exist
bot.postMessageToGroup('private_group', 'Hello world!', params);
Let's also write a function to check for errors and return them:
我们还编写一个函数来检查错误并返回错误:
bot.on('error', (err) => {
console.log(err);
})
Now let's build the main bot functionality.
现在,让我们构建主要的机器人功能。
Like I said earlier, we'll be using the quotes JSON from the extension I built as our quotes API. The JSON can be found with this URL: https://raw.githubusercontent.com/BolajiAyodeji/inspireNuggets/master/src/quotes.json
就像我之前说的,我们将使用我构建为引号API的扩展中的引号JSON。 可以通过以下URL找到JSON: https://raw.githubusercontent.com/BolajiAyodeji/inspireNuggets/master/src/quotes.json
: https://raw.githubusercontent.com/BolajiAyodeji/inspireNuggets/master/src/quotes.json
When a user mentions our bot and adds inspire me, the bot returns a random quote from inspireNuggets. When the user types random joke, it returns a random joke from the Chuck Norris API. And when the user types help, it returns the instruction guide.
当用户提及我们的机器人并添加启发我时 ,该机器人会从inspireNuggets返回随机报价。 当用户键入随机笑话时 ,它将从Chuck Norris API返回一个随机笑话。 当用户键入help时 ,它将返回说明指南。
First, let's check for our command words from the user message (inspire me, random joke, and help):
首先,让我们从用户消息中检查命令词( 激发我 , 开玩笑和帮助 ):
function handleMessage(message) {
if(message.includes(' inspire me')) {
inspireMe()
} else if(message.includes(' random joke')) {
randomJoke()
} else if(message.includes(' help')) {
runHelp()
}
}
Now let's create the three function we need
现在让我们创建我们需要的三个功能
inspireMe()
鼓舞我()
Our demo JSON is not really an API, it's just some JSON I used in the Chrome Extension. We're only accessing it from GitHub raw contents. You can use any API you prefer, you'll just have to iterate differently to get your data depending on if your API returns an array or object - whichever it returns, it's not a big deal.
我们的演示JSON并不是一个真正的API,它只是我在Chrome扩展程序中使用的一些JSON。 我们仅从GitHub原始内容访问它。 您可以使用自己喜欢的任何API,仅需进行不同的迭代即可获取数据,具体取决于您的API是否返回数组或对象-无论返回什么,这都不重要。
Check out my previous articles on:
查阅我以前的文章:
Iterating through JavaScript Objects - 5 Techniques and Performance Tests.
function inspireMe() {
axios.get('https://raw.githubusercontent.com/BolajiAyodeji/inspireNuggets/master/src/quotes.json')
.then(res => {
const quotes = res.data;
const random = Math.floor(Math.random() * quotes.length);
const quote = quotes[random].quote
const author = quotes[random].author
const params = {
icon_emoji: ':male-technologist:'
}
bot.postMessageToChannel(
'random',
`:zap: ${quote} - *${author}*`,
params
);
})
}
We just used Axios to get the JSON file which returns some data:
我们只是使用Axios来获取返回一些数据的JSON文件:
[
{
"number": "1",
"author": "Von R. Glitschka",
"quote": "The client may be king, but he's not the art director."
},
{
"number": "2",
"author": "Frank Capra",
"quote": "A hunch is creativity trying to tell you something."
},
.
.
.
.
]
This JSON currently contains 210 quotes and I update them frequently. So we want to get a random quote plus the author name every time the user request it. From our Axios response, we just do this:
该JSON当前包含210个引号,我经常对其进行更新。 因此,我们希望每次用户请求时都提供一个随机报价以及作者姓名。 从我们的Axios响应中,我们可以这样做:
const quotes = res.data;
const random = Math.floor(Math.random() * quotes.length);
const quote = quotes[random].quote
const author = quotes[random].author
And just like we did with the welcome message, we just return the quote and author instead of a string message:
就像处理欢迎消息一样,我们只返回引号和作者,而不是字符串消息:
`:zap: ${quote} - *${author}*`
Let's test this:
让我们测试一下:
Type @inspirenuggets inspire me
@inspirenuggets inspire me
Yayyy! It worked!
耶! 有效!
PS: You can always change the emoji type for every request. If you noticed I changed the inspireMe()
to :male-technologist:
PS:您随时可以为每个请求更改表情符号类型。 如果您注意到我将inspireMe()
更改为:male-technologist:
randomJoke()
randomJoke()
We're getting the jokes from the Chuck Norris API from this endpoint https://api.chucknorris.io/jokes/random
.
我们从这个端点https://api.chucknorris.io/jokes/random
获得了Chuck Norris API的笑话。
{
"categories": [],
"created_at": "2016-05-01 10:51:41.584544",
"icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
"id": "6vUvusBeSVqdsU9C5-ZJZw",
"updated_at": "2016-05-01 10:51:41.584544",
"url": "https://api.chucknorris.io/jokes/6vUvusBeSVqdsU9C5-ZJZw",
"value": "Chuck Norris once choked a wildcat to death with his sphincter muscle."
}
This is a real API that returns a random joke on every request, so we don't have to do Math.floor()
again.
这是一个真正的API,可在每个请求上返回一个随机笑话,因此我们不必再次执行Math.floor()
。
function randomJoke() {
axios.get('https://api.chucknorris.io/jokes/random')
.then(res => {
const joke = res.data.value;
const params = {
icon_emoji: ':smile:'
}
bot.postMessageToChannel(
'random',
`:zap: ${joke}`,
params
);
})
}
By now, you should understand how this works already. Make a post with the channel name, message and params.
现在,您应该已经了解了它是如何工作的。 用频道名称,消息和参数发表帖子。
runHelp()
runHelp()
This is similar to our welcome message: we just want to return a custom text when the user adds help to the request.
这类似于我们的欢迎消息:当用户向请求中添加帮助时,我们只想返回自定义文本。
function runHelp() {
const params = {
icon_emoji: ':question:'
}
bot.postMessageToChannel(
'random',
`Type *@inspirenuggets* with *inspire me* to get an inspiring techie quote, *random joke* to get a Chuck Norris random joke and *help* to get this instruction again`,
params
);
}
Now let's test all three commands:
现在让我们测试所有三个命令:
Everything works fine now, congratulations!!!! You just built your SlackBot.
一切正常,恭喜!!!! 您刚刚构建了SlackBot。
There are an endless number of possibilities of Bots you can build with this to automate your own work or teamwork.
您可以使用Bot建立无限的Bot,以自动化您自己的工作或团队合作。
You can build a bot that:
您可以构建一个机器人:
Fetches your tasks from somewhere and reminds you when you type hey what next
,
从某处获取任务,并在您键入hey what next
时提醒您,
Welcomes every user to your workspace (I built this during one of the HNG Internship's),
and many more...
还有很多...
It's just about having somewhere to get the data from, and some basic iteration skills and the bot.postMessageToChannel()
method.
它只是具有在某处获取数据的位置,以及一些基本的迭代技巧和bot.postMessageToChannel()
方法。
Automation is one thing we should learn as developers. We have a lot to do, so we should automate the simpler tasks so we have time for the more difficult ones. I hope with this you can automate your tasks and I look forward to the creative ideas you'll bring to life.
自动化是我们作为开发人员应该学习的一件事。 我们有很多工作要做,因此我们应该自动化较简单的任务,以便有时间处理较困难的任务。 我希望借此可以使您的任务自动化,并期待您将带给您的创意。
Here's our final index.js
这是我们最终的index.js
const SlackBot = require('slackbots');
const axios = require('axios')
const dotenv = require('dotenv')
dotenv.config()
const bot = new SlackBot({
token: `${process.env.BOT_TOKEN}`,
name: 'inspirenuggets'
})
// Start Handler
bot.on('start', () => {
const params = {
icon_emoji: ':robot_face:'
}
bot.postMessageToChannel(
'random',
'Get inspired while working with @inspirenuggets',
params
);
})
// Error Handler
bot.on('error', (err) => {
console.log(err);
})
// Message Handler
bot.on('message', (data) => {
if(data.type !== 'message') {
return;
}
handleMessage(data.text);
})
// Response Handler
function handleMessage(message) {
if(message.includes(' inspire me')) {
inspireMe()
} else if(message.includes(' random joke')) {
randomJoke()
} else if(message.includes(' help')) {
runHelp()
}
}
// inspire Me
function inspireMe() {
axios.get('https://raw.githubusercontent.com/BolajiAyodeji/inspireNuggets/master/src/quotes.json')
.then(res => {
const quotes = res.data;
const random = Math.floor(Math.random() * quotes.length);
const quote = quotes[random].quote
const author = quotes[random].author
const params = {
icon_emoji: ':male-technologist:'
}
bot.postMessageToChannel(
'random',
`:zap: ${quote} - *${author}*`,
params
);
})
}
// Random Joke
function randomJoke() {
axios.get('https://api.chucknorris.io/jokes/random')
.then(res => {
const joke = res.data.value;
const params = {
icon_emoji: ':smile:'
}
bot.postMessageToChannel(
'random',
`:zap: ${joke}`,
params
);
})
}
// Show Help
function runHelp() {
const params = {
icon_emoji: ':question:'
}
bot.postMessageToChannel(
'random',
`Type *@inspirenuggets* with *inspire me* to get an inspiring techie quote, *random joke* to get a Chuck Norris random joke and *help* to get this instruction again`,
params
);
}
Our bot only runs in development now, and to use it we always have to npm start
.
我们的bot现在仅在开发中运行,要使用它,我们总是必须npm start
。
This isn't cool, right? We'll want to host it somewhere it can run every time. In my next article, I'll show you how to host this on either Heroku, Zeit or Netlify and publish it to the Slack Apps store so anyone around the world can use it.Also, don't forget to add this in your .gitignore
before pushing to GitHub:
这不酷吧? 我们希望将其托管在每次都能运行的地方。 在我的下一篇文章中,我将向您展示如何在Heroku , Zeit或Netlify上托管它,并将其发布到Slack Apps商店中,以便全世界的人都可以使用它。此外,请不要忘记将其添加到您的.gitignore
然后.gitignore
送到GitHub:
/.env
/node_modules
Subscribe to my newsletter to get updated.
订阅我的时事通讯以进行更新。
Slack Apps
松弛应用
翻译自: https://www.freecodecamp.org/news/building-a-slackbot-with-node-js-and-slackbots-js/
构建node.js基础镜像