<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Slack - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ freeCodeCamp 是一个免费学习编程的开发者社区，涵盖 Python、HTML、CSS、React、Vue、BootStrap、JSON 教程等，还有活跃的技术论坛和丰富的社区活动，在你学习编程和找工作时为你提供建议和帮助。 ]]>
        </description>
        <link>https://www.freecodecamp.org/chinese/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Slack - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/chinese/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 14 Jun 2026 05:02:34 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/chinese/news/tag/slack/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 通过构建你自己的 Slack App 来学习 Serverless ]]>
                </title>
                <description>
                    <![CDATA[ Serverless 架构在业内炙手可热，很多大厂已经开始拥抱它了。 本文将介绍 Serverless 是什么，为什么要拥抱它。以及 AWS 设置，如何创建 serverless app，如何创建 slack app。 什么是 Serverless Serverless 是云计算范例，开发者只需关注代码，无需担忧服务器运维。 云提供商，比如 AWS 或者 Azure，通过动态分配资源来运行代码以及运维服务。很多事件都可以触发代码，包括定时任务、http 请求或者数据库事件。 开发者发送到云端的代码通常只是一个函数，因此，serverless 架构通常实现为函数即服务（Function-as-a-Service），即 FaaS。很多云服务商提供 FaaS 框架，比如 AWS 的 Lambda 和 Azure 的 Functions。 为什么使用 Serverless Serverless 除了让开发者只关心代码外，还有如下优势。 由于云服务商负责运行代码以及分配资源，所以可以按请求数或者代码执行次数付费。 另外，由于云服务商接管服务器，不必担心流量涌入等问题，云服务商会搞定 ]]>
                </description>
                <link>https://www.freecodecamp.org/chinese/news/make-a-serverless-slack-app/</link>
                <guid isPermaLink="false">5dbaf0e4ca1efa04e196a2bb</guid>
                
                    <category>
                        <![CDATA[ Slack ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Serverless ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AWS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ ZhichengChen ]]>
                </dc:creator>
                <pubDate>Fri, 01 Nov 2019 02:00:00 +0000</pubDate>
                <media:content url="https://chinese.freecodecamp.org/news/content/images/2021/04/photo-1572481566261-4e2503288d82.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Serverless 架构在业内炙手可热，很多大厂已经开始拥抱它了。</p><p>本文将介绍 Serverless 是什么，为什么要拥抱它。以及 AWS 设置，如何创建 serverless app，如何创建 slack app。</p><h2 id="-serverless">什么是 Serverless</h2><p>Serverless 是云计算范例，开发者只需关注代码，无需担忧服务器运维。</p><p>云提供商，比如 AWS 或者 Azure，通过动态分配资源来运行代码以及运维服务。很多事件都可以触发代码，包括定时任务、http 请求或者数据库事件。</p><p>开发者发送到云端的代码通常只是一个函数，因此，serverless 架构通常实现为函数即服务（Function-as-a-Service），即 FaaS。很多云服务商提供 FaaS 框架，比如 AWS 的 Lambda 和 Azure 的 Functions。</p><h2 id="-serverless-1">为什么使用 Serverless</h2><p>Serverless 除了让开发者只关心代码外，还有如下优势。</p><p>由于云服务商负责运行代码以及分配资源，所以可以按请求数或者代码执行次数付费。</p><p>另外，由于云服务商接管服务器，不必担心流量涌入等问题，云服务商会搞定。综上，serverless app 便宜、易维护、高可用。</p><h2 id="-aws-lambda">设置 AWS Lambda</h2><p>在这个教程里会使用 AWS Lambda，首先来创建一个 <a href="https://aws.amazon.com/">AWS 账号</a>。AWS UI 不是很友好，我会给每个步骤贴一个截图。</p><p>登录后，如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-17.png" class="kg-image" alt="image-17" width="600" height="400" loading="lazy"></figure><p>首屏</p><p>接下来，创建一个 IAM 用户。<a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html">IAM</a> &nbsp;(Identity and Access Management) 用户可以操作 AWS 以及指定的资源。可以按场景创建具有相应权限的不同的 IAM 用户，不必担忧泄露 root 用户账号从而引发安全隐患。</p><p>点击页面导航栏的 "services“ ，在搜索框输入 ”IAM“ ：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-27.png" class="kg-image" alt="image-27" width="600" height="400" loading="lazy"></figure><p>单击第一个搜索结果，看到如下的左侧边栏，这就是 IAM 控制台了。点击 ”User“ 选项来创建一个新的 IAM 用户。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-28.png" class="kg-image" alt="image-28" width="600" height="400" loading="lazy"></figure><p>点击 ”Add user“ 按钮创建一个新用户。按照下图填写详情：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-29.png" class="kg-image" alt="image-29" width="600" height="400" loading="lazy"></figure><p>IAM 用户用什么名字都可以，在这里用的是 <code>serverless-admin</code>。确保选中了 ”Programmatic access“，取消 ”AWS Management Console Access“ 选中。 后者是给团队成员或者其它需要访问 AWS 的人用的。这里的 IAM 用户只需要和 AWS Lambda 交互，只需要给予 programmatic 权限即可。</p><p>在权限这里，因为还没有任何 Groups，也没有存在的可以复制权限的用户，选择 Attach existing policies。由于只是一个私人的项目，这里创建了一个具有超级管理员（Administrator）访问权限的用户。如果在生产环境使用 serverless app，IMA 用户应该限制为只具有访问 AWS Lambda 的权限。（<a href="https://serverless.com/blog/abcs-of-iam-permissions/">这里</a>有介绍）。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-58.png" class="kg-image" alt="image-58" width="600" height="400" loading="lazy"></figure><p>我没有给创建的用户添加任何标签。这对于接下来保存 Access ID 和 Secret Access Key 信息很重要。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot_2019-08-04-IAM-Management-Console.png" class="kg-image" alt="Screenshot_2019-08-04-IAM-Management-Console" width="600" height="400" loading="lazy"></figure><p>千万不要在没有复制和下载 key 前关掉这个页面。关掉了就在也看不到 Secret access key 了。</p><p>最后，使用 AWS 命令行添加 credentials 。可以根据这个<a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">指引</a>来安装 aws cli。</p><p>运行 <code>aws --version</code>来确保已经安装成功。如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-04-at-2.02.27-PM.png" class="kg-image" alt="Screen-Shot-2019-08-04-at-2.02.27-PM" width="600" height="400" loading="lazy"></figure><p>接着运行 <code>aws configure</code> 填写 Key 信息：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-04-at-5.42.53-PM.png" class="kg-image" alt="Screen-Shot-2019-08-04-at-5.42.53-PM" width="600" height="400" loading="lazy"></figure><p>上面默认的地区就是 <code>us-east-2</code>, 可以通过<a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">这个</a>来确定你的地区是什么。</p><p>为了确保 credentials 设置成功，可以在终端里运行 <code>cat ~/.aws/credentials</code>。</p><p>如果想设置某一个属性，可以运行如下命令：<code>aws configure --profile [profile name]</code>。</p><p>如果有和预期不符的地方，可以查询 <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html">AWS 的文档</a>。</p><h2 id="-serverless-2">设置 serverless</h2><p>打开终端执行命令 <code>npm i -g serverless</code> 在全局安装 <code>serverless</code> 框架。如下所示。<a href="https://serverless.com/">戳此了解更多 serverless 框架</a>。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-04-at-1.55.12-PM.png" class="kg-image" alt="Screen-Shot-2019-08-04-at-1.55.12-PM" width="600" height="400" loading="lazy"></figure><p>接着，到工作目录下，运行 <code>serverless</code>，按如下填写：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-04-at-5.55.03-PM.png" class="kg-image" alt="Screen-Shot-2019-08-04-at-5.55.03-PM" width="600" height="400" loading="lazy"></figure><p>在这里使用 Node.js。可以给 app 起任何名字，在这里使用 <code>exampleSlackApp</code>。</p><p>用代码编辑器打开 <code>exampleSlackApp</code>（或者你命名的项目）。</p><p>首先，打开 <code>serverless.yml</code>。会看到有大量的注释的代码描述了可以再这个文件使用的不同的选项。可以了解一下，下面的文件它们都删除了，便于显示：</p><pre><code>service: exampleslackapp

provider:
  name: aws
  runtime: nodejs10.x
  region: us-east-2

</code></pre><p>serverless.yml</p><p>由于默认的 <code>region</code> 是 <code>us-east-1</code> 我添加了 <code>region</code> &nbsp;改成 <code>us-east-2</code>。</p><p>运行 <code>serverless deploy</code> 来部署 <code>serverless</code> 刚刚创建的 app。输出如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-05-at-12.07.10-AM.png" class="kg-image" alt="Screen-Shot-2019-08-05-at-12.07.10-AM" width="600" height="400" loading="lazy"></figure><p>如果在终端运行 <code>serverless invoke -f hello</code>，会启动 app，输出如下：</p><pre><code>{
    "statusCode": 200,
    "body": "{\n  "message": "Go Serverless v1.0! Your function executed successfully!",\n  "input": {}\n}"
}
</code></pre><p>为了证明 slack app 已经在线，回到 AWS 控制台。打开 services 下拉菜单，搜索 ”Lambda“，选择第一个选项（Run code without thinking about servers）。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-32.png" class="kg-image" alt="image-32" width="600" height="400" loading="lazy"></figure><p>这里就是我们的 app！</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-33.png" class="kg-image" alt="image-33" width="600" height="400" loading="lazy"></figure><p>接下来，通过 serverless 构建 slack app，可以通过 &nbsp;<a href="https://api.slack.com/slash-commands">slash command</a> 向 slack 随机发送 <a href="https://en.wikipedia.org/wiki/Ron_Swanson">Ron Swanson</a> 的名言，如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-07-at-10.23.40-PM.png" class="kg-image" alt="Screen-Shot-2019-08-07-at-10.23.40-PM" width="600" height="400" loading="lazy"></figure><p>下面的步骤不必按顺序做，如果想跳着来，随意。</p><h2 id="-api">给我们的代码添加 API</h2><p>我使用<a href="https://github.com/jamesseanwright/ron-swanson-quotes#ron-swanson-quotes-api?ref=public-apis">这个 API</a> 来生成 Ron Swanson 的名言，它的文档很清晰（最重要的是免费）。如果想知道怎么调用以及返回格式，把这个链接复制到浏览器，访问一下：</p><p><a href="https://ron-swanson-quotes.herokuapp.com/v2/quotes"><code>https://ron-swanson-quotes.herokuapp.com/v2/quotes</code></a></p><p>结果如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-59.png" class="kg-image" alt="image-59" width="600" height="400" loading="lazy"></figure><p>打开默认的函数改成如下：</p><pre><code>module.exports.hello = (event) =&gt; {
  getRon();
};
</code></pre><p>注：我已经移除了 async</p><p><code>getRon</code> 方法如下</p><pre><code>function getRon() {
  request('https://ron-swanson-quotes.herokuapp.com/v2/quotes', function (err, resp, body) {
    console.log('error:', err)
    console.log('statusCode:', resp &amp;&amp; resp.statusCode)
    console.log('body', body)
  })
}
</code></pre><p>现在，检查一下是否正常。在终端里执行：<code>serverless invoke local -f hello</code>，在本地测试代码。输出如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-07-at-9.41.53-PM.png" class="kg-image" alt="Screen-Shot-2019-08-07-at-9.41.53-PM" width="600" height="400" loading="lazy"></figure><p>Spoiler: There was a wrong way to consume alcohol</p><p><code>serverless invoke -f hello</code> 会运行已经部署的代码，如前文所述。</p><p><code>serverless invoke local -f hello</code>，在本地运行代码，用它来测试很方便。测试无虞后 <code>serverless deploy</code> 部署一下，棒。</p><h2 id="-slack-app">创建 Slack App</h2><p>按照这个<a href="https://api.slack.com/apps?new_app=1">链接</a>创建 slack app。需要先注册 slack worksapce，确保有添加 slack app 的权限。这里创建了一个测试。弹出这个弹窗后，信息按需填写，如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-61.png" class="kg-image" alt="image-61" width="600" height="400" loading="lazy"></figure><p>接下来，是 app 的首页。这里可以好好研究一下，我是像下面这样定制的 app：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-62.png" class="kg-image" alt="image-62" width="600" height="400" loading="lazy"></figure><p>Display information 可以在 app 的 ”Basic information“ 标签页打开</p><p>接下来需要给 app 添加一些权限：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot_2019-08-07-Slack-API-Applications-lekha_test-Slack.png" class="kg-image" alt="Screenshot_2019-08-07-Slack-API-Applications-lekha_test-Slack" width="600" height="400" loading="lazy"></figure><p>向下滚动页面，添加 scope 和 permissions 来获得 OAuth Access Token。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-64.png" class="kg-image" alt="image-64" width="600" height="400" loading="lazy"></figure><p>I've added "Modify your public channels" so that the bot could write to a channel, "Send messages as Ron Swanson" so when the message gets posted, it looks like a user called Ron Swanson is posting the message, and slash commands so the user can "request" a quote as shown in the screenshot at the beginning of the article. After you save the changes, you should be able to scroll back up to OAuths &amp; Permissions to see:</p><p>添加 ”Modify your public channels“ 以便机器人可以向 channel 发消息。添加 ”Send messages as Ron Swaon“，这样收到信息时，看起来像是 Ron Swanson 用户发送的，以及 ”slash commands“，以便用户可以像文章开头的截图那样请求名言。点击 Save Changes 后，滚动回 OAuths &amp; Permissions 如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-65.png" class="kg-image" alt="image-65" width="600" height="400" loading="lazy"></figure><p>点击 Install App to Workspace 按钮，就会获得一个 OAuth Access Token。一会会用到它，复制或者下载它到某个地方。</p><h2 id="-slack-app-1">链接代码到 Slack App</h2><p>在 AWS Lambda 里，找到对应的 slack app 函数。函数代码部分应该显示更新过的代码，包含调用 Ron Swanson API 的代码（如果没有，在终端里执行一下 <code>serverless deploy</code>）。</p><p>滚动屏幕到 ”Environment Variables“ 部分，把 Slack OAuth Access Token 放在这里（给 key 起一个名字）：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot_2019-08-07-Lambda-Management-Console.png" class="kg-image" alt="Screenshot_2019-08-07-Lambda-Management-Console" width="600" height="400" loading="lazy"></figure><p>返回代码在函数里添加 Slack key。在文件顶部，声明一个 <code>const</code> ，引用 OAuth Token。</p><p>const SLACK_OAUTH_TOKEN = process.env.OAUTH_TOKEN`.</p><p><code>process.env</code> 只是获取到环境变量（<a href="https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env">戳此查看介绍</a>）。接下来看一下 <a href="https://api.slack.com/methods/chat.postMessage">Slack API</a> 来研究一下怎么向 channel 里发消息。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-67.png" class="kg-image" alt="image-67" width="600" height="400" loading="lazy"></figure><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-76.png" class="kg-image" alt="image-76" width="600" height="400" loading="lazy"></figure><p>上面的两幅图片是我在 API 文档里面截的，参考文档发起对应请求，这里使用 <code>request</code> 方法传入了一个名为 <code>options</code> 的对象：</p><pre><code>  let options = {
    url: 'https://slack.com/api/chat.postMessage',
    headers: {
      'Accept': 'application/json',
    },
    method: 'POST',
    form: {
      token: SLACK_OAUTH_TOKEN,
      channel: 'general', // hard coding for now
      text: 'I am here',
    }
  }
</code></pre><p>然后发起请求：</p><pre><code>  request(options, function(err, resp, body) {
    console.log('error:', err)
    console.log('statusCode:', resp &amp;&amp; resp.statusCode)
    console.log('body', body)
  })
</code></pre><p>最后封装成函数：</p><pre><code>function postRon(quote) {
  let options = {
    url: 'https://slack.com/api/chat.postMessage',
    headers: {
      'Accept': 'application/json',
    },
    method: 'POST',
    form: {
      token: SLACK_OAUTH_TOKEN,
      channel: 'general',
      text: quote,
    }
  }

</code></pre><p>给这个函数命名为 <code>getRon</code>，如下：</p><pre><code>function getRon() {
  request('https://ron-swanson-quotes.herokuapp.com/v2/quotes', function (err, resp, body) {
    console.log('error:', err)
    console.log('statusCode:', resp &amp;&amp; resp.statusCode)
    console.log('body', body)
    postRon(body.substring(2, body.length - 2)) // here for parsing, remove if you want to see how/why I did it
  })
}
</code></pre><p>整个代码看起来如下：</p><pre><code>'use strict';
let request = require('request');
const SLACK_OAUTH_TOKEN = process.env.OAUTH_TOKEN
module.exports.hello = (event) =&gt; {
  getRon();
};
function getRon() {
  request('https://ron-swanson-quotes.herokuapp.com/v2/quotes', function (err, resp, body) {
    console.log('error:', err)
    console.log('statusCode:', resp &amp;&amp; resp.statusCode)
    console.log('body', body)
    postRon(body.substring(2, body.length - 2))
  })
}
function postRon(quote) {
  let options = {
    url: 'https://slack.com/api/chat.postMessage',
    headers: {
      'Accept': 'application/json',
    },
    method: 'POST',
    form: {
      token: SLACK_OAUTH_TOKEN,
      channel: 'general',
      text: quote,
    }
  }

</code></pre><p>现在来测试一下！很不幸 AWS Lambda 里的环境变量在运行 <code>serverless invoke local -f hello</code> 时并不可用。有很多方法来解决这个问题，这里我们把 <code>SLACK_OAUTH_TOKEN</code> 替换成真实的 OAuth Token（确保以字符串的形式）。一定要记得不要把它提交到版本控制里面去哦。</p><p>运行 <code>serverless invoke local -f hello</code>，在 #general channel 会看到类似下面的信息：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-69.png" class="kg-image" alt="image-69" width="600" height="400" loading="lazy"></figure><p><em>注意我的是测试 workspace 所以 channel 名字是 <code>general</code>，如果在真实的 workspace 里，应该为测试 app 创建一个单独的 channel，在测试的时候把消息发到这里面</em>。</p><p>终端里输出如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screen-Shot-2019-08-07-at-10.48.38-PM.png" class="kg-image" alt="Screen-Shot-2019-08-07-at-10.48.38-PM" width="600" height="400" loading="lazy"></figure><p>如果正常，使用命令 <code>serverless deploy</code> 部署。如果有问题，通过 <code>serverless invoke local -f hello</code> 来debug。</p><h2 id="-slash-command">添加 slash command</h2><p>最后一件事就是添加 slash command！返回 AWS Lambda 函数的首页，找到 “Add trigger” 按钮：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-70.png" class="kg-image" alt="image-70" width="600" height="400" loading="lazy"></figure><p>我们将要添加 API Gateway（其实已经存在了）。</p><p>单击按钮打开 “Add trigger” 页，在列表中选择 "API Gateway"：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-71.png" class="kg-image" alt="image-71" width="600" height="400" loading="lazy"></figure><p>按下图填写信息：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-72.png" class="kg-image" alt="image-72" width="600" height="400" loading="lazy"></figure><p>这个 API 会开放使用，如果用于生产环境，需要和团队讨论一下协议标准。”Add“ API，会收到一个 API endpoint。记住它，在下一步会用到。</p><p>返回 slack app 添加 slash 命令：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-73.png" class="kg-image" alt="image-73" width="600" height="400" loading="lazy"></figure><p>点击 ”Create New Command“，会弹出一个新窗口来创建命令。下面是我的填写：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot_2019-08-07-Slack-API-Applications-lekha_test-Slack-1-.png" class="kg-image" alt="Screenshot_2019-08-07-Slack-API-Applications-lekha_test-Slack-1-" width="600" height="400" loading="lazy"></figure><p>”command“ 和 ”short description“ 可以随意填写，但是 ”request URL“，需要填写刚才的 API endpoint。</p><p>最后，返回代码做最后的调整。如果尝试使用 slash command，会返回错误 - 这是因为 slack 预期收到一个 response，AWS 也预期 endpoint 触达时返回一个响应。修改代码返回 <code>callback</code>（<a href="https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html">文档</a>）</p><pre><code>module.exports.hello = (event,context,callback) =&gt; {
  getRon(callback);
};
</code></pre><p>修改 <code>getRon</code> 返回 callback：</p><pre><code>function getRon(callback) {
  request('https://ron-swanson-quotes.herokuapp.com/v2/quotes', function (err, resp, body) {
    console.log('error:', err)
    console.log('statusCode:', resp &amp;&amp; resp.statusCode)
    console.log('body', body)
    callback(null, SUCCESS_RESPONSE)
    postRon(body.substring(2, body.length - 2))
  })
}
</code></pre><p>在文件顶部添加 <code>SUCCESS_RESPONSE</code>:</p><pre><code>const SUCCESS_RESPONSE = {
  statusCode: 200,
  body: null
}
</code></pre><p>可以把 callback 放在 &nbsp;<code>postRon</code> 里 - 具体取决于代码。</p><p>我的代码如下：</p><pre><code>'use strict';
let request = require('request');
const SLACK_OAUTH_TOKEN = OAUTH_TOKEN
const SUCCESS_RESPONSE = {
  statusCode: 200,
  body: null
}
module.exports.hello = (event,context,callback) =&gt; {
  getRon(callback);
};
function getRon(callback) {
  request('https://ron-swanson-quotes.herokuapp.com/v2/quotes', function (err, resp, body) {
    console.log('error:', err)
    console.log('statusCode:', resp &amp;&amp; resp.statusCode)
    console.log('body', body)
    callback(null, SUCCESS_RESPONSE)
    postRon(body.substring(2, body.length - 2))
  })
}
function postRon(quote) {
  let options = {
    url: 'https://slack.com/api/chat.postMessage',
    headers: {
      'Accept': 'application/json',
    },
    method: 'POST',
    form: {
      token: SLACK_OAUTH_TOKEN,
      channel: 'general',
      text: quote,
    }
  }

</code></pre><p>现在可以再 slack 里面使用 <code>/ron</code> 命令获取 Ron Swanson 的名言啦。如果有问题，可以使用 Cloudwatch 日志来看一下哪里出了问题：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot_2019-08-07-Lambda-Management-Console-1-.png" class="kg-image" alt="Screenshot_2019-08-07-Lambda-Management-Console-1-" width="600" height="400" loading="lazy"></figure><p>代码现在可以运行，我们已经 hardcoded 了 channel name。但是实际上我们想在任何发送 <code>/ron</code> 的 channel 返回名言。</p><p>在函数里面使用 event。</p><pre><code>module.exports.hello = (event,context,callback) =&gt; {
  console.log(event)
  getRon(callback);
};
</code></pre><p>使用 <code>/ron</code> 来运行函数，然后检查 Cloudwatch 日志来看控制台输出了什么（可能会需要刷新）。检查最新的日志会看到如下：</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-74.png" class="kg-image" alt="image-74" width="600" height="400" loading="lazy"></figure><p>列表的第一项（也就是 "resource"、"path"，等）是 event，如果展开它，你会发现一长列表东西，我们关注的是在底部的 “body”。</p><figure class="kg-card kg-image-card"><img src="https://www.freecodecamp.org/news/content/images/2019/08/image-75.png" class="kg-image" alt="image-75" width="600" height="400" loading="lazy"></figure><p>waldo 在哪里: 发现 param 版本</p><p>Body 是含有一些相关信息的字符串，其中的一个是 “channel_id”。可以使用 channel_id （或者 channel_name）做为参数传入创建 Slack 信息的函数。为了方便，直接给出获取该参数方法：<code>event.body.slit("&amp;")[3].split("=")[1]</code>，这会返回 channel_id。hardcoded 了一下，第三个值就是 channel_id。</p><p>Now, we can alter our code to save that string as a variable:</p><p>现在，可以获取到的字符串保存为一个变量：</p><p><code>let channel = 'general'</code>（做为 fallback）</p><pre><code>module.exports.hello = (event,context,callback) =&gt; {
  console.log(event)
  channel = event.body.split("&amp;")[3].split("=")[1]
  console.log(context)
  getGoat(callback);
};
</code></pre><p>以及 <code>postRon</code>:</p><pre><code>  let options = {
    url: 'https://slack.com/api/chat.postMessage',
    headers: {
      'Accept': 'application/json',
    },
    method: 'POST',
    form: {
      token: SLACK_OAUTH_TOKEN,
      channel: channel,
      text: quote,
    }
  }
</code></pre><p>可选的 psotRon 里的 var</p><p>最后，如果在 workspace 的任何 channel 使用 slack command，会看到 Ron Swanson 的名言。如果没有，就像之前说的那样，最好的 debug serverless app 的工具是 <code>serverless invoke local -f &lt;function name&gt;</code> 以及 Cloudwatch 日志。</p><p>希望你能成功的创建 Slack 应用！我已经在文末附了相关资料和背景阅读。希望能够解决你的问题。</p><p><em>Final Repo with code:</em> <a href="https://github.com/lsurasani/ron-swanson-slack-app/">https://github.com/lsurasani/ron-swanson-slack-app/</a></p><p>原文：<a href="https://www.freecodecamp.org/news/make-a-serverless-slack-app/">https://www.freecodecamp.org/news/make-a-serverless-slack-app/</a>，作者：Lekha Surasani</p> ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
