プログラムからメッセージを送信する方法は、2種類のSlack APIがあります。
今回は、chat.postMessageの使い方を紹介します。
npm install @slack/web-api
npm install dotenv
SLACK_TOKEN=取得したBot User OAuth Token
CHANNEL_ID=チェンネルID.Slackのチェンネル詳細モーダルから取得できる
require('dotenv').config();
const { WebClient } = require("@slack/web-api");
const client = new WebClient(process.env.SLACK_TOKEN, {})
async function main() {
try {
const result = await client.chat.postMessage({
channel: process.env.CHANNEL_ID,
//▼ シンプルテキスト: text
//text: "Hello world via Slack API",
//▼ 構造化テキスト: blocks
blocks: [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "お問合せがありました!",
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `>${heading("*会社名*")}: テスト株式会社\n>${heading("*氏名*")}: テスト太郎\n>${heading("*メールアドレス*")}: test@test.com\n>${heading("*問合せ内容*")}: テストです\n`
}
},
]
});
} catch(error) {
console.log(error);
}
}
main();
function heading(word) {
return word.padStart(9, " ")
}
node index.js
以下のようなメッセージを確認できました。padStartを用いて、文字列を整形しています。
©Omori
MEOW!