博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Python和Flask的Slack API入门
阅读量:2518 次
发布时间:2019-05-11

本文共 14594 字,大约阅读时间需要 48 分钟。

The slick hosted chat application is all the rage this year. The tool’s adoption isn’t empty hype – it’s incredibly useful for communicating with and learning from fellow developers. For example, software developer communities such as , , and set up their own Slack channels.

精巧的托管聊天应用程序今年风靡一时。 该工具的采用并非吹牛,它对于与其他开发人员进行交流和向他们学习非常有用。 例如, , 和等软件开发人员社区建立了自己的Slack渠道。

However, Slack wouldn’t be that useful if it was just a glorified AOL Instant Messenger. It’s the programmatic access to retrieve and send messages with the Slack web application programming interface (API) where the power really kicks in.

但是,如果Slack只是美化的AOL Instant Messenger,那么它就不会有用。 这是使用Slack Web应用程序编程接口(API)检索和发送消息的编程访问方式,真正发挥了作用。

In this post, we’ll see how to work with Slack via the API and the official SlackClient Python helper library. We will grab an API access token and write some Python code to list, retrieve and send data through the API. Let’s dig in now!

在本文中,我们将看到如何通过API和官方的SlackClient Python帮助程序库使用Slack。 我们将获取一个API访问令牌,并编写一些Python代码以列出,检索和通过API发送数据。 让我们开始吧!

Slack Python Flask

This is a guest blog post by ​, Developer Evangelist at and author of .

这是开发人员传教士,《 作者的客座博客文章。

我们需要的工具 (Tools We’ll Need)

Several tools will be used to run the code in this blog post, including:

本博客文章中将使用几种工具来运行代码,包括:

  • A or sign up for the
  • Either Python 2 or 3
  • Official Python code library built by the Slack team
  • Slack API
  • ; if you’re unfamiliar with it, check out the , the , or
  • 一个或注册了
  • Python 2或3
  • Slack团队构建的官方Python 代码库
  • Slack API
  • ; 如果您不熟悉它,请查看 , 或

It’s also handy to have the open for reference. You can follow along by writing the code in this post or .

打开以供参考也很方便。 您可以通过在本文中编写代码来进行后续操作,也可以 。

Now that we know what tools we need to use, let’s begin by creating a new to isolate our application dependencies from other Python projects you’re working on:

现在我们知道我们需要使用什么工具,让我们开始创建一个新的 ,将我们的应用程序依赖项与您正在处理的其他Python项目隔离开:

1122

Activate the virtualenv:

激活virtualenv:

11

Depending on how your virtualenv and shell are set up, your prompt should now look something like this:

根据您的virtualenv和shell的设置方式,您的提示符现在应如下所示:

11

Keep the shell open for now as we get our Slack access established via the official slackclient API helper library built by Slack.

现在通过我们由Slack构建的官方slackclient API帮助程序库建立Slack访问,保持外壳打开状态。

There are also other fantastic Python helper libraries created by the community. For simplicity, we’re only going to install and use slackclient, but you can also try out libraries like , and once we’re done here.

社区还创建了其他出色的Python帮助程序库。 为简单起见,我们只打算安装和使用slackclient,但你也可以尝试像图书馆 , 和一次我们在这里完成。

Install the slackclient helper library into your virtualenv with pip:

使用pip将slackclient helper库安装到您的virtualenv中:

11

Now that we have the helper library installed, we need to obtain a Slack access token for our team and account.

现在我们已经安装了帮助程序库,我们需要为我们的团队和客户获取一个Slack访问令牌。

Slack Web API (The Slack Web API)

Head to the :

转到的 :

Slack Sign In

Once you’ve signed in you can scroll down on the web API page where you’ll see a button to generate test tokens:

登录后,您可以在Web API页面上向下滚动,在该页面上您会看到一个用于生成测试令牌的按钮:

Slack Test Token

Generate a test token for a Slack team on which you have administrative privileges. This token will serve fine for our development purposes in this blog post, but you can also where other users can generate tokens for authentication through their own accounts.

为您拥有管理特权的Slack团队生成测试令牌。 在本博客文章中,此令牌可以很好地用于我们的开发目的,但是您也可以 ,其他用户可以在中通过自己的帐户生成用于身份验证的令牌。

We’ll need that test token in just a moment, so keep it handy. Let’s switch into our Python environment set up so we can try out the API. With your virtualenv still active, fire up the Python REPL:

我们将在短时间内需要该测试令牌,因此请随时使用。 让我们切换到我们的Python环境设置,以便尝试API。 在您的virtualenv仍处于活动状态的情况下,启动Python REPL:

1122334455

Let’s test our API token with a test call; type the following code at the REPL prompt:

让我们通过测试调用来测试我们的API令牌; 在REPL提示符下键入以下代码:

112233

The REPL should return back something like the following dictionary if your API test with the token was successful:

如果使用令牌的API测试成功,则REPL应该返回类似以下字典的内容:

11

If you get back {u'ok': False, u'error': u'invalid_auth'} then double-check that you copied the Slack token correctly into the second line entered on the REPL.

如果返回{u'ok': False, u'error': u'invalid_auth'}然后再次检查您是否已将Slack令牌正确复制到REPL上输入的第二行中。

Enter one more quick test for our authentication with another line of code in the REPL:

在REPL中使用另一行代码为我们的身份验证输入另一个快速测试:

11

You should see another dictionary similar to this one:

您应该看到与此字典类似的另一本字典:

11

Awesome! We’re authorized to start using the Slack API through our account. Now the fun begins as we can start programmatically obtaining Slack data and handling messages!

太棒了! 我们有权通过我们的帐户开始使用Slack API。 现在,乐趣开始了,因为我们可以开始以编程方式获取Slack数据并处理消息!

Slack API基础 (Slack API Basics)

Exit out of the REPL with a quick CTRL-d or exit() command. Back on the command line, export the Slack token as an environment variable:

使用快速CTRL-d或exit()命令exit() REPL。 返回命令行,将Slack令牌导出为环境变量:

11

We’ll snag the environment variable in our Python script using the os module instead of hardcoding it into the source code.

我们将使用os模块在Python脚本中捕获环境变量,而不是将其硬编码为源代码。

Dive into your favorite text editor such as , , or so we can cut some new Python code. Create a new file named app.py and start filling it out with the following imports:

深入研究您喜欢的文本编辑器,例如 , 或以便我们可以剪切一些新的Python代码。 创建一个名为app.py的新文件,并开始使用以下导入内容进行填充:

1122

Again, the os module will be used to pull the SLACK_TOKEN environment variable we just exported. The SlackClient import should look familiar, as it is the same line we wrote earlier on the REPL:

再次, os模块将用于提取我们刚刚导出的SLACK_TOKEN环境变量。 SlackClient导入应该看起来很熟悉,因为它与我们之前在REPL上写的相同:

112233

In the above two lines, we snag the SLACK_TOKEN environment variable value and instantiate the SlackClient helper library. Next let’s create a function to list channels via an API call. Slack returns back the results in a dictionary with two keys: ok and channels. ok allows us to know if the API call was successful, and if its value is True then channels contains the data we need on the list of channels.

在以上两行中,我们获取了SLACK_TOKEN环境变量值并实例化了SlackClient帮助器库。 接下来,让我们创建一个通过API调用列出频道的函数。 Slack在带有两个键的字典中返回结果: okchannelsok让我们知道API调用是否成功,并且如果其值为Truechannels包含通道列表中所需的数据。

1122334455

Finally, let’s add a convenience main function that will allow us to print all the channels when we invoke the Python file with python app.py on the command line:

最后,让我们添加一个便捷的main函数,当我们在命令行上使用python app.py调用Python文件时,该函数将允许我们打印所有通道:

1122334455667788

That’s all the code we need for the moment. Time to give it a try. Execute the script from the command line with python app.py. You’ll see output like the following channels list:

这就是我们目前需要的所有代码。 是时候尝试一下了。 使用python app.py从命令行执行脚本。 您将看到类似以下通道列表的输出:

11223344

What is the channel ID that we printed out in parentheses next the the channel name for? Slack’s API needs a unique reference for channels, so we use the ID, not the name, as an identifier instead of the human-readable channel name.

我们在通道名称旁边的括号中打印出的通道ID是什么? Slack的API需要通道的唯一引用,因此我们使用ID(而不是名称)作为标识符,而不是人类可读的通道名称。

We can write some code that uses the to obtain data for a specific channel based on its ID.

我们可以编写一些使用代码,以根据其ID获取特定渠道的数据。

Add a new function along with a few new lines in main to output the latest message from each channel, which is only available in the more detailed channel.info API call.

在main中添加一个新功能以及一些新行,以从每个通道输出最新消息,该消息仅在更详细的channel.info API调用中可用。

Updated code:

更新的代码:

1122334455667788991010111112121313141415151616171718181919202021212222232324242525262627272828292930303131323233333434

Note that with this code we’re greatly increasing the API calls the script executes, from one to N+1, where N is the number of channels returned back by Slack.

请注意,通过此代码,我们极大地增加了脚本执行的API调用,从一个增加到N + 1,其中N是Slack返回的通道数。

Run the new script again by executing python app.py:

通过执行python app.py再次运行新脚本:

11223344556677

Nice! Now we have both the list of channels as well as a way to get detailed information on each channel with its ID. Next let’s interact with other users in one of our channels by sending and receiving messages.

真好! 现在,我们既有了频道列表,又有了一种获取每个频道及其ID的详细信息的方法。 接下来,让我们通过发送和接收消息来与我们的渠道之一中的其他用户进行交互。

传送讯息 (Sending Messages)

We can go even further into the Slack API now that we know our API calls are working and have the channel ID. Let’s send a message to the #general channel.

现在我们知道我们的API调用正在运行并且具有通道ID,我们可以进一步研究Slack API。 让我们向#general频道发送一条消息。

Add a new function under channel_info named send_message:

channel_info下添加一个名为send_message的新函数:

1122334455667788

send_message takes in the ID for a channel, then posts a message from our “Python bot” to that channel. In addition, modify the main function so that when we run this file, main will call our new send_message function:

send_message接收通道的ID,然后将来自“ Python机器人”的消息发布到该通道。 另外,修改main函数,以便当我们运行此文件时, main将调用我们的新send_message函数:

1122334455667788991010111112121313141415151616

Save the changes and run python app.py. Open the #general channel for your Slack team. You should see your Python bot post a new message to the channel:

保存更改并运行python app.py 为您的Slack团队打开#general频道。 您应该看到您的Python机器人在频道中发布了一条新消息:

Slack Send Message

Awesome! So we can send messages, but what about if we want to see what users in the #general channel are saying?

太棒了! 这样我们就可以发送消息了,但是如果我们想查看#general频道中的用户在说什么呢?

接收讯息 (Receiving Messages)

We can set up an outgoing webhook that will alert our Python application via an HTTP POST request. This part is a bit more complicated than sending messages because we need to receive one or more POST requests.

我们可以设置一个传出的Webhook,以通过HTTP POST请求提醒我们的Python应用程序。 这部分比发送消息要复杂一些,因为我们需要接收一个或多个POST请求。

First we’ll need a simple web server that can handle an inbound POST request from the Slack webhook. Create a new file named receive.py with the following code:

首先,我们需要一个简单的Web服务器,该服务器可以处理来自Slack Webhook的入站POST请求。 使用以下代码创建一个名为receive.py的新文件:

112233445566778899101011111212131314141515161617171818191920202121222223232424252526262727

In the above Python file, we:

在上面的Python文件中,我们:

  1. Import Flask
  2. Instantiate a new Flask application context
  3. Pull in the SLACK_WEBHOOK_SECRET environment variable, which we’ll get in just a moment from the Slack console
  4. Establish a route that can receive an HTTP POST request from Slack that prints the output to the command line as long as the webhook secret key sent to us matches the one from our environment variable
  5. Create another route for testing purposes that responds to a GET request
  6. Set our Flask app to run when we run this script with Python
  1. 进口瓶
  2. 实例化新的Flask应用程序上下文
  3. 输入SLACK_WEBHOOK_SECRET环境变量,我们将在稍后从Slack控制台中获取
  4. 建立一条可以从Slack接收HTTP POST请求的路由,只要发送给我们的webhook密钥与环境变量中的一个相匹配,该路由就会将输出打印到命令行
  5. 创建另一个路由以响应GET请求以进行测试
  6. 将我们的Flask应用设置为在我们使用Python运行此脚本时运行

Install Flask (pip install flask), and then start the Flask app with the python receive.py command and we’ll see some debugging output indicating the development server is running.

安装Flask( pip install flask ),然后使用python receive.py命令启动Flask应用程序,我们将看到一些调试输出,指示开发服务器正在运行。

  • Running on (Press CTRL+C to quit)
  • Restarting with stat
  • Debugger is active!
  • Debugger pin code: 144-609-426
  • 在运行(按CTRL + C退出)
  • 用统计重启
  • 调试器处于活动状态!
  • 调试器密码:144-609-426

We’re set to receive our POST request webhook, except that most development environments do not expose routes beyond localhost. We need a localhost tunnel that will give us an externally-accessible domain name while we’re developing our code. I typically use since it’s . There are also other options such as and .

我们准备接收POST请求的webhook,除了大多数开发环境不会暴露本地主机以外的路由。 我们需要一个本地主机隧道,以便在我们开发代码时为我们提供一个外部可访问的域名。 我通常使用因为它 。 还有其他选项,例如和 。

After downloading and running ngrok (or another localhost tunneling tool) in a new terminal window, you’ll get a subdomain that forwards requests sent to that subdomain over to your localhost server. Here is what ngrok looks like in the console when it’s started with the ./ngrok http 5000 command:

在新的终端窗口中下载并运行ngrok(或另一个localhost隧道工具)后,您将获得一个子域,该子域将发送到该子域的请求转发到您的localhost服务器。 这是使用./ngrok http 5000命令启动时, ./ngrok http 5000在控制台中的./ngrok http 5000

ngrok

Take note of your Forwarding URL, in this case https://6940e7da.ngrok.io, as we’ll need that for Slack to set up our outgoing webhook. Then test that our ngrok forwarding URL is properly connected to our Flask app by opening your web browser and going to the Forwarding URL. We should see the “It works!” message.

记下您的转发URL,在这种情况下为https://6940e7da.ngrok.io ,因为我们需要Slack来设置我们的传出Webhook。 然后,通过打开Web浏览器并转到转发URL,测试我们的ngrok转发URL是否已正确连接到Flask应用。 我们应该看到“它有效!” 信息。

Now we can use that ngrok Forwarding URL in our Slack configuration. Go to the , then click the “outgoing webhook integration” link as shown below:

现在,我们可以在Slack配置中使用该ngrok转发URL。 转到 ,然后单击“外发Webhook集成”链接,如下所示:

Slack Outgoing Webhooks

Scroll down to the Integration Settings section. Select “#general” as the channel to listen on. Copy your ngrok Forwarding URL plus “/slack” into the URL(s) text box:

向下滚动到“集成设置”部分。 选择“ #general”作为收听频道。 将您的ngrok转发URL加“ / slack”复制到URL文本框中:

Slack Outgoing Webhooks Settings

Copy the generated Token. Scroll down and press the “Save Settings” button.

复制生成的令牌。 向下滚动并按“保存设置”按钮。

Stop your Flask server for just a moment. As we did earlier with the Slack token, use the export command to expose the outgoing webhook token as an environment variable:

暂时停止Flask服务器。 正如我们之前使用Slack令牌所做的那样,请使用export命令将传出的webhook令牌公开为环境变量:

11

Then restart your Flask server so it can grab the generated SLACK_WEBHOOK_SECRET. Finally, it’s time to test out receiving messages!

然后重新启动Flask服务器,以便它可以捕获生成的SLACK_WEBHOOK_SECRET 。 最后,该测试接收消息了!

Go to your Slack #general channel. You should see that the outgoing webhook integration has been added to the channel:

转到您的Slack #general频道。 您应该看到传出的Webhook集成已添加到通道:

Slack Webhook Added to the Channel

Within Slack, type in a message like “testing” and hit enter. Go back to the command line where your Flask app is running. You should see the message output printed from the POST request:

在Slack中,输入诸如“测试”之类的消息,然后按Enter。 返回运行Flask应用程序的命令行。 您应该看到从POST请求打印的消息输出:

1122

Now we’ve got a way to receive messages from one or more channels and can add whatever Python code we want to handle the input. This is a great hook for building a bot or sending messages to another service for processing.

现在,我们有了一种从一个或多个通道接收消息的方法,并且可以添加我们想要处理输入的任何Python代码。 这是构建机器人或将消息发送到另一个服务进行处理的绝妙钩子。

结语 (Wrapping it up)

Woohoo! All done! Well actually, there’s a whole lot more you can do with the Slack API. Here are several more ideas to try out now that you’ve got the basics down:

oo! 全做完了! 好吧,实际上,您可以使用Slack API做更多的事情。 现在,您已经掌握了一些基础知识,现在可以尝试其他一些想法:

  1. Combine the
  2. Try a different Slack client or ditch the helper library entirely and use the
  1. 结合使用
  2. 尝试使用其他Slack客户端或完全放弃帮助程序库,然后使用


That’s all for now.

目前为止就这样了。

  • Twitter: and
  • GitHub:
  • Twitch (live coding with Python & Swift):
  • Twitter: 和
  • 的GitHub:
  • Twitch(使用Python和Swift进行实时编码):

翻译自:

转载地址:http://lgqwd.baihongyu.com/

你可能感兴趣的文章
配置php_memcache访问网站的步骤
查看>>
textarea 输入框限制字数
查看>>
基本硬件知识(一)
查看>>
js之事件冒泡和事件捕获
查看>>
Linux——LVM 逻辑卷的创建与扩展
查看>>
WIN2003 Apache httpd.exe 进程内存只增不减
查看>>
用Java设计简易的计算器
查看>>
通讯框架后续完善3
查看>>
SharedPreference工具类
查看>>
css文本样式-css学习之旅(4)
查看>>
Java多线程3:Thread中的静态方法
查看>>
找出字符串中第一个只出现一次的字母
查看>>
到底什么样的企业才适合实施SAP系统?
查看>>
事件驱动模型
查看>>
.NET 项目SVN 全局排除设置
查看>>
[语法]全面理解抽象类(abstract class),抽象方法(abstract method),虚方法(virtual method),接口(interface)...
查看>>
PostgreSQL远程连接配置管理/账号密码分配(解决:致命错误: 用户 "postgres" Ident 认证失败)...
查看>>
Java防止SQL注入2(通过filter过滤器功能进行拦截)
查看>>
SQL Server判断语句(IF ELSE/CASE WHEN )
查看>>
Qt: The State Machine Framework 学习
查看>>