如何在Ubuntu 20.04上的Python中构建Slackbot

The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

作者选择了Tech Education Fund作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

Slack is a communication platform designed for workplace productivity. It includes features such as direct messaging, public and private channels, voice and video calls, and bot integrations. A Slackbot is an automated program that can perform a variety of functions in Slack, from sending messages to triggering tasks to alerting on certain events.

Slack是旨在提高工作效率的通信平台。 它包括直接消息传递,公共和私人频道,语音和视频通话以及漫游器集成等功能。 Slackbot是一个自动化程序,可以在Slack中执行各种功能,从发送消息到触发任务再到在某些事件时发出警报。

In this tutorial you will build a Slackbot in the Python programming language. Python is a popular language that prides itself on simplicity and readability. Slack provides a rich Python Slack API for integrating with Slack to perform common tasks such as sending messages, adding emojis to messages, and much more. Slack also provides a Python Slack Events API for integrating with events in Slack, allowing you to perform actions on events such as messages and mentions.

在本教程中,您将使用Python编程语言构建一个Slackbot。 Python是一种流行的语言,以简单性和可读性为荣。 Slack提供了丰富的Python Slack API,用于与Slack集成以执行常见的任务,例如发送消息,向消息中添加表情符号等等。 Slack还提供了一个Python Slack Events API,用于与Slack中的事件集成,从而使您可以对消息和提及等事件执行操作。

As a fun proof-of-concept that will demonstrate the power of Python and its Slack APIs, you will build a CoinBot—a Slackbot that monitors a channel and, when triggered, will flip a coin for you. You can then modify your CoinBot to fulfill any number of slightly more practical applications.

作为一个有趣的概念验证,它将演示Python及其Slack API的功能,您将构建一个CoinBot一个Slackbot,它监视一个频道,并在触发时为您掷硬币。 然后,您可以修改您的CoinBot以实现任何数量稍多的实际应用程序。

Note that this tutorial uses Python 3 and is not compatible with Python 2.

请注意,本教程使用Python 3,并且与Python 2不兼容。

先决条件 (Prerequisites)

In order to follow this guide, you’ll need:

为了遵循本指南,您需要:

  • A Slack Workspace that you have the ability to install applications into. If you created the workspace you have this ability. If you don’t already have one, you can create one on the Slack website.

    您可以将应用程序安装到的Slack工作区。 如果创建了工作空间,则具有此功能。 如果您还没有,则可以在Slack网站上创建一个。

  • (Optional) A server or computer with a public IP address for development. We recommend a fresh installation of Ubuntu 20.04, a non-root user with sudo privileges, and SSH enabled. You can follow this guide to initialize your server and complete these steps.

    (可选)具有用于开发的公共IP地址的服务器或计算机。 我们建议全新安装Ubuntu 20.04,具有sudo特权的非root用户并启用SSH。 您可以按照本指南初始化服务器并完成这些步骤

You may want to test this tutorial on a server that has a public IP address. Slack will need to be able to send events such as messages to your bot. If you are testing on a local machine you will need to port forward traffic through your firewall to your local system. If you are looking for a way to develop on a cloud server, check out this tutorial on How To Use Visual Studio Code for Remote Development via the Remote-SSH Plugin.

您可能要在具有公共IP地址的服务器上测试本教程。 Slack将需要能够将诸如消息之类的事件发送到您的机器人。 如果要在本地计算机上进行测试,则需要将通过防火墙的转发流量移植到本地系统。 如果您正在寻找在云服务器上进行开发的方法,请查看有关如何通过Remote-SSH插件使用Visual Studio Code进行远程开发的本教程。

第1步-在Slack UI中创建Slackbot (Step 1 — Creating the Slackbot in the Slack UI)

First create your Slack app in the Slack API Control Panel. Log in to your workspace in Slack via a web browser and navigate to the API Control Panel. Now click on the Create an App button.

首先在Slack API控制面板中创建您的Slack应用。 通过Web浏览器登录到Slack中的工作区,然后导航到API控制面板 。 现在单击创建应用程序按钮。

Next you’ll be prompted for the name of your app and to select a development Slack workspace. For this tutorial, name your app CoinBot and select a workspace you have admin access to. Once you have done this click on the Create App button.

接下来,将提示您输入应用程序的名称,并选择一个开发Slack工作区。 在本教程中,将您的应用CoinBot并选择您具有管理员访问权限的工作区。 完成此操作后,单击“ 创建应用程序”按钮。

Once your app is created you’ll be presented with the following default app dashboard. This dashboard is where you manage your app by setting permissions, subscribing to events, installing the app into workspaces, and more.

创建应用后,系统将为您显示以下默认应用信息中心。 您可以在此信息中心通过设置权限,订阅事件,将应用程序安装到工作区等来管理应用程序。

In order for your app to be able to post messages to a channel you need to grant the app permissions to send messages. To do this, click the Permissions button in the control panel.

为了使您的应用能够将消息发布到某个频道,您需要授予该应用发送消息的权限。 为此,请单击控制面板中的“ 权限”按钮。

When you arrive at the OAuth & Permissions page, scroll down until you find the Scopes section of the page. Then find the Bot Token Scopes subsection in the scope and click on Add an OAuth Scope button.

到达“ OAuth和权限”页面时,向下滚动直到找到页面的“ 范围”部分。 然后在范围内找到Bot令牌范围小节,然后单击添加OAuth范围按钮。

Click on that button and then type chat:write. Select that permission to add it to your bot. This will allow the app to post messages to channels that it can access. For more information on the available permissions refer to Slack’s Documentation.

单击该按钮,然后键入chat:write 。 选择该权限以将其添加到您的机器人中。 这将允许该应用将消息发布到它可以访问的频道。 有关可用权限的更多信息,请参阅Slack文档

Now that you’ve added the appropriate permission it is time to install your app into your Slack workspace. Scroll back up on the OAuth & Permissions page and click the Install App to Workspace button at the top.

现在,您已经添加了适当的权限,是时候将您的应用程序安装到Slack工作空间中了。 在“ OAuth和权限”页面上向上滚动并单击顶部的“ 将应用程序安装到工作区”按钮。

Click this button and review the actions that the app can perform in the channel. Once you are satisfied, click the Allow button to finish the installation.

单击此按钮并查看应用程序可以在通道中执行的操作。 满意后,单击“ 允许”按钮以完成安装。

Once the bot is installed you’ll be presented with a Bot User OAuth Access Token for your app to use when attempting to perform actions in the workspace. Go ahead and copy this token; you’ll need it later.

机器人安装完成后,系统会为您提供Bot用户OAuth访问令牌,供您的应用在尝试在工作区中执行操作时使用。 继续并复制此令牌; 您稍后将需要它。

Finally, add your newly installed bot into a channel within your workspace. If you haven’t created a channel yet you can use the #general channel that is created by default in your Slack workspace. Locate the app in the Apps section of the navigation bar in your Slack client and click on it. Once you’ve done that open the Details menu in the top right hand side. If your Slack client isn’t full-screened it will look like an i in a circle.

最后,将新安装的漫游器添加到工作区中的一个通道中。 如果尚未创建频道,则可以使用Slack工作空间中默认创建的#general频道。 在Slack客户端的导航栏的“ 应用程序”部分中找到该应用程序,然后单击它。 完成后,打开右上角的“ 详细信息”菜单。 如果您的客户端松弛不完全屏蔽它看起来像i转了一圈。

To finish adding your app to a channel, click on the More button represented by three dots in the details page and select Add this app to a channel…. Type your channel into the modal that appears and click Add.

要将应用添加到频道,请在详细信息页面中单击三个按钮代表的更多按钮,然后选择将此应用添加到频道… 。 在显示的模式中输入您的频道,然后点击添加

You’ve now successfully created your app and added it to a channel within your Slack workspace. After you write the code for your app it will be able to post messages in that channel. In the next section you’ll start writing the Python code that will power CoinBot.

现在,您已经成功创建了应用程序,并将其添加到了Slack工作区中的频道。 在为您的应用编写代码后,它将能够在该频道中发布消息。 在下一节中,您将开始编写将为CoinBot的Python代码。

第2步-设置Python开发人员环境 (Step 2 — Setting Up Your Python Developer Environment)

First let’s set up your Python environment so you can develop the Slackbot.

首先,让我们设置您的Python环境,以便您可以开发Slackbot。

Open a terminal and install python3 and the relevant tools onto your system:

打开一个终端并将python3和相关工具安装到您的系统上:

  • sudo apt install python3 python3-venv

    sudo apt安装python3 python3-venv

Next you will create a virtual environment to isolate your Python packages from the system installation of Python. To do this, first create a directory into which you will create your virtual environment. Make a new directory at ~/.venvs:

接下来,您将创建一个虚拟环境,以将Python软件包与Python的系统安装隔离开。 为此,首先创建一个目录,您将在其中创建虚拟环境。 在~/.venvs一个新目录:

  • mkdir ~/.venvs

    mkdir〜/ .venvs

Now create your Python virtual environment:

现在创建您的Python虚拟环境:

  • python3 -m venv ~/.venvs/slackbot

    python3 -m venv〜/ .venvs / slackbot

Next, activate your virtual environment so you can use its Python installation and install packages:

接下来,激活您的虚拟环境,以便您可以使用其Python安装并安装软件包:

  • source ~/.venvs/slackbot/bin/activate

    源〜/ .venvs / slackbot / bin / activate

Your shell prompt will now show the virtual environment in parenthesis. It will look something like this:

现在,您的shell提示符将在括号中显示虚拟环境。 它看起来像这样:

Now use pip to install the necessary Python packages into your virtual environment:

现在使用pip将必要的Python软件包安装到您的虚拟环境中:

  • pip install slackclient slackeventsapi Flask

    点安装slackclient slackeventsapi烧瓶

slackclient and slackeventsapi facilitate Python’s interaction with Slack’s APIs. Flask is a popular micro web framework that you will use to deploy your app:

slackclientslackeventsapi促进了Python与Slack API的交互。 Flask是一个流行的微型Web框架,可用于部署应用程序:

Now that you have your developer environment set up, you can start writing your Python Slackbot:

现在,您已经设置了开发人员环境,可以开始编写Python Slackbot了:

步骤3 —在Python中创建Slackbot消息类 (Step 3 — Creating the Slackbot Message Class in Python)

Messages in Slack are sent via a specifically formatted JSON payload. This is an example of the JSON that your Slackbot will craft and send as a message:

Slack中的消息通过特定格式的JSON有效负载发送。 这是您的Slackbot将制作并作为消息发送的JSON的示例:

{
   "channel":"channel",
   "blocks":[
      {
         "type":"section",
         "text":{
            "type":"mrkdwn",
            "text":"Sure! Flipping a coin....\n\n"
         }
      },
      {
         "type":"section",
         "text":{
            "type":"mrkdwn",
            "text":"*flips coin* The result is Tails."
         }
      }
   ]
}

You could manually craft this JSON and send it, but instead let’s build a Python class that not only crafts this payload, but also simulates a coin flip.

您可以手动制作并发送该JSON,但让我们构建一个Python类,该类不仅可以制作此有效载荷,还可以模拟硬币翻转。

First use the touch command to create a file named coinbot.py:

首先使用touch命令创建一个名为coinbot.py的文件:

  • touch coinbot.py

    触摸coinbot.py

Next, open this file with nano or your favorite text editor:

接下来,使用nano或您喜欢的文本编辑器打开此文件:

  • nano coinbot.py

    纳米硬币机器人

Now add the following lines of code to import the relevant libraries for your app. The only library you need for this class is the random library from the Python Standard Library. This library will allow us to simulate a coin flip.

现在,添加以下代码行以为您的应用导入相关的库。 此类所需的唯一库是Python标准库中的random库。 该库将允许我们模拟硬币翻转。

Add the following lines to coinbot.py to import all of the necessary libraries:

coinbot.py添加到coinbot.py以导入所有必需的库:

coinbot.py
coinbot.py
# import the random library to help us generate the random numbers
import random

Next, create your CoinBot class and an instance of this class to craft the message payload. Add the following lines to coinbot.py to create the CoinBot class:

接下来,创建您的CoinBot类和该类的实例以制作消息有效负载。 coinbot.py添加到coinbot.py以创建CoinBot类:

coinbot.py
coinbot.py
...
class CoinBot:

Now indent by one and create the constants, constructors, and methods necessary for your class. First let’s create the constant that will hold the base of your message payload. This section specifies that this constant is of the section type and that the text is formatted via markdown. It also specifies what text you wish to display. You can read more about the different payload options in the official Slack message payload documentation.

现在缩进一个并创建类所需的常量,构造函数和方法。 首先,让我们创建一个常量,该常量将保存消息有效负载的基础。 此部分指定此常量为部分类型,并且文本通过markdown格式化。 它还指定您要显示的文本。 您可以在Slack消息有效负载官方文档中了解有关不同有效负载选项的更多信息

Append the following lines to coinbot.py to create the base template for the payload:

coinbot.py添加到coinbot.py以创建有效内容的基本模板:

coinbot.py
coinbot.py
...
    # Create a constant that contains the default text for the message
    COIN_BLOCK = {
        "type": "section",
        "text": {
            "type": "mrkdwn",
            "text": (
                "Sure! Flipping a coin....\n\n"
            ),
        },
    }

Next create a constructor for your class so that you can create a separate instance of your bot for every request. Don’t worry about memory overhead here; the Python garbage collector will clean up these instances once they are no longer needed. This code sets the recipient channel based on a parameter passed to the constructor.

接下来,为您的类创建一个构造函数,以便您可以为每个请求创建一个单独的bot实例。 不用担心这里的内存开销。 一旦不再需要这些实例,Python垃圾收集器就会清理它们。 此代码根据传递给构造函数的参数设置接收方通道。

Append the following lines to coinbot.py to create the constructor:

coinbot.py添加到coinbot.py以创建构造函数:

coinbot.py
coinbot.py
...
    # The constructor for the class. It takes the channel name as the a
    # parameter and sets it as an instance variable.
    def __init__(self, channel):
        self.channel = channel

Now write the code that simulates to flip a coin. We’ll randomly generate a one or zero, representing heads or tails respectively.

现在,编写模拟掷硬币的代码。 我们将随机生成一个1或0,分别代表正面或反面。

Append the following lines to coinbot.py to simulate the coin flip and return the crafted payload:

coinbot.py添加到coinbot.py以模拟硬币翻转并返回精心制作的有效载荷:

coinbot.py
coinbot.py
...
    # Generate a random number to simulate flipping a coin. Then return the 
    # crafted slack payload with the coin flip message.
    def _flip_coin(self):
        rand_int =  random.randint(0,1)
        if rand_int == 0:
            results = "Heads"
        else:
            results = "Tails"

        text = f"The result is {results}"

        return {"type": "section", "text": {"type": "mrkdwn", "text": text}},

Finally, create a method that crafts and returns the entire message payload, including the data from your constructor, by calling your _flip_coin method.

最后,通过调用_flip_coin方法,创建一个可以制作并返回整个消息有效负载(包括来自构造函数的数据)的方法。

Append the following lines to coinbot.py to create the method that will generate the finished payload:

coinbot.py添加到coinbot.py以创建将生成完成的有效负载的方法:

coinbot.py
coinbot.py
...
    # Craft and return the entire message payload as a dictionary.
    def get_message_payload(self):
        return {
            "channel": self.channel,
            "blocks": [
                self.COIN_BLOCK,
                *self._flip_coin(),
            ],
        }

You are now finished with the CoinBot class and it is ready for testing. Before continuing, verify that your finished file, coinbot.py, contains the following:

现在,您已经完成了CoinBot类,并且可以进行测试了。 在继续之前,请验证完成的文件coinbot.py包含以下内容:

coinbot.py
coinbot.py
# import the random library to help us generate the random numbers
import random

# Create the CoinBot Class
class CoinBot:

    # Create a constant that contains the default text for the message
    COIN_BLOCK = {
        "type": "section",
        "text": {
            "type": "mrkdwn",
            "text": (
                "Sure! Flipping a coin....\n\n"
            ),
        },
    }

    # The constructor for the class. It takes the channel name as the a 
    # parameter and then sets it as an instance variable
    def __init__(self, channel):
        self.channel = channel

    # Generate a random number to simulate flipping a coin. Then return the 
    # crafted slack payload with the coin flip message.
    def _flip_coin(self):
        rand_int =  random.randint(0,1)
        if rand_int == 0:
            results = "Heads"
        else:
            results = "Tails"

        text = f"The result is {results}"

        return {"type": "section", "text": {"type": "mrkdwn", "text": text}},

    # Craft and return the entire message payload as a dictionary.
    def get_message_payload(self):
        return {
            "channel": self.channel,
            "blocks": [
                self.COIN_BLOCK,
                *self._flip_coin(),
            ],
        }

Save and close the file.

保存并关闭文件。

Now that you have a Python class ready to do the work for your Slackbot, let’s ensure that this class produces a useful message payload and that you can send it to your workspace.

现在,您已经准备好一个Python类来为Slackbot进行工作,让我们确保该类产生有用的消息有效负载并将其发送到工作区。

第4步-测试您的消息 (Step 4 — Testing Your Message)

Now let’s test that this class produces a proper payload. Create a file named coinbot_test.py:

现在让我们测试一下此类是否产生了适当的有效负载。 创建一个名为coinbot_test.py的文件:

  • nano coinbot_test.py

    纳米coinbot_test.py

Now add the following code. Be sure to change the channel name in the instantiation of the coinbot class coin_bot = coinbot("#YOUR_CHANNEL_HERE"). This code will create a Slack client in Python that will send a message to the channel you specify that you have already installed the app into:

现在添加以下代码。 确保在coinbot类coin_bot = coinbot("# YOUR_CHANNEL_HERE ")的实例化中更改通道名称 。 此代码将在Python中创建一个Slack客户端,它将向您指定已将应用程序安装到的通道发送消息:

coinbot_test.py
coinbot_test.py
from slack import WebClient
from coinbot import CoinBot
import os

# Create a slack client
slack_web_client = WebClient(token=os.environ.get("SLACK_TOKEN"))

# Get a new CoinBot
coin_bot = CoinBot("#YOUR_CHANNEL_HERE")

# Get the onboarding message payload
message = coin_bot.get_message_payload()

# Post the onboarding message in Slack
slack_web_client.chat_postMessage(**message)

Save and close the file.

保存并关闭文件。

Before you can run this file you will need to export the Slack token that you saved in Step 1 as an environment variable:

在运行此文件之前,您需要将在步骤1中保存的Slack令牌导出为环境变量:

  • export SLACK_TOKEN="your_bot_user_token"

    出口SLACK_TOKEN =“ your_bot_user_token ”

Now test this file and verify that the payload is produced and sent by running the following script in your terminal. Make sure that your virtual environment is activated. You can verify this by seeing the (slackbot) text at the front of your bash prompt. Run this command you will receive a message from your Slackbot with the results of a coin flip:

现在测试此文件,并通过在终端中运行以下脚本来验证是否产生并发送了有效负载。 确保您的虚拟环境已激活。 您可以通过查看bash提示符前面的(slackbot)文本来验证这一点。 运行以下命令,您将收到来自Slackbot的消息,其中包含硬币翻转的结果:

  • python coinbot_test.py

    python coinbot_test.py

Check the channel that you installed your app into and verify that your bot did indeed send the coin flip message. Your result will be heads or tails.

检查您安装应用程序的渠道,并验证您的机器人确实确实发送了硬币翻转消息。 您的结果将是正面或反面。

Now that you’ve verified that your Slackbot can flip a coin, create a message, and deliver the message, let’s create a Flask to perpetually run this app and make it simulate a coin flip and share the results whenever it sees certain text in messages sent in the channel.

既然您已经验证了Slackbot可以翻转硬币,创建消息并传递消息,那么让我们创建一个Flask来永久运行此应用程序,并使它模拟硬币翻转并在每次看到消息中的某些文本时共享结果在频道中发送。

第5步—创建一个Flask应用程序以运行您的Slackbot (Step 5 — Creating a Flask Application to Run Your Slackbot)

Now that you have a functioning application that can send messages to your Slack workspace, you need to create a long running process so your bot can listen to messages sent in the channel and reply to them if the text meets certain criteria. You’re going to use the Python web framework Flask to run this process and listen for events in your channel.

既然您已经拥有一个可以正常运行的应用程序,可以将消息发送到Slack工作区,那么您需要创建一个长时间运行的进程,以便您的机器人可以侦听通道中发送的消息,并在文本满足特定条件时对其进行回复。 您将使用Python网络框架Flask来运行此过程,并监听频道中的事件。

In this section you will be running your Flask application from a server with a public IP address so that the Slack API can send you events. If you are running this locally on your personal workstation you will need to forward the port from your personal firewall to the port that will be running on your workstation. These ports can be the same, and this tutorial will be set up to use port 3000.

在本部分中,您将从带有公共IP地址的服务器上运行Flask应用程序,以便Slack API可以向您发送事件。 如果您是在个人工作站上本地运行此端口,则需要将端口从个人防火墙转发到将在工作站上运行的端口。 这些端口可以相同,并且本教程将设置为使用端口3000

First adjust your firewall settings to allow traffic through port 3000:

首先调整防火墙设置,以允许通过端口3000进行通信:

  • sudo ufw allow 3000

    须藤ufw允许3000

Now check the status of ufw:

现在检查ufw的状态:

  • sudo ufw status

    sudo ufw状态

You will see an output like this:

您将看到类似以下的输出:


   
   
Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 3000 ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) 3000 (v6) ALLOW Anywhere (v6)

Now create the file for your Flask app. Name this file app.py:

现在为Flask应用创建文件。 将此文件app.py

  • touch app.py

    触摸app.py

Next, open this file in your favorite text editor:

接下来,在您喜欢的文本编辑器中打开此文件:

  • nano app.py

    纳米应用

Now add the following import statements. You’ll import the following libraries for the following reasons:

现在添加以下导入statements 。 出于以下原因,您将导入以下库:

  • import os - To access environment variables

    import os访问环境变量

  • import logging - To log the events of the app

    import logging -记录应用程序的事件

  • from flask import Flask - To create a Flask app

    from flask import Flask创建Flask应用

  • from slack import WebClient - To send messages via Slack

    from slack import WebClient通过Slack发送消息

  • from slackeventsapi import SlackEventAdapter - To receive events from Slack and process them

    from slackeventsapi import SlackEventAdapter从Slack接收事件并处理它们

  • from coinbot import CoinBot - To create an instance of your CoinBot and generate the message payload.

    from coinbot import CoinBot创建from coinbot import CoinBot的实例并生成消息有效负载。

Append the following lines to app.py to import all of the necessary libraries:

app.py添加到app.py以导入所有必需的库:

app.py
app.py
import os
import logging
from flask import Flask
from slack import WebClient
from slackeventsapi import SlackEventAdapter
from coinbot import CoinBot

Now create your Flask app and register a Slack Event Adapter to your Slack app at the /slack/events endpoint. This will create a route in your Slack app where Slack events will be sent and ingested. To do this you will need to get another token from your Slack app, which you will do later in the tutorial. Once you get this variable you will export it as an environment variable named SLACK_EVENTS_TOKEN. Go ahead and write your code to read it in when creating the SlackEventAdapter, even though you haven’t set the token yet.

现在创建您的Flask应用程序,并在/slack/events端点上向Slack应用程序注册一个Slack事件适配器。 这将在您的Slack应用中创建一条路由,在该路由中将发送和接收Slack事件。 为此,您需要从Slack应用程序中获取另一个令牌,您将在本教程的后面部分进行操作。 获得此变量后,将其导出为名为SLACK_EVENTS_TOKEN的环境变量。 继续并编写代码以在创建SlackEventAdapter时将其读SlackEventAdapter ,即使您尚未设置令牌也是如此。

Append the following lines to app.py to create the Flask app and register the events adapter into this app:

app.py添加到app.py以创建Flask应用并将事件适配器注册到该应用中:

app.py
app.py
...
# Initialize a Flask app to host the events adapter
app = Flask(__name__)

# Create an events adapter and register it to an endpoint in the slack app for event ingestion.
slack_events_adapter = SlackEventAdapter(os.environ.get("SLACK_EVENTS_TOKEN"), "/slack/events", app)

Next create a web client object that will allow your app to perform actions in the workspace, specifically to send messages. This is similar to what you did when you tested your coinbot.py file previously.

接下来,创建一个Web客户端对象,该对象将允许您的应用在工作区中执行操作,特别是发送消息。 这类似于您先前测试coinbot.py文件时所做的coinbot.py

Append the following line to app.py to create this slack_web_client:

app.py添加到app.py以创建slack_web_client

app.py
app.py
...
# Initialize a Web API client
slack_web_client = WebClient(token=os.environ.get("SLACK_TOKEN"))

Now create a function that can be called that will create an instance of CoinBot, and then use this instance to create a message payload and pass the message payload to the Slack web client for delivery. This function will take in a single parameter, channel, which will specify what channel receives the message.

现在创建一个可以调用的函数,该函数将创建CoinBot的实例,然后使用该实例创建消息有效负载,并将消息有效负载传递给Slack Web客户端进行传递。 此函数将接受单个参数channel ,它将指定接收消息的通道。

Append the following lines to app.py to create this function:

app.py添加到app.py以创建此功能:

app.py
app.py
...
def flip_coin(channel):
    """Craft the CoinBot, flip the coin and send the message to the channel
    """
    # Create a new CoinBot
    coin_bot = CoinBot(channel)

    # Get the onboarding message payload
    message = coin_bot.get_message_payload()

    # Post the onboarding message in Slack
    slack_web_client.chat_postMessage(**message)

Now that you have created a function to handle the messaging aspects of your app, create one that monitors Slack events for a certain action and then executes your bot. You’re going to configure your app to respond with the results of a simulated coin flip when it sees the phrase “Hey Sammy, Flip a coin”. You’re going to accept any version of this—case won’t prevent the app from responding.

现在,您已经创建了一个处理应用程序消息传递方面的功能,创建一个监视Slack事件以执行特定操作的功能,然后执行您的机器人。 您将配置您的应用程序,使其在看到短语“嘿萨米,翻转硬币”时以模拟硬币翻转的结果做出响应。 您将接受此版本的任何版本,这种情况不会阻止应用程序响应。

First decorate your function with the @slack_events_adapter.on syntax that allows your function to receive events. Specify that you only want the message events and have your function accept a payload parameter containing all of the necessary Slack information. Once you have this payload you will parse out the text and analyze it. Then, if it receives the activation phrase, your app will send the results of a simulated coin flip.

首先使用@slack_events_adapter.on语法修饰您的函数,该语法允许您的函数接收事件。 指定您只想要message事件,并让您的函数接受包含所有必要的Slack信息的有效负载参数。 拥有此有效负载后,您将解析出文本并进行分析。 然后,如果收到激活短语,则您的应用程序将发送模拟硬币翻转的结果。

Append the following code to app.py to receive, analyze, and act on incoming messages:

将以下代码附加到app.py以接收,分析传入消息并对其进行处理:

app.py
app.py
# When a 'message' event is detected by the events adapter, forward that payload
# to this function.
@slack_events_adapter.on("message")
def message(payload):
    """Parse the message event, and if the activation string is in the text,
    simulate a coin flip and send the result.
    """

    # Get the event data from the payload
    event = payload.get("event", {})

    # Get the text from the event that came through
    text = event.get("text")

    # Check and see if the activation phrase was in the text of the message.
    # If so, execute the code to flip a coin.
    if "hey sammy, flip a coin" in text.lower():
        # Since the activation phrase was met, get the channel ID that the event
        # was executed on
        channel_id = event.get("channel")

        # Execute the flip_coin function and send the results of
        # flipping a coin to the channel
        return flip_coin(channel_id)

Finally, create a main section that will create a logger so you can see the internals of your application as well as launch the app on your external IP address on port 3000. In order to ingest the events from Slack, such as when a new message is sent, you must test your application on a public-facing IP address.

最后,创建一个main部分,它将创建一个记录器,以便您可以查看应用程序的内部以及在端口3000外部IP地址上启动该应用程序。 为了从Slack接收事件,例如发送新消息时,必须在面向公众的IP地址上测试应用程序。

Append the following lines to app.py to set up your main section:

app.py添加到app.py以设置您的主要部分:

app.py
app.py
if __name__ == "__main__":
    # Create the logging object
    logger = logging.getLogger()

    # Set the log level to DEBUG. This will increase verbosity of logging messages
    logger.setLevel(logging.DEBUG)

    # Add the StreamHandler as a logging handler
    logger.addHandler(logging.StreamHandler())

    # Run your app on your externally facing IP address on port 3000 instead of
    # running it on localhost, which is traditional for development.
    app.run(host='0.0.0.0', port=3000)

You are now finished with the Flask app and it is ready for testing. Before you move on verify that your finished file, app.py contains the following:

现在,您已经完成了Flask应用程序,可以进行测试了。 在继续进行操作之前,请先确认app.py包含以下内容:

app.py
app.py
import os
import logging
from flask import Flask
from slack import WebClient
from slackeventsapi import SlackEventAdapter
from coinbot import CoinBot

# Initialize a Flask app to host the events adapter
app = Flask(__name__)
# Create an events adapter and register it to an endpoint in the slack app for event injestion.
slack_events_adapter = SlackEventAdapter(os.environ.get("SLACK_EVENTS_TOKEN"), "/slack/events", app)

# Initialize a Web API client
slack_web_client = WebClient(token=os.environ.get("SLACK_TOKEN"))

def flip_coin(channel):
    """Craft the CoinBot, flip the coin and send the message to the channel
    """
    # Create a new CoinBot
    coin_bot = CoinBot(channel)

    # Get the onboarding message payload
    message = coin_bot.get_message_payload()

    # Post the onboarding message in Slack
    slack_web_client.chat_postMessage(**message)


# When a 'message' event is detected by the events adapter, forward that payload
# to this function.
@slack_events_adapter.on("message")
def message(payload):
    """Parse the message event, and if the activation string is in the text, 
    simulate a coin flip and send the result.
    """

    # Get the event data from the payload
    event = payload.get("event", {})

    # Get the text from the event that came through
    text = event.get("text")

    # Check and see if the activation phrase was in the text of the message.
    # If so, execute the code to flip a coin.
    if "hey sammy, flip a coin" in text.lower():
        # Since the activation phrase was met, get the channel ID that the event
        # was executed on
        channel_id = event.get("channel")

        # Execute the flip_coin function and send the results of
        # flipping a coin to the channel
        return flip_coin(channel_id)

if __name__ == "__main__":
    # Create the logging object
    logger = logging.getLogger()

    # Set the log level to DEBUG. This will increase verbosity of logging messages
    logger.setLevel(logging.DEBUG)

    # Add the StreamHandler as a logging handler
    logger.addHandler(logging.StreamHandler())

    # Run our app on our externally facing IP address on port 3000 instead of
    # running it on localhost, which is traditional for development.
    app.run(host='0.0.0.0', port=3000)

Save and close the file.

保存并关闭文件。

Now that your Flask app is ready to serve your application let’s test it out.

现在,您的Flask应用程序已准备就绪,可以为您的应用程序提供服务了,让我们对其进行测试。

第6步-运行Flask应用 (Step 6 — Running Your Flask App)

Finally, bring everything together and execute your app.

最后,将所有内容组合在一起并执行您的应用程序。

First, add your running application as an authorized handler for your Slackbot.

首先,将正在运行的应用程序添加为Slackbot的授权处理程序。

Navigate to the Basic Information section of your app in the Slack UI. Scroll down until you find the App Credentials section.

Slack UI中导航至应用程序的“ 基本信息”部分。 向下滚动,直到找到“ 应用程序凭据”部分。

Copy the Signing Secret and export it as the environment variable SLACK_EVENTS_TOKEN:

复制签名密钥并将其导出为环境变量SLACK_EVENTS_TOKEN

  • export SLACK_EVENTS_TOKEN="MY_SIGNING_SECRET_TOKEN"

    出口SLACK_EVENTS_TOKEN =“ MY_SIGNING_SECRET_TOKEN ”

With this you have all the necessary API tokens to run your app. Refer to Step 1 if you need a refresher on how to export your SLACK_TOKEN. Now you can start your app and verify that it is indeed running. Ensure that your virtual environment is activated and run the following command to start your Flask app:

有了这个,您就有了运行应用程序所需的所有API令牌。 如果需要有关如何导出SLACK_TOKEN的更新,请参考步骤1。 现在,您可以启动您的应用程序并验证其确实正在运行。 确保您的虚拟环境已激活,然后运行以下命令来启动Flask应用程序:

  • python3 app.py

    python3 app.py

You will see an output like this:

您将看到类似以下的输出:

(slackbot) [20:04:03] sammy:coinbot$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:3000/ (Press CTRL+C to quit)

To verify that your app is up, open a new terminal window and curl the IP address of your server with the correct port at /slack/events:

要验证您的应用已启动,请打开一个新的终端窗口,并使用/slack/events上的正确端口curl服务器的IP地址:

  • curl http://YOUR_IP_ADDRESS:3000/slack/events

    卷曲http:// YOUR_IP_ADDRESS :3000 / slack / events

curl will return the following:

curl将返回以下内容:


   
   
Output
These are not the slackbots you're looking for.

Receiving the message These are not the slackbots you're looking for., indicates that your app is up and running.

接收消息These are not the slackbots you're looking for. ,表示您的应用已启动并正在运行。

Now leave this Flask application running while you finish configuring your app in the Slack UI.

现在,在完成在Slack UI中配置应用程序后,让该Flask应用程序运行。

First grant your app the appropriate permissions so that it can listen to messages and respond accordingly. Click on Event Subscriptions in the UI sidebar and toggle the Enable Events radio button.

首先,为您的应用授予适当的权限,以便它可以收听消息并做出相应的响应。 单击UI侧栏中的“ 事件订阅” ,然后切换“ 启用事件”单选按钮。

Once you’ve done that, type in your IP address, port, and /slack/events endpoint into the Request URL field. Don’t forget the HTTP protocol prefix. Slack will make an attempt to connect to your endpoint. Once it has successfully done so you’ll see a green check mark with the word Verified next to it.

完成此操作后,在“ 请求URL”字段中输入IP地址,端口和/slack/events端点。 不要忘记HTTP协议前缀。 Slack将尝试连接到您的端点。 成功完成后,您将看到绿色的复选标记,其旁边带有“ 已验证 ”字样。

Next, expand the Subscribe to bot events and add the message.channels permission to your app. This will allow your app to receive messages from your channel and process them.

接下来,展开“ 订阅机器人事件”,然后向您的应用添加message.channels权限。 这将使您的应用可以接收您频道中的消息并进行处理。

Once you’ve done this you will see the event listed in your Subscribe to bot events section. Next click the green Save Changes button in the bottom right hand corner.

完成此操作后,您将在“ 订阅机器人事件”部分中看到该事件。 接下来,单击右下角的绿色“ 保存更改”按钮。

Once you do this you’ll see a yellow banner across the top of the screen informing you that you need to reinstall your app for the following changes to apply. Every time you change permissions you’ll need to reinstall your app. Click on the reinstall your app link in this banner to reinstall your app.

完成此操作后,您会在屏幕顶部看到一个黄色的横幅,通知您需要重新安装应用程序才能应用以下更改。 每次更改权限时,都需要重新安装应用程序。 单击此横幅中的重新安装您的应用程序链接以重新安装您的应用程序。

You’ll be presented with a confirmation screen summarizing the permissions your bot will have and asking if you want to allow its installation. Click on the green Allow button to finish the installation process.

系统将显示一个确认屏幕,概述您的机器人将具有的权限,并询问您是否要允许其安装。 单击绿色的“ 允许”按钮以完成安装过程。

Now that you’ve done this your app should be ready. Go back to the channel that you installed CoinBot into and send a message containing the phrase Hey Sammy, Flip a coin in it. Your bot will flip a coin and reply with the results. Congrats! You’ve created a Slackbot!

至此,您的应用程序应该已经准备就绪。 返回您安装CoinBot的频道,并发送一条消息,其中包含短语Hey Sammy,在其中插入硬币 。 您的机器人将掷硬币并返回结果。 恭喜! 您已经创建了一个Slackbot!

结论 (Conclusion)

Once you are done developing your application and you are ready to move it to production, you’ll need to deploy it to a server. This is necessary because the Flask development server is not a secure production environment. You’ll be better served if you deploy your app using a WSGI and maybe even securing a domain name and giving your server a DNS record. There are many options for deploying Flask applications, some of which are listed below:

开发完应用程序并准备将其移至生产环境后,您需要将其部署到服务器上。 这是必需的,因为Flask开发服务器不是安全的生产环境。 如果使用WSGI部署应用程序,甚至可以保护域名并为服务器提供DNS记录,将为您提供更好的服务。 有很多用于部署Flask应用程序的选项,下面列出其中一些:

There are many more ways to deploy your application than just these. As always, when it comes to deployments and infrastucture, do what works best for you.

除了这些以外,还有更多的方法来部署应用程序。 与往常一样,在部署和基础架构方面,请执行最适合您的工作

In any case, you now have a Slackbot that you can use to flip a coin to help you make decisions, like what to eat for lunch.

无论如何,您现在都拥有一个Slackbot,可以用来掷硬币来帮助您做出决策,例如午餐吃什么。

You can also take this base code and modify it to fit your needs, whether it be automated support, resource management, pictures of cats, or whatever you can think of. You can view the complete Python Slack API docs here.

您也可以采用此基础代码并对其进行修改以适合您的需求,无论它是自动支持,资源管理,猫的照片还是您能想到的任何东西。 您可以在此处查看完整的Python Slack API文档。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-a-slackbot-in-python-on-ubuntu-20-04

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值