簡體   English   中英

通過Azure部署Javascript Microsoft Botframework模板后,提供的URL返回錯誤

[英]After deploying a Javascript Microsoft Botframework template via Azure the provided URL returns an error

遵循Microsoft提供的從頭到尾的所有步驟之后(此處的教程: https//docs.microsoft.com/en-us/azure/bot-service/javascript/bot-builder-javascript-quickstart?view = azure- bot-service-4.0 ),我已經通過GIT設置了持續部署,效果很好。

我已經能夠在localhost和Bot Framework Emulator上運行代碼而沒有任何問題。 我還能夠使用Azure平台上提供的Web聊天頻道iframe運行該機器人。 (https:// webchat.botframework.com/embed/{your-bot}?s={secret})

最后,我還可以通過Azure使用“在網絡聊天中測試”選項來運行該機器人。

但是,當我嘗試使用azure提供的URL來測試我的機器人時,我得到以下信息:

https:// {您的域} .azurewebsites.net / api / messages {"code":"MethodNotAllowed","message":"GET is not allowed"}

並來自https:// {your-domain} .azurewebsites.net

{"code":"ResourceNotFound","message":"/ does not exist"}

我搜尋了互聯網,試圖找到一個解決方案,發現的所有解決方案都使用舊版本的框架,並指向index.js中沒有的server.get方法。

如果我可以提供更多信息,請告訴我。

這是index.js中的代碼

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// index.js is used to setup and configure your bot

// Import required packages
const path = require('path');
const restify = require('restify');

// Import required bot services. See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter, ConversationState, InputHints, MemoryStorage, UserState } = require('botbuilder');
const { FlightBookingRecognizer } = require('./dialogs/flightBookingRecognizer');

// This bot's main dialog.
const { DialogAndWelcomeBot } = require('./bots/dialogAndWelcomeBot');
const { MainDialog } = require('./dialogs/mainDialog');

// the bot's booking dialog
const { BookingDialog } = require('./dialogs/bookingDialog');
const BOOKING_DIALOG = 'bookingDialog';

// Note: Ensure you have a .env file and include LuisAppId, LuisAPIKey and LuisAPIHostName.
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });

// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about adapters.
const adapter = new BotFrameworkAdapter({
    appId: process.env.MicrosoftAppId,
    appPassword: process.env.MicrosoftAppPassword
});

// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
    // This check writes out errors to console log
    // NOTE: In production environment, you should consider logging this to Azure
    //       application insights.
    console.error(`\n [onTurnError]: ${ error }`);
    // Send a message to the user
    const onTurnErrorMessage = `Sorry, it looks like something went wrong!`;
    await context.sendActivity(onTurnErrorMessage, onTurnErrorMessage, InputHints.ExpectingInput);
    // Clear out state
    await conversationState.delete(context);
};

// Define a state store for your bot. See https://aka.ms/about-bot-state to learn more about using MemoryStorage.
// A bot requires a state store to persist the dialog and user state between messages.

// For local development, in-memory storage is used.
// CAUTION: The Memory Storage used here is for local bot debugging only. When the bot
// is restarted, anything stored in memory will be gone.
const memoryStorage = new MemoryStorage();
const conversationState = new ConversationState(memoryStorage);
const userState = new UserState(memoryStorage);

// If configured, pass in the FlightBookingRecognizer.  (Defining it externally allows it to be mocked for tests)
const { LuisAppId, LuisAPIKey, LuisAPIHostName } = process.env;
const luisConfig = { applicationId: LuisAppId, endpointKey: LuisAPIKey, endpoint: `https://${ LuisAPIHostName }` };

const luisRecognizer = new FlightBookingRecognizer(luisConfig);

// Create the main dialog.
const bookingDialog = new BookingDialog(BOOKING_DIALOG);
const dialog = new MainDialog(luisRecognizer, bookingDialog);
const bot = new DialogAndWelcomeBot(conversationState, userState, dialog);

// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
    console.log(`\n${ server.name } listening to ${ server.url }`);
    console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
    console.log(`\nTo test your bot, see: https://aka.ms/debug-with-emulator`);
});

// Listen for incoming activities and route them to your bot main dialog.
server.post('/api/messages', (req, res) => {
    // Route received a request to adapter for processing
    adapter.processActivity(req, res, async (turnContext) => {
        // route to bot activity handler.
        await bot.run(turnContext);
    });
});

Bot Framework /api/messages端點配置為接受POST請求。 導航到https://{your-domain}.azurewebsites.net/api/messagesGET請求,這就是為什么得到“找不到資源”響應的原因。 “未找到資源”響應實際上告訴您您的機器人正在運行。 如果Web應用程序未運行或初始部署失敗,則會看到“正在尋找的資源已被刪除,名稱更改或暫時不可用”的消息。 只要“ Web聊天中的測試”有效,您就可以開始工作!

如果要將靜態HTML頁面添加到服務器,則建議對機器人進行一些更改。

直線令牌端點

首先,您應該將另一個端點添加到您的漫游器以生成直接令牌。 這是一個基本的實現。 有關更多詳細信息,我建議您查看“ 直接線路身份驗證”文檔。

// DirectLine Token
server.post('/directline/token', async (req, res) => {

    const id = (req.body && req.body.id)? `dl_${req.body.id}`: `dl_default_user`

    const options = {
        method: 'POST',
        headers: { 
            'Authorization': `Bearer ${process.env.directLineSecret}`,
            'Content-Type': 'application/json',
         },
        url: 'https://directline.botframework.com/v3/directline/tokens/generate', 
        data: {
            user: { id }
        }
    };

    try {
        const { data } = await axios(options);
        res.send(data);
    } catch ({ message }) {
        res.status(403);
        res.send({ message });
    }
});

服務靜態文件接下來,在根目錄中創建一個公共文件,並使用Restify serveStatic插件向您的機器人添加一個新的端點。 有關更多詳細信息,請參閱Restify插件文檔。

server.get('/*', restify.plugins.serveStatic({
    directory: path.join(__dirname, 'public'),
    default: 'index.html'
}));

index.html最后,在您的公共目錄中,創建一個index.html並添加以下代碼。 它被配置為從/directline/token端點請求令牌,並呈現Web Chat實例。

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>Web Chat: Full-featured bundle</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <style>
      html, body { height: 100% }
      body { margin: 0 }

      #webchat {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="webchat" role="main"></div>
    <script>
      (async function () {

        const res = await fetch('/directline/token', { method: 'POST' });
        const { token } = await res.json();

        window.WebChat.renderWebChat({
          directLine: window.WebChat.createDirectLine({ token })
        }, document.getElementById('webchat'));

        document.querySelector('#webchat > *').focus();
      })().catch(err => console.error(err));
    </script>
  </body>
</html>

希望這可以幫助!

暫無
暫無

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

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