如何在 Python 中将消息发送到 Slack 频道

How to send message to a Slack channel in Python

我需要使用 Python 向 Slack 频道发送消息。

我的 Google 搜索 here and search right from our Stack Overflow sitehere 结果没什么帮助。让它工作的正确方法是什么?

我找到的最接近的指南来自 Slack 官方指南 here 但它 没有 清楚如何使用 SLACK_BOT_TOKEN 进行身份验证以调用 client.chat_postMessage()

from slack_sdk import WebClient
client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))

result = client.chat_postMessage(
    channel=channel_id,
    text="Hello world!"
)

简述

  • 创建 Slack 应用又名 myslackchat ref

  • 将范围 chat:write 授予 Slack 应用程序 ref

  • 获取 Slack 频道 ID 又名 channel id

  • 获取 SLACK_BOT_TOKEN 您的 Slack 应用程序

  • 将 Slack 应用程序 myslackchat 添加到您的 Slack 工作区,第二,将 myslackchat 添加到 Slack 频道 channel id

  • python 向 channel id 发送消息的代码,使用 SLACK_BOT_TOKEN ref

p.s.

如何获得

在为它寻找 Slack 文档几天后,这里是相关的 guide;请搜索页面以转到此部分 OAuth Tokens for Your Workspace - 这很痛苦 ^^ 我不知道为什么本指南中没有提到 SLACK_BOT_TOKEN



完整详情

One thing you'll need before starting is a Slack app. If you don't have one yet, here's a very quick guide to help you create one.

Requesting the necessary permissions chat:write. This one grants permission for your app to send messages as itself (apps can send messages as users or bot users)

Requesting these permissions is easy:

  • Load up the settings for your app from the app management page.
  • In the navigation menu, choose the OAuth & Permissions feature.
  • Scroll down to the Scopes section, and pick channels:read and chat:write from the drop down menu.
  • Click save changes.
  • Scroll back to the top of this page and look for the button that says Install App to Workspace (or Reinstall App if you've done this before). Click it.