如何在现有DM中以Slack Bot形式发布消息

时间:2020-07-16 20:52:58

标签: reactjs token slack-api

我对Slack Web API的chat.postMessage方法的理解是,作为具有bot令牌的bot,您可以将消息发布到公共频道。但是,如果要发布到DM,则需要先请求用户令牌,然后代表用户发布

但是,我使用了一些能够作为应用程序发布到DM中的应用程序(因此,我认为使用的是机器人令牌)。对我来说,这是理想的选择,因此您不必在Slack工作区中烦扰每个人来获取他们的用户令牌

谁能告诉我这是怎么做的?

作为参考,这是我用来将消息作为机器人发布的代码。它不适用于DM或尚未邀请该机器人的私人渠道。很想解决这个问题。谢谢

function getQueryString(data = {}) {
        return Object.entries(data)
          .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
          .join('&');
  }

function postMessageInSlack(bot_token, channelID, userID, message, send_blocks, endpoint) {
        const options = {
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        };
        const data = {
            token: bot_token,
            channel: channelID,
            text: `${message} from <@${userID}>`,
            blocks: JSON.stringify(send_blocks),
        }
        delete axios.defaults.headers.common["Content-Type"];
        axios.post(endpoint,
            data, {
            options,
            transformRequest: getQueryString}
        )
        .then(res => console.log("result is ", res))
        .catch(err => console.log("the error is ", err))
}

1 个答案:

答案 0 :(得分:1)

您需要与用户打开新的对话,即没有打开任何对话。为此,您需要使用conversations.open方法。这将返回包含会话ID的响应。现在,您可以在chat.postMessage方法中使用会话ID代替频道ID。