Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9003

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

$
0
0

スクリプト

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

import{escape}from'querystring';importfetchfrom'isomorphic-unfetch'exportasyncfunctionnotify(api_token:string,room_id:string,message:string,self_unread?:0|1):Promise<Response>{returnawaitfetch(`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=${typeofself_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を提供してくれるため使用しています。

使い方

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

Chatwork API

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


Viewing all articles
Browse latest Browse all 9003

Trending Articles