最近触っていて、それっぽい簡易サンプルがなかったのでメモしておきます。
jQueryやaxiosでやっても良いのですが、xhrでシンプルに。
to Slack
Slackはこれまでのincoming webhookと作り方が変わったのでSlack側の設定で苦戦するかも。
function toSlack(message) {
const url = 'Webhook URL';
const data = {
text: message
};
const xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xhr.send('payload=' + JSON.stringify(data))
}
const msg = `hello slack~`;
toSlack(msg); //実行
to Discord
Discrodは割とシンプルです。
Slackのapplication/x-www-form-urlencoded
とは違い、application/json
で送ります。(むしろこっちの方が多いか)
function toDiscord(message){
const url = 'Webhook URL';
const data = {
content: message
};
const xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data))
}
const msg = `hello discord~`;
toDiscord(msg); //実行