PHPでSlackへメッセージ送信するサンプル。
Slackの該当チャンネルで、チャンネル詳細〜インテグレーション〜アプリを追加する、でIncomming Webhookを追加。
その際に、チャンネルを指定(ここで新規作成も可)&投稿者名を設定し、Webhook URLを拾う。
あとはChatWorkとほぼ一緒。(要php-curl)
<?php
class SlackComponent
{
/**
* Slackへメッセージ送信
* @param $url : Incomming WebhookのWebhook URL
* @param $channel : #チャンネル名
* @param $bodyText : 内容
* @return string | false
* error : ?
* success: "ok"
*/
public static function send(string $url, string $channel, string $bodyText) : string | false
{
$ch = curl_init();
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'payload' => json_encode([
'channel' => $channel, // #チャンネル名
'text' => $bodyText, //本文
]),
])
];
curl_setopt_array($ch, $options);
$res = curl_exec($ch);
curl_close($ch);
if ($res === false) {
return false;
}
return $res;
}
}
呼び出し側は、
$url = 'https://hooks.slack.com/services/XXXXXXXXX/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$channel = '#test';
$res = SlackComponent::send($url, $channel, 'this is test');
if ($res !== 'ok') {
//fail
}
else {
//success
}
こんな感じでするっと’ok’が返ってくる。