LoginSignup
307

More than 5 years have passed since last update.

Slack APIを使用してメッセージを送信する

Last updated at Posted at 2015-10-10

概要

SlackのAPIを使用してメッセージを送信するまでの操作メモです。

環境

  • Slack (Free plan).
  • curl (Windows版)

参考

API

Slackの外部からメッセージを送信するにはWEB APIを使用する方法と、Incoming webhooksを使用する方法があります。

WEB API

The Slack APIs allow you to integrate complex services with Slack to go beyond the integrations we provide out of the box.

WEB APIを利用するには事前にTOKENを取得する必要があります。
用意されているメソッドはAPI Methodsで確認できます。

TOKENの取得

左側メニューのチーム名をクリックしコンテキストメニューからConfigure Integrationsを選択します。
IntegrationsページのAll ServicesタブにあるSlack API(ページの下の方にあります)をクリックします。

s04.png

左側メニューのAPIS -> Web APIをクリックします。

s05.png

AuthenticationのCreate tokenボタンをクリックしてTokenを取得します。

s07.png

auth.test

tokenのテストができるAPIが用意されていますので、それを使って確認してみます。

auth.test
curl -XPOST "https://slack.com/api/auth.test?token=<TOKEN>&pretty=1"

または

auth.test
curl -XPOST -d "token=<TOKEN>" -d "pretty=1" "https://slack.com/api/auth.test"

response

okキーの値がtrueであれば成功です。

chat.postMessage

chat.postMessage APIを使ってメッセージを送信してみます。
tokenパラメータに取得したトークンを指定します。

chat.postMessage
curl -XPOST "https://slack.com/api/chat.postMessage?token=<TOKEN>&channel=%23general&text=Hello%20@rubytomato&username=rubybot"
  • URLはパーセントエンコードする必要があります。

または

chat.postMessage
curl -XPOST -d "token=<TOKEN>" -d "channel=#general" -d "text=Hello @rubytomato" -d "username=rubybot" "https://slack.com/api/chat.postMessage"

response

s06.png

Incoming WebHooks

Incoming Webhooks are a simple way to post messages from external sources into Slack. They make use of normal HTTP requests with a JSON payload, which includes the message and a few other optional details described later.

Incoming WebHooksを使用するには事前にIntegration serviceに登録する必要があります。

Integration serviceに登録

Slackの左側メニューのチーム名をクリックしコンテキストメニューからConfigure Integrationsを選択します。
IntegrationsページのAll ServicesタブにあるIncoming WebHooks(ページの下の方にあります)をクリックします。

s01.png

Post to Channelでchannelを選択して登録します。

s02.png

登録するとWebhook URLが発行されますので、そのURLに対してメッセージ登録のHTTPリクエストを発行します。

Webhook URLは下記のような形式です。

https://hooks.slack.com/services/Txxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxxxx

メッセージの送信

channelキーを省略するとIncoming WebHooksを登録するときに選択したchannelがデフォルトの送信先となりますが、channelキーを上書きすることで他のchannelへメッセージを送信することができます。

curl -X POST "<Webhook URL>" -d @message.json
message.json
payload={
  "channel": "#general",
  "username": "webhookbot",
  "text": "This is posted to #general and comes from a bot named webhookbot.",
  "icon_emoji": ":ghost:"
}

response

s03.png

Direct Message

channelキーに@ユーザーを指定するとそのユーザーへDirect Messageを送信できます。

"channel": "@rubytomato"

メモ

curl

Windows版のcurlでhttpsに対してリクエストを送ると下記のエラーが発生することがあります。

curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

このエラーが発生する場合は、http://curl.haxx.se/docs/caextract.htmlにアクセスして最新の証明書を取得します。
このページのca-bundle.crtというテキストリンクをクリックしてその内容をcurl-ca_bundle.crtとしてcurl.exeと同じディレクトリに保存します。

s08.png

API TEST

api.test
curl -XPOST "https://slack.com/api/api.test"
response
{"ok":true}

クエリにerrorというパラメータが存在するとリクエストは必ず失敗するようになります。

api.test
curl -X POST "https://slack.com/api/api.test?error=test&foo=bar&pretty=1"

または

api.test
curl -X POST -d "error=test" -d "foo=bar" -d "pretty=1" "https://slack.com/api/api.test"
response
{
    "ok": false,
    "error": "test",
    "args": {
        "error": "test",
        "foo": "bar",
        "pretty": "1"
    }
}

この形式のリクエストはできないようです。

api.test
curl -X POST --data-urlencode "{\"error\":\"test\", \"foo\":\"bar\", \"pretty\":1}" "https://slack.com/api/api.test"

Slackのメモ

Public Channel

This will create a new public channel that anyone on your team can join.
If you need this conversation to be private, you should create a new Private Group instead.

チームに招待されたメンバーであればだれでも参加できるチャネルです。

Direct Message

Direct messages are private, 1-to-1 messages. Once you invite people, you'll be able to chat with them here.

指定するユーザーと直接メッセージの交換ができます。

Private Group

A private group is only visible to its members, and only members of a private group can read or search its contents.

招待したメンバーしか参加できないグループです。

Invite People

ユーザーには下記のroleがあり、roleによって操作できる内容が異なります。

  • Owner
  • Admin
  • Member
  • Restricted Account
  • Single-Channel Guest
Full Members

Full Members can access messages and files in any public channel and access the full team directory.

Team members have access to standard features like joining any public channel, uploading files, and other optional abilities. This is the default for new people added to your team.

Restricted Accounts

Restricted Accounts see a partial team directory and can only access messages and files from selected channels and groups.

These accounts can access only a limited set of channels. Restricted accounts are not able to view the entire team directory or search messages and files outside of their permitted channels.

Single-Channel Guest

Single-Channel Guests can only access messages and files in a single channel. This account type is free.

Guests are a type of Restricted Account that are only allowed to join a single channel or group.

  • Free planではRestricted Accounts、Single-Channel Guestは利用できません。
  • 有料planではRestricted Accounts、Single-Channel Guestを利用できます。

Integrations

Integration serviceを登録するにはチーム名をクリックしコンテキストメニューから"Configure Integrations"をクリックします。

free planでは登録数に制限があります。

  • Free planでは10 service integrations
  • 有料planではUnlimited service integrations

下記もIntegration Serviceの1つなので使用するなら有効にする必要があります。

  • Incoming WebHooks
  • Outgoing WebHooks
  • Slackbot

Desktop Apps for Windows

Desktop Appsよりダウンロードできます。

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
307