Slack API 運算子¶
引言¶
Slack API 運算子可以將文字訊息或檔案傳送到指定的 Slack 頻道。
SlackAPIPostOperator¶
使用 SlackAPIPostOperator 將訊息傳送到 Slack 頻道。
使用運算子¶
您可以傳送簡單的文字訊息
tests/system/slack/example_slack.py
slack_operator_post_text = SlackAPIPostOperator(
task_id="slack_post_text",
channel=SLACK_CHANNEL,
text=(
"Apache Airflow® is an open-source platform for developing, "
"scheduling, and monitoring batch-oriented workflows."
),
)
或者您可以使用 Block Kit 建立應用佈局
tests/system/slack/example_slack.py
slack_operator_post_blocks = SlackAPIPostOperator(
task_id="slack_post_blocks",
channel=SLACK_CHANNEL,
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
"*<https://github.com/apache/airflow|Apache Airflow®>* "
"is an open-source platform for developing, scheduling, "
"and monitoring batch-oriented workflows."
),
},
"accessory": {"type": "image", "image_url": IMAGE_URL, "alt_text": "Pinwheel"},
}
],
text="Fallback message",
)
SlackAPIFileOperator¶
使用 SlackAPIFileOperator 將檔案傳送到 Slack 頻道。
使用運算子¶
注意
此運算子支援兩種檔案上傳方法,由 method_version 控制,預設使用 Slack SDK 方法 upload_files_v2。也可以透過將 method_version 設定為 v1 來使用傳統的 upload_files 方法,但不建議這樣做,因為它可能會影響效能、導致隨機 API 錯誤,並且將於 2025 年 3 月 11 日停用。此外,從 2024 年 5 月 8 日開始,新建立的應用將無法使用此 API 方法。
如果您之前使用 v1,您應該檢查您的應用是否具有適當的範圍 (scopes)
files:write - 用於寫入檔案。
files:read - 用於讀取檔案(如果您使用 Slack SDK >= 3.23.0 則無需)。
channels:read - 獲取公共頻道列表,用於將頻道名稱轉換為頻道 ID。
groups:read - 獲取私有頻道列表,用於將頻道名稱轉換為頻道 ID
mpim:read - API 方法 conversations.list 的附加許可權
im:read - API 方法 conversations.list 的附加許可權
您可以透過指定檔案路徑傳送檔案附件
tests/system/slack/example_slack.py
slack_operator_file = SlackAPIFileOperator(
task_id="slack_file_upload_1",
channels=SLACK_CHANNEL,
filename="/files/dags/test.txt",
filetype="txt",
)
或者透過直接提供檔案內容
tests/system/slack/example_slack.py
slack_operator_file_content = SlackAPIFileOperator(
task_id="slack_file_upload_2",
channels=SLACK_CHANNEL,
content="file content in txt",
)