LoginSignup
8
4

More than 5 years have passed since last update.

TypeScript で型安全に Slack の Incoming Webhook を扱う

Last updated at Posted at 2018-02-15

Slack の Incoming Webhook のラッパーライブラリはいくつかありますが、型定義がなかったり、あっても any になってしまっていて、型のサポートを受けることができません。

Slackのドキュメント は見にくいし、ドキュメントを見にいくのも面倒なので 型定義がそのままドキュメントになる ような npm ライブラリを作ってみました。

starhoshi/typed-slack

vscode\.gif \(898×298\)

VSCode の補完のサポートを受けながら開発できます。
パラメータの説明もドキュメントコメントに書いてあるので、それを見ながら何を使うか判断していけます。

Installation

npm install typed-slack

Usage

import して new して send するだけです。 return は Promise です。

import * as Slack from 'typed-slack'

let slack = new Slack.IncomingWebhook('https://hooks.slack.com/services/.......')
slack.send({ text: 'text' }).then(e => {
  console.log('success')
}).catch(e => {
  console.error(e)
})

オプションを使う

typed-slack.d.ts に型定義があります。これを見ながら or 補完を頼りにオプションを書いていけます。

const options = <Slack.IncomingWebhookOptions>{
  text: '@star__hoshi Hi!',
  channel: 'debug',
  icon_emoji: ':smile:',
  link_names: 1,
  attachments: [
    {
      color: Slack.Color.Danger,
      fields: [
        {
          title: 'Priority',
          value: 'High',
          short: false
        }
      ],
      image_url: 'http://my-website.com/path/to/image.jpg',
      ts: 123456789
    }
  ]
}
await slack.send(options)

おわり

TypeScript で Incoming Webhook 使う人は使ってみてください :pray:

starhoshi/typed-slack: Type-safe slack client for TypeScript.

8
4
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
8
4