如何保存发送给机器人的主动消息?

How to save proactive messages sent to the bot?

我正在使用 Microsoft BotConnector 向我的机器人发送消息,但它们没有被记录为普通消息。为了将消息记录到数据库,我编写了自定义记录器:

class CustomLogger {
    /**
     * Log an activity to the transcript file.
     * @param activity Activity being logged.
     */
    constructor() {
        this.conversations = {};
    }

    logActivity(activity) {

        if (activity) {
            console.log("Log information")
        }


        if (!activity) {
            throw new Error("Activity is required.");
        }
        if (activity.conversation) {
            var id = activity.conversation.id;
            if (id.indexOf("|" !== -1)) {
                id = activity.conversation.id.replace(/\|.*/, "");
            }
        }

        if (activity.type === "message") {
            Conv.create({
                text: activity.text,
                conv_id: activity.conversation.id,
                from_type: activity.from.role,
                message_id: activity.id || activity.replyToId
            }).then(() => {
                console.log("logged");
            });
            delete this.conversations[id];
        }
    }
}

它适用于普通消息,但不适用于发送到

的消息

POST /v3/conversations/{conversationId}/activities

通过微软机器人连接器。

当我使用机器人连接器发送消息时,它不会通过 activity 记录请求。

我用来发送主动消息的代码:

/**
 * Send message to the user.
 */
function sendMessage(token, conversation, name) {

  var config = {
    headers: { "Authorization": "Bearer " + token }
  };

  var bodyParameters = {
    "type": "message",
    "text": name
  }

  axios.post(
    'https://smba.trafficmanager.net/apis/v3/conversations/29:XXXXXXXXXXXXXXX/activities',
    bodyParameters,
    config
  ).then((response) => {
    console.log(response)
  }).catch((error) => {
    console.log(error)
  });
}


let name = "Hey, How was your week?";
let conversation = "29:XXXXXXXXXXXXXXX";

run(conversation, name);

我建议使用 BotFramework 适配器继续与用户对话,而不是使用 REST API 向用户发送主动消息。当您从适配器发送主动消息时,activity 通过记录器中间件并保存到存储中。如果要从 Azure 函数启动主动消息,可以在从该函数调用的索引文件中设置另一个消息传递端点。看看下面的代码片段。

index.js

// Listen for incoming notifications and send proactive messages to user.
server.get('/api/notify/:conversationID', async (req, res) => {
    const { conversationID } = req.params;
    const conversationReference = conversationReferences[conversationID];

    await adapter.continueConversation(conversationReference, async turnContext => {
        await turnContext.sendActivity('proactive hello');
    });


    res.setHeader('Content-Type', 'text/html');
    res.writeHead(200);
    res.write('<html><body><h1>Proactive messages have been sent.</h1></body></html>');
    res.end();
});

有关更多详细信息,我会查看此 Proactive Messages Sample。它位于 samples-work-in-progress 分支中,可能会略有变化,但它是一个很好的示例,说明如何配置您的项目以从 Restify 端点发送主动消息。

希望对您有所帮助!