> For the complete documentation index, see [llms.txt](https://easonwang.gitbook.io/web_advance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easonwang.gitbook.io/web_advance/slack-api.md).

# Slack API

## 讓 Bot 傳送訊息到 Private Channel

首先加入權限

<figure><img src="https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FMXiaaa4u3OV95epBYH2k%2F%E6%88%AA%E5%9C%96%202023-11-18%20%E4%B8%8B%E5%8D%886.46.15.png?alt=media&amp;token=3c472413-8d55-472e-bf34-81f57e7a8072" alt=""><figcaption></figcaption></figure>

之後 install 到 workplace 後會產生 OAuth token

<figure><img src="https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FjPCmxZNKO8qN0fZyUxS0%2F%E6%88%AA%E5%9C%96%202023-11-18%20%E4%B8%8B%E5%8D%886.47.08.png?alt=media&amp;token=ac2d8f7e-0a45-4d01-89a7-e2898966a1b3" alt=""><figcaption></figcaption></figure>

之後要把 Bot 手動加入到 Private channel 中 (點選新增應用程式)

<figure><img src="https://2356031413-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0u4DAqfidGmTt67qrG%2Fuploads%2FpCJTB5o1sWK6asMRMjfJ%2F%E6%88%AA%E5%9C%96%202023-11-18%20%E4%B8%8B%E5%8D%886.41.49.png?alt=media&amp;token=0077c468-8431-45d1-b5b5-316a97767aa8" alt=""><figcaption></figcaption></figure>

之後在 channel 資訊左下方找到 channel ID，並且紀錄下剛才的 Bot User OAuth Token

執行以下程式：

```javascript
const { WebClient } = require("@slack/web-api");

const options = {};
const web = new WebClient(
  "Bot User OAuth Token",
  options
);

const sendSlackMessage = async (message, channel = null) => {
  const channelId = "Channel Id";

  return new Promise(async (resolve, reject) => {
    try {
      const resp = await web.chat.postMessage({
        text: message,
        channel: channelId,
      });
      return resolve(true);
    } catch (error) {
      return resolve(true);
    }
  });
};

const sendMessage = async (message) => {
  const resp = await sendSlackMessage(message);
  console.log(resp); // true
};
sendMessage("Test App 123");
```
