Skip to main content

用于 Web API 和 RTM API(旧版)的 Slack API 客户端 - 请改用 https://pypi.org/project/slack-sdk/。

项目描述

Python 松弛客户端

重要通知

这个slackclientPyPI 项目现在处于维护模式slack-sdk项目是继任者。v3 SDK 提供了更多功能,例如套接字模式、OAuth 流模块、SCIM API、审计日志 API、更好的异步支持、重试处理程序等等。

请参阅迁移指南,了解如何顺利迁移现有代码。

概述

Pythonslackclient库是一个开发工具包,用于在 Python 3.6 及更高版本上与 Slack Web API 和实时消息传递 (RTM) API 进行交互。

可以在https://slack.dev/python-slackclient/找到有关使用 Slack Python 的综合文档

无论您是为您的团队构建自定义应用程序,还是将第三方服务集成到您的 Slack 工作流程中,Slack Developer Kit for Python 都允许您利用 Python 的灵活性来尽快启动和运行您的项目。

Python slackclient允许与以下交互:

如果您想使用我们的事件 API和交互功能,请查看 [Bolt for Python][bolt-python] 库。有关令牌和身份验证的详细信息,请参阅我们的身份验证指南

有关令牌和身份验证的详细信息,请参阅我们的身份验证指南

目录

要求


该库需要 Python 3.6 及更高版本。如果您需要 Python 2,请使用我们的SlackClient - v1.x。如果您不确定如何检查您使用的 Python 版本,可以使用以下命令进行检查:

注意:您可能需要python3在命令之前使用,以确保使用正确的 Python 路径。例如python3 --version

python --version

-- or --

python3 --version

安装

我们建议使用PyPI安装适用于 Python 的 Slack Developer Kit。

$ pip3 install slackclient

入门教程


我们创建本教程是为了在 10 分钟内构建一个基本的 Slack 应用程序。它需要一些通用的编程知识和 Python 基础知识。它专注于与 Slack 的 Web 和 RTM API 的交互。使用它可以让您了解如何使用此 SDK。

阅读教程以开始使用!

Web客户端的基本用法


Slack 提供了一个 Web API,使您能够构建以各种方式与 Slack 交互的应用程序。该开发工具包是一个基于模块的包装器,可以更轻松地与该 API 进行交互。我们在这里有一个基本示例,其中包含一些更常见的用途,但这里提供了可用方法的完整列表。更详细的示例可以在我们的基本使用指南中找到。

向 Slack 发送消息

最常见的用例之一是向 Slack 发送消息。如果您想作为您的应用程序或作为用户发送消息,则此方法可以同时进行。在我们的示例中,我们指定了通道名称,但建议尽可能使用channel_id。此外,如果您的应用程序的机器人用户尚未在频道中,请在运行代码段之前邀请机器人用户(或添加chat:write.public到机器人令牌范围以在任何公共频道中发布)。

import os
from slack import WebClient
from slack.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_API_TOKEN'])

try:
    response = client.chat_postMessage(
        channel='#random',
        text="Hello world!")
    assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

在这里,我们还确保从 Slack 返回的响应是成功的,并且消息是我们使用assert语句发送的消息。

将文件上传到 Slack

我们更改了将文件上传到 Slack 的流程,使其更加简单直接。您现在可以直接在 API 调用中包含文件路径并以这种方式上传。您可以在此处找到有关此 api 调用的详细信息

import os
from slack import WebClient
from slack.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_API_TOKEN'])

try:
    filepath="./tmp.txt"
    response = client.files_upload(
        channels='#random',
        file=filepath)
    assert response["file"]  # the uploaded file
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

RTM客户端的基本使用


Real Time Messaging (RTM) API是一个基于 WebSocket的API,它允许您从 Slack 实时接收事件并以用户身份发送消息。

如果您更喜欢将事件推送给您,我们建议改用基于 HTTP 的事件 API。RTM API 支持的大多数事件类型在事件 API 中也可用。如果您想改用此 API,可以查看我们的Python Slack 事件适配器。

RTMClient 允许应用程序与 Slack 平台的 RTM API 进行通信。

该客户端的事件驱动架构允许您简单地将回调链接到它们相应的事件。当一个事件发生时,这个客户端执行你的回调,同时传递它接收到的任何信息。我们还让您能够从回调中调用我们的 Web 客户端。

在下面的示例中,我们观察包含“Hello”的消息事件say_hello(),如果收到,我们调用该函数。然后,我们向 Web 客户端发出调用,以回帖到频道,向用户说“嗨”。

import os
from slack import RTMClient
from slack.errors import SlackApiError

@RTMClient.run_on(event='message')
def say_hello(**payload):
    data = payload['data']
    web_client = payload['web_client']
    rtm_client = payload['rtm_client']
    if 'text' in data and 'Hello' in data.get('text', []):
        channel_id = data['channel']
        thread_ts = data['ts']
        user = data['user']

        try:
            response = web_client.chat_postMessage(
                channel=channel_id,
                text=f"Hi <@{user}>!",
                thread_ts=thread_ts
            )
        except SlackApiError as e:
            # You will get a SlackApiError if "ok" is False
            assert e.response["ok"] is False
            assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
            print(f"Got an error: {e.response['error']}")

rtm_client = RTMClient(token=os.environ["SLACK_API_TOKEN"])
rtm_client.start()

请注意,创建 Slack 应用程序的默认方式不再支持 RTM API。使用 RTM API 的事件必须使用经典的 Slack 应用程序(具有普通bot范围)。

如果您已经拥有经典的 Slack 应用程序,则可以使用这些凭据。如果您不需要并且需要使用 RTM API,您可以从此链接创建经典的 Slack 应用程序。您可以在API 文档中了解更多信息。

此外,即使 Slack 应用程序配置页面鼓励您升级到更新的权限模型,也不要升级它并继续使用“经典”机器人权限。

异步使用

slackclient v2 及更高版本在后台使用AIOHttp处理异步请求,使用urllib处理同步请求。

该库的正常使用不会以异步方式运行它,因此run_async=True需要一个 kwarg 。

在异步模式下,重要的是要记住等待或运行/run_until_complete 调用。

Slackclient 作为脚本

import asyncio
import os
from slack import WebClient
from slack.errors import SlackApiError

client = WebClient(
    token=os.environ['SLACK_API_TOKEN'],
    run_async=True
)
future = client.chat_postMessage(
    channel='#random',
    text="Hello world!"
)

loop = asyncio.get_event_loop()
try:
    # run_until_complete returns the Future's result, or raise its exception.
    response = loop.run_until_complete(future)
    assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")
finally:
    loop.close()

框架中的 Slackclient

如果您正在使用调用 asyncio 事件循环的框架,例如:sanic/jupyter notebook/etc。

import os
from slack import WebClient
from slack.errors import SlackApiError

client = WebClient(
    token=os.environ['SLACK_API_TOKEN'],
    run_async=True # turn async mode on
)
# Define this as an async function
async def send_to_slack(channel, text):
    try:
        # Don't forget to have await as the client returns asyncio.Future
        response = await client.chat_postMessage(
            channel=channel,
            text=text
        )
        assert response["message"]["text"] == text
    except SlackApiError as e:
        assert e.response["ok"] is False
        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
        raise e

# https://sanicframework.org/
from sanic import Sanic
from sanic.response import json

app = Sanic()
# e.g., http://localhost:3000/?text=foo&text=bar
@app.route('/')
async def test(request):
    text = 'Hello World!'
    if 'text' in request.args:
        text = "\t".join(request.args['text'])
    try:
        await send_to_slack(channel="#random", text=text)
        return json({'message': 'Done!'})
    except SlackApiError as e:
        return json({'message': f"Failed due to {e.response['error']}"})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)

高级选项

SSL

您可以提供自定义 SSL 上下文或通过传递sslRTM 和 Web 客户端都支持的选项来禁用验证。

对于异步请求,请参阅AIOHttp SSL 文档

对于同步请求,请参阅urllib SSL 文档

代理人

发出异步请求时支持代理,通过proxyRTM 和 Web 客户端都支持的选项。

对于异步请求,请参阅AIOHttp 代理文档

对于同步请求,设置环境HTTPS_PROXY变量或proxy选项有效。

DNS 性能

使用异步客户端并寻求性能提升?安装可选的依赖项 (aiodns) 可能有助于加快客户端的 DNS 解析。我们将它作为额外的“可选”包含在内:

$ pip3 install slackclient[optional]

例子

import os
from slack import WebClient
from ssl import SSLContext

sslcert = SSLContext()
# pip3 install proxy.py
# proxy --port 9000 --log-level d
proxyinfo = "http://localhost:9000"

client = WebClient(
    token=os.environ['SLACK_API_TOKEN'],
    ssl=sslcert,
    proxy=proxyinfo
)
response = client.chat_postMessage(
    channel="#random",
    text="Hello World!")
print(response)

从 v1 迁移


如果您从 slackclient 的 v1.x 迁移到 v2.x,请按照我们的迁移指南确保您的应用在更新后继续工作。

在此处查看迁移指南!

支持


我们不再为此 SDK 的 v1 或 v2 提供支持,只维护最新的 v3 版本。如果您希望获得该项目维护人员的支持,请考虑先更新到最新版本的 SDK。否则,您可以访问Slack 社区以获得使用 Slack Developer Kit for Python 的帮助,或者只是一般地与您的 Slack 开发人员建立联系。

项目详情