LoginSignup
1
0

More than 1 year has passed since last update.

AxiosでSlack botによる通知を送信する

Posted at

前提

Slack APIでwebhook URLを取得済み

コード

import axios from 'axios';

const notification = (content, image_url) => {


    const data = {
        "text": "料理が新しく投稿されました!",
        "attachments": [{
            "fields": [
                {
                    "title": content,
                    "value": content,
                }],
            "image_url": image_url
        }]
    }

    axios.post(
        {WebhookのURL},
        JSON.stringify(data),
        // corsエラー回避
        {
            withCredentials: false,
            transformRequest: [(data, headers) => {
            delete headers.post["Content-Type"]
            return data
            }]
        }
    )
    .then(res => {
      console.log(res)
    })
    .catch(e => {
      console.log(e)
    });
}

結果

このような通知がチャンネルに飛んできます。
スクリーンショット 2022-06-12 8.41.46.png

参考

CORSエラーの対処法
https://stackoverflow.com/questions/41042786/cors-issue-using-axios-with-slack-api

リッチな通知UIの作り方(公式)
https://api.slack.com/messaging/composing/layouts

SlackAPI attachment チートシート
https://qiita.com/daikiojm/items/759ea40c00f9b539a4c8

1
0
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
1
0