Slack API 透過 webhook 將訊息傳入

串接 Slack API 沒什麼困難,最難的是要找到 API token 去哪拿... XD

Slack API 透過 webhook 將訊息傳入

Slack webhook 的 API 得要從 https://api.slack.com/apps 去取得(App、Web 頁面拿不到)

這邊直接紀錄 Webhook 新的申請取得路徑:

  • https://my.slack.com/services/new/incoming-webhook/
  • 登入後,直接進入此頁面就可以去申請 Webhook API URL
  • Webhook API URL 會長這樣:
    • https://hooks.slack.com/services/$XXX/$CHANNEL/$TOKEN
  • 測試:
    • curl -X POST --data-urlencode "payload={\"channel\": \"#my-channel-here\", \"username\": \"webhookbot\", \"text\": \"This is posted to #my-channel-here and comes from a bot named webhookbot.\", \"icon_emoji\": \":ghost:\"}" https://hooks.slack.com/services/$XXX/$CHANNEL/$TOKEN

PHP Slack API 串接 Function

<?php
function send_slack_message($text)
{
    $slack_webhook_url = 'https://hooks.slack.com/services/$XXX/$CHANNEL/$TOKEN';

    $json_data = ['text' => $text]; // $json_data = ["text" => "Hello Slack Webhook"];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $slack_webhook_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    return true;
}

// send_slack_message('Slack API 傳送測試');
?>

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料