LoginSignup
1
2

More than 3 years have passed since last update.

Chatwork に Node.js + TypeScript でメッセージを通知する

Last updated at Posted at 2020-11-28

スクリプト

ちょっとしたツールを作成していて Chatwork 通知が必要になりましたため、作成しました。

import { escape } from 'querystring';
import fetch from 'isomorphic-unfetch'

export async function notify(
  api_token: string,
  room_id: string,
  message: string,
  self_unread?: 0 | 1
): Promise<Response> {
  return await fetch(`https://api.chatwork.com/v2/rooms/${room_id}/messages`, {
    method: 'POST',
    headers: {
      'X-ChatWorkToken': api_token,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: `body=${escape(message)}&self_unread=${
      typeof self_unread === 'undefined' ? 1 : self_unread
    }`,
  });
}

下記のライブラリのインストールが必要です。

# yarn の場合
$ yarn add querystring isomorphic-unfetch

# npm の場合
$ npm install querystring isomorphic-unfetch

querystring.escapeで投稿するメッセージURLパーセントエンコードしています。
これがないと投稿内容にURLで使用できない文字が混ざった際に投稿が失敗します。

また、isomorphic-unfetchはブラウザ(window.fetch)、サーバー(node-fetch)両方で動くfetch APIを提供してくれるため使用しています。

使い方

async function main() {
  await notify(
    process.env.CHATWORK_API_TOKEN,
    process.env.CHATWORK_ROOM_ID,
    "テストメッセージです。"
  );
}
main();

Chatwork API

詳しい仕様は公式ドキュメントをご確認ください。

1
2
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
1
2