簡體   English   中英

Microsoft Bot Framework-如何從第三方API發送響應

[英]Microsoft Bot Framework - how to send responses from a 3rd party API

使用Microsoft Bot Framework,如何在傳入和傳出的漫游器消息之間代理API?

我已替換:

server.post('/api/messages', connector.listen());

使用我自己的實現,該實現采用req.body.text並將其發送到單獨的端點。

如何將端點響應發送回聊天?

server.post('/api/messages', (req, res, next) => {
  request.post('endpoint', {
    json: {"text": req.body.text},
  }, (error, response, body) => {
    // how to send body as an outgoing chat message?
  })
})

更新:

為了指出為什么Ezequiel Jadib的答案不起作用,我添加了完整的代碼。 機器人的回調函數中未定義req

const restify = require('restify')
const builder = require('botbuilder')
const request = require('request')

// Setup Restify Server
const server = restify.createServer()
server.use(restify.plugins.bodyParser())
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url) 
})

// Create chat connector for communicating with the Bot Framework Service
const connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
})

server.post('/api/messages', connector.listen())

const bot = new builder.UniversalBot(connector, function (session) {
  request.post('endpoint', {
    json: {"text": req.body.text}
  }, (error, response, body) => {
    session.send(body)
  })
})

首先,我認為您應該閱讀Node.js文檔,因為這個問題似乎與SDK的基礎有關。

然后,我認為您在錯誤的地方呼叫了端點。 而不是在發布時執行此操作,您應該在UniversalBot的功能中執行此操作,該功能基本上就是接收用戶消息的位置。

您可以嘗試如下操作:

var bot = new builder.UniversalBot(connector, function (session) {
    request.post('endpoint', {
      json: {"text": session.message.text},
    }, (error, response, body) => {
        session.send("You said: %s", "your endpoint response");
   })
});

您可以使用Bot Builder Node.js SDK的中間件功能攔截消息。

從文章使用Node.js開發>消息>攔截消息

Bot Builder SDK中的中間件功能使您的機器人可以攔截用戶和機器人之間交換的所有消息。 對於每條被截獲的消息,您可以選擇執行以下操作,例如將消息保存到指定的數據存儲中,這將創建對話日志,或者以某種方式檢查消息並采取代碼指定的任何操作。

您可以通過配置bot.use()方法來定義用於處理攔截消息的中間件函數。

例:

bot.use({
    botbuilder: function (session, next) {
        // this function handles incoming messages sent to your bot
        next();
    },
    send: function (event, next) {
        // this function handles outgoing messages to your user(s)
        next();
    }
});

作為參考,您可以在此處找到一個演示中間件功能的工作示例bot: https : //github.com/Microsoft/BotBuilder-Samples/tree/master/Node/capability-middlewareLogging

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM