使用MongoDB Stitch在10分钟内构建一个Slack应用

Slack is not only the fastest growing startup in history, but it's also an app by the same name and one of the most popular communication tools in use today. We use it extensively at MongoDB to foster efficient communications between teams and across the company. We're not alone. It seems like every developer I encounter uses it in their company as well.

Slack不仅是历史上发展最快的创业公司 ,还是同名应用程序,并且是当今使用的最受欢迎的通信工具之一。 我们在MongoDB中广泛使用它,以促进团队之间以及整个公司之间的有效通信。 我们并不孤单。 似乎我遇到的每个开发人员也在他们的公司中使用它。

One interesting thing about Slack (and there are many) is its extensibility. There are several ways you can extend Slack. Building chatbots, applications that interface with the communication service and extending Slack through the introduction of additional commands called "slash commands" that enable Slack users to communicate with external services. In this article, we'll build a simple slash command that enables users to store and retrieve data in and from a MongoDB database. I'm always finding interesting information on the internet that I want to share with my team members so let's build an application we'll call URL Stash that will store interesting URLs for later retrieval via a Slack slash command. Now, follow along in the video below or skip over the video and read on for the details.

关于Slack(还有很多)的一件有趣的事情是它的可扩展性。 有几种扩展Slack的方法。 构建聊天机器人,与通信服务接口的应用程序,并通过引入称为“斜线命令”的附加命令扩展Slack,这些附加命令使Slack用户能够与外部服务进行通信。 在本文中,我们将构建一个简单的斜杠命令,使用户能够在MongoDB数据库中存储数据或从中检索数据。 我一直在Internet上找到想要与团队成员共享的有趣信息,因此让我们构建一个名为URL Stash的应用程序,该应用程序将存储有趣的URL,以便以后通过Slack斜杠命令进行检索。 现在,请按照下面的视频进行操作,或跳过视频并继续阅读以获取详细信息。

创建一个松弛应用 ( Create a Slack App )

Start by logging into your slack team, or you can create a new one for testing. Visit the Slack API Console to create a new Slack App.

首先登录到松弛的团队,或者您可以创建一个新的团队进行测试。 访问Slack API控制台以创建新的Slack应用。

创建一个松弛的应用程序

You'll need to have a Slack team or instance where we can install and test URL Stash. I'm going to use the MongoDB Community Slack instance. Once we've created the app in our team workspace, we can put the Slack app to the side for the moment and create the other half of the app — the MongoDB Atlas Cluster, Database, Collections, and Stitch app.

您需要有一个Slack团队或实例,我们可以在其中安装和测试URL Stash。 我将使用MongoDB社区Slack实例。 一旦在团队工作区中创建了该应用程序,就可以暂时将Slack应用程序放到一边,并创建该应用程序的另一半-MongoDB Atlas集群,数据库,集合和Stitch应用程序。

创建Atlas集群,数据库和集合 ( Create an Atlas Cluster, Database, and Collection )

Stashing URLs implies that we'll need a place to store them. For this example, we're going to demonstrate how easy it is to use MongoDB Atlas to do this. We'll start by logging in to MongoDB Atlas, creating a cluster, a database and a collection. You can start for free and create an M0 class cluster instance. Once you've launched your cluster, create a database, and a collection using the collection viewer in Atlas. I called mine exampledb and examplecoll but you may call yours whatever you like. You'll just need to make sure you reference them correctly in the function we'll create in Stitch in the next section.

隐藏URL意味着我们需要一个地方来存储它们。 对于此示例,我们将演示使用MongoDB Atlas做到这一点有多么容易。 我们将从登录MongoDB Atlas开始, 创建一个集群 ,一个数据库和一个集合。 您可以免费启动并创建M0类集群实例 。 启动集群后,使用Atlas中的集合查看器创建数据库和集合。 我叫我exampledbexamplecoll,但是您可以随便叫什么。 您只需要确保在下一部分我们将在Stitch中创建的函数中正确引用它们即可。

创建一个MongoDB Atlas数据库

创建针迹应用 ( Create a Stitch App )

Stitch apps are associated with specific clusters so once you create your cluster, you can click Stitch apps from the left-hand navigation menu in Atlas, then click Create New app.

Stitch应用程序与特定的群集相关联,因此一旦创建群集,就可以从Atlas左侧导航菜单中单击Stitch应用程序,然后单击Create New app。

创建针迹应用

创建服务 ( Create a Service )

Services in Stitch are a primary point of integration with the outside world — in this case, Slack. Let's create an HTTP Service that will provide the integration point between Slack and Stitch.

Stitch中的服务是与外界集成的主要点,在本例中为Slack。 让我们创建一个HTTP服务,该服务将提供Slack和Stitch之间的集成点。

Click on Services, Add New Service, Click HTTP, and name the service. Click Add Service. Then, in the settings tab, name the incoming webhook something meaningful. I chose "slack" but you may name this anything you like. The webhook will provide an external web address that will be plugged into your Slack app.

单击服务,添加新服务,单击HTTP,然后命名服务。 单击添加服务。 然后,在“设置”选项卡中,将传入的Webhook命名为有意义的名称。 我选择了“ slack”,但您可以随意命名。 该Webhook将提供一个外部网址,该网址将插入到您的Slack应用程序中。

Plugging in this webhook URI, will tell your Slack app to send certain details of the conversation from Slack to your newly created Stitch Application.

插入此Webhook URI,将告诉您的Slack应用将会话的某些详细信息从Slack发送到您新创建的Stitch应用。

Once you click Save, your newly created webhook will be assigned a public URI, and you'll be given the ability to edit the JavaScript code that will be executed when a request is sent to your webhook. You may want to copy the Webhook URL because you will need that shortly when we create a Slack slash command.

单击“保存”后,将为新创建的Webhook分配一个公共URI,并且您可以编辑将请求发送到您的Webhook时将执行JavaScript代码。 您可能需要复制Webhook URL,因为在我们创建Slack斜杠命令后不久将需要该URL。

设置Webhook

This is where the magic happens. In just a few minutes, we created an integration between Slack and Stitch. The simple act of setting some configuration (naming) for your service is all that's required. Let's turn our attention to the code that we'll use to store, and retrieve URLs for our Slack users.

这就是魔术发生的地方。 在短短的几分钟内,我们在Slack和Stitch之间创建了一个集成。 只需为服务设置一些配置(命名)即可。 让我们将注意力转移到将用于存储和检索Slack用户URL的代码上。

The heart of a Stitch Service is the function that's run when it receives an incoming request via its Webhook URL. In this case, we chose to respond to POST requests. In Slack, we'll send the data from a slash command via POST to our Stitch function. We'll evaluate the text that the user sends as part of the slash command and either stash a URL, or list out the existing URLs that have been previously stashed.

Stitch Service的核心是通过Webhook URL接收到传入请求时运行的功能。 在这种情况下,我们选择响应POST请求。 在Slack中,我们将通过POST将来自斜杠命令的数据发送到Stitch函数。 我们将评估用户作为slash命令的一部分发送的文本,并隐藏一个URL,或列出先前已隐藏的现有URL。

松弛/缝合的心

Since the function is receiving the details from Slack, we'll enable a simple set of commands after the slash command itself. We'll want users to be able to store URL's, so we'll use the command format:

由于该函数正在从Slack接收详细信息,因此我们将在slash命令本身之后启用一组简单的命令。 我们希望用户能够存储URL,因此我们将使用以下命令格式:

/url stash [url]

/url stash [url]

And since we'll want users to be able to review the URL's that have previously been stashed, we'll enable a "list" option:

并且由于我们希望用户能够查看以前隐藏的URL,因此我们将启用“列表”选项:

/url list

/url list

And lastly, since we'll want users to be able to remove URLs that they've previously added, we'll enable a "remove" option:

最后,由于我们希望用户能够删除他们先前添加的URL,因此我们将启用“删除”选项:

/url remove [url]

/url remove [url]

With these basic commands in mind, let's write some basic JavaScript for the function inside our service:

牢记这些基本命令,让我们为服务中的函数编写一些基本JavaScript:

exports = async function (payload) {
   const mongodb = context.services.get("mongodb-atlas");
   const exampledb = mongodb.db("exampledb");
   const examplecoll = exampledb.collection("examplecoll");

   const args = payload.query.text.split(" ");

   switch (args[0]) {
       case "stash":
           const result = await examplecoll.insertOne({
               user_id: payload.query.user_id,
               when: Date.now(),
               url: args[1]
           });
           if (result) {
               return {
                   text: `Stashed ${args[1]}`
               };
           }
           return {
               text: `Error stashing`
           };
       case "list":
           const findresult = await examplecoll.find({}).toArray();
           const strres = findresult.map(x => `<${x.url}|${x.url}>  by <@${x.user_id}> at ${new Date(x.when).toLocaleString()}`).join("\n");
           return {
               text: `Stash as of ${new Date().toLocaleString()}\n${strres}`
           };
       case "remove":
           const delresult = await examplecoll.deleteOne({
               user_id: {
                   $eq: payload.query.user_id
               },
               url: {
                   $eq: args[1]
               }
           });
           return {
               text: `Deleted ${delresult.deletedCount} stashed items`
           };
       default:
           return {
               text: "Unrecognized"
           };
   }
}

Example Function for Slack HTTP Service in Stitch

Stitch中的Slack HTTP服务示例函数

The heart of our function is the switch statement which evaluates the text sent to the command by the Slack user.

我们函数的核心是switch语句,该语句评估Slack用户发送到命令的文本。

创建一个斜杠命令 ( Create a Slash Command )

Let's complete the final step in the process and add a slash command to our Slack App. To do this, head back over to the Slack app console and click "Slash Command".

让我们完成该过程的最后一步,并将斜杠命令添加到我们的Slack App。 为此,请回到Slack应用程序控制台,然后单击“斜杠命令”。

创建一个斜杠命令

Creating a slash command in Slack

在Slack中创建斜线命令

Name your slash command. Keep in mind you'll need to grab the MongoDB Stitch service webhook URI that we created in the previous section above. Once you save this slash command you should select Install Your app from the left-hand navigation in Slack's app Management console.

命名您的斜杠命令。 请记住,您需要获取我们在上一节中创建的MongoDB Stitch服务Webhook URI。 保存此斜杠命令后,您应该从Slack的应用程序管理控制台的左侧导航中选择“安装您的应用程序”。

安装Slack应用

Install App

安装软件

This will prompt you to confirm your identity on your slack team and authorize the app to be used in your workspace.

这将提示您确认松弛团队的身份,并授权该应用程序在您的工作空间中使用。

授权应用

Authorize app Installation

授权安装应用

Once this is complete, your app is nearly done. You can switch back to your Slack client, visit your own personal chat channel for privacy while you test and type your newly created Slack slash command. For example "/url stash http://mongodb.com". Pressing enter will send the command to Slack and then to your newly created Stitch app. You should see something like following in response:

完成后,您的应用程序即将完成。 您可以切换回Slack客户端,在测试并键入新创建的Slack斜杠命令时访问自己的个人聊天频道以获取隐私。 例如“ / url stash http://mongodb.com” 。 按Enter键会将命令发送到Slack,然后发送到您新创建的Stitch应用程序。 您应该看到以下响应:

与应用互动

It's just that simple, you've created a fully functioning Slack Chatbot, or at least a slash command with only a few lines of code and no servers involved!

就是这么简单,您已经创建了一个功能齐全的Slack Chatbot,或者至少使用了几行代码且不涉及服务器的斜杠命令!

This is merely a starting point and you should now easily be able to build additional functionality into your new Slack App. To review more details and fork the project, head over to the GitHub Repository.

这仅仅是一个起点,您现在应该可以轻松地在新的Slack App中构建附加功能。 要查看更多详细信息并创建项目,请转到GitHub Repository

翻译自: https://scotch.io/tutorials/build-a-slack-app-in-10-minutes-with-mongodb-stitch

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值