LoginSignup
2
2

More than 3 years have passed since last update.

javascriptでslackにメッセージを送信する方法

Last updated at Posted at 2020-02-26

javascriptでslackにメッセージを送信する方法をまとめました。

前提条件

  • npmがインストールされていること
  • slackのapiキーが分かっていること

インストール

npmコマンドでモジュールをインストール

$ npm i --save axios

使い方

ファイルの作成

touchコマンドでtest.jsファイルを作成

$ touch test.js

設定

pathにはslackのapiが入ります。

test.js
const axios = require('axios')

const slack = async (path, channel, username, text, iconEmoji) => {
  const data = `payload={
    "channel": "${channel}",
    "username": "${username}",
    "text": "${text}",
    "icon_emoji":"${iconEmoji}"
  }`
  const param = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }
  }

  try {
    const res = await axios.post(path, data, param)
    console.log(res.data)
  } catch (err) {
    console.log(err)
  }
}

(async function () {
  await slack('xxxxxx', '#test', 'テストマン', 'テストコメント', ':memo:')
  console.log('slackにメッセージを送信しました。')
}())

実行

nodeコマンドでtest.jsを実行する

$ node test

出力結果

ok
slackにメッセージを送信しました。

参考文献

この記事は以下の情報を参考にして執筆しました。

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