【发布时间】:2020-11-06 15:07:54
【问题描述】:
我对 Slack Web API 的chat.postMessage 方法的理解是,您可以作为一个拥有机器人令牌的机器人,将消息发布到公共频道。但是,如果您想向 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))
}
【问题讨论】: