【Node.js, TypeScript, SlackAPI】Slackへメッセージを投稿する(TypeScriptバージョン)
$ npm i
src/main.ts
の 【SlackAPIトークン】
の部分を自分のSlackAPIトークンに変更する
$ tsc src/main.ts
$ node .
自分のスラックの general
チャンネルに「Hello World!!」と表示されれば成功。
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "src/main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"request": "^2.79.0"
}
}
// コンパイル時に「Cannot find namespace 'http'.」って言われるけど大丈夫
import slack from './slack';
var test = new slack;
test.post({text: 'Hello World!!'}, function(){});
import request = require('request')
export interface SlackPostForm {
token?: string
channel?: string
username?: string
text?: string
}
export default class Slack {
constructor() {
}
post(form: SlackPostForm, callBack: (error: any, response: http.IncomingMessage, body: any) => void) {
let options: request.CoreOptions = {
form: {
token: form.token || '【SlackAPIトークン】',
channel: form.channel || 'general',
username: form.username || 'post_slack',
text: form.text || ''
}
}
request.post('https://slack.com/api/chat.postMessage', options, (error, response, body) => {
callBack(error, response, body)
})
}
}