LoginSignup
6
9

More than 5 years have passed since last update.

SlackのAPIでメッセージ通知を送る(PHP)

Last updated at Posted at 2016-12-20

1. APIを使うためにAPIキーを取得

  • https://api.slack.com/web
    1. Authentication配下のGenarate test tokenボタンをクリック
    2. 通知を送りたいチームでCreate tokenボタンをクリック
    3. できたtokenをKEYとする

2. PHPでSlackに通知を送る

<?php
$slackApiKey = 'xxxx-xxxxxxxxx-xxxx~~~~'; //上で作成したAPIキー
$text = 'こんにちは';
$text = urlencode('投稿されたよ。' . $text);
$url = "https://slack.com/api/chat.postMessage?token=${slackApiKey}&channel=%23random&username=huga-bot&text=${text}&as_user=true";
file_get_contents($url);
  • urlencode($text):urlに埋め込むときはurlエンコードをする。
  • リクエストパラメータ(token, channel, textは必須パラメータ)
    • token:作成したAPIキー
    • channel:通知を送るチャンネル名(%23は#のurlエンコード。この例なら、チャンネル名は「#random」)
    • ダイレクトメッセージの場合は、@のエンコードである%40を頭に付けて、送信先のユーザー名を記載すればOK
    • username:通知を送るbot名(この例なら、投稿者は「huga-bot」)
    • text:通知内容
    • as_user:これを指定しなければ「bot」が投稿。trueにしたら、「APIキーの作成者」が投稿。
    • ドキュメントは下記参照。
    • https://api.slack.com/methods/chat.postMessage

$text = 'Hello!';をPOSTで受け取ったテキストにするなどカスタマイズして色々遊べそう

6
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9