作为 Slack 机器人响应丰富的消息

Respond with a rich message as a Slack bot

我正在开发一个包含机器人用户的 Node.js slack 应用程序。但是我不知道如何以机器人的身份回复带有丰富消息的用户。

示例:

我可以使用以下代码毫无问题地回复简单的消息:

import * as SlackClient from '@slack/client';

slackBot = new SlackClient.RtmClient(bot_access_token)
slackBot.on(SlackClient.RTM_EVENTS.MESSAGE, message => {
    slackBot.sendMessage('Hello', message.channel);
});
slackBot.start();

但 RTM API 不支持富消息:

The RTM API only supports posting simple messages formatted using our default message formatting mode. It does not support attachments or other message formatting modes. To post a more complex message as a user clients can call the chat.postMessage Web API method with as_user set to true.

所以我尝试使用网络客户端来响应丰富的消息并移动到此代码:

import * as SlackClient from '@slack/client';

slackWebClient = new SlackClient.WebClient(access_token);
slackBot = new SlackClient.RtmClient(bot_access_token)
slackBot.on(SlackClient.RTM_EVENTS.MESSAGE, message => {
    slackWebClient.chat.postMessage(message.channel, 'Hello', { attachments: myAttachments });
});
slackBot.start();

当我用我的帐户测试机器人时,这种方法有效。但是,如果其他团队用户向机器人写入 DM,slackWebClient.chat.postMessage 会失败并显示错误 error: channel_not_found。 (我也尝试添加一个参数 as_user: true - 但行为是一样的,除了消息是用我的名字而不是机器人名字签名的)。

已解决:我使用 Bot 用户 OAuth 访问令牌 而不是 OAuth 访问令牌 创建了一个 SlackClient.WebClient 实例( as_user 也设置为 true),现在它按预期工作了。我不知道 Bot 用户 OAuth 访问令牌 也可以用作 Web API 客户端的令牌。

工作代码:

import * as SlackClient from '@slack/client';

slackWebClient = new SlackClient.WebClient(bot_access_token);
slackBot = new SlackClient.RtmClient(bot_access_token)
slackBot.on(SlackClient.RTM_EVENTS.MESSAGE, message => {
    slackWebClient.chat.postMessage(message.channel, 'Hello', { attachments: myAttachments, as_user: true });
});
slackBot.start();