

终止支持通知：2025年9月15日， AWS 我们将停止对Amazon Lex V1的支持。2025 年 9 月 15 日之后，您将无法再访问 Amazon Lex V1 控制台或 Amazon Lex V1 资源。如果您使用的是 Amazon Lex V2，请改为参阅 [Amazon Lex V2 指南](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 步骤 1：创建 Lambda 函数
<a name="gs2-prepare"></a>

首先，创建一个用于履行披萨订单的 Lambda 函数。您将在下一节中创建的 Amazon Lex 机器人中指定此函数。

**创建 Lambda 函数**



1. 登录 AWS 管理控制台 并打开 AWS Lambda 控制台，网址为[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)。

1. 选择**创建函数**。

1. 在**创建函数**页面上，选择**从 Scratch 开始创作**。

   因为您使用本练习中提供的自定义代码创建 Lambda 函数，因此请选择从头创建该函数。

   执行以下操作：

   1. 键入名称 (`PizzaOrderProcessor`)。

   1. 对于 **Runtime**，选择 Node.js 的最新版本。

   1. 对于 **Role**，选择 **Create new role from template(s)**。

   1. 输入新的角色名称 (`PizzaOrderProcessorRole`)。

   1. 选择**创建函数**。

1. 在函数页面上，执行以下操作：

   在 **Function code** 部分中，选择 **Edit code inline**，然后复制以下 Node.js 函数代码并将其粘贴到窗口中。

   ```
   'use strict';
        
   // Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled ("Thanks, your pizza will arrive in 20 minutes")
   function close(sessionAttributes, fulfillmentState, message) {
       return {
           sessionAttributes,
           dialogAction: {
               type: 'Close',
               fulfillmentState,
               message,
           },
       };
   }
    
   // --------------- Events -----------------------
    
   function dispatch(intentRequest, callback) {
       console.log(`request received for userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`);
       const sessionAttributes = intentRequest.sessionAttributes;
       const slots = intentRequest.currentIntent.slots;
       const crust = slots.crust;
       const size = slots.size;
       const pizzaKind = slots.pizzaKind;
       
       callback(close(sessionAttributes, 'Fulfilled',
       {'contentType': 'PlainText', 'content': `Okay, I have ordered your ${size} ${pizzaKind} pizza on ${crust} crust`}));
       
   }
    
   // --------------- Main handler -----------------------
    
   // Route the incoming request based on intent.
   // The JSON body of the request is provided in the event slot.
   export const handler = (event, context, callback) => {
       try {
           dispatch(event,
               (response) => {
                   callback(null, response);
               });
       } catch (err) {
           callback(err);
       }
   };
   ```

1. 选择**保存**。

## 使用示例事件数据测试 Lambda 函数
<a name="gs2-lambdafunction-test"></a>

在控制台中，使用示例事件数据手动调用 Lambda 函数，以对其进行测试。

**测试 Lambda 函数：**

1. 登录 AWS 管理控制台 并打开 AWS Lambda 控制台，网址为[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)。

1. 在 **Lambda 函数**页面上，选择 Lambda 函数 (`PizzaOrderProcessor).`)

1. 在函数页面上的测试事件列表中，选择 **Configure test events**。

1. 在 **Configure test event** 页面上，执行以下操作：

   1. 选择 **Create new test event**（新建测试事件）。

   1. 在 **Event name** 字段中，为事件输入名称 (`PizzaOrderProcessorTest`)。

   1. 将以下 Amazon Lex 事件复制到窗口中。

      ```
      {
        "messageVersion": "1.0",
        "invocationSource": "FulfillmentCodeHook",
        "userId": "user-1",
        "sessionAttributes": {},
        "bot": {
          "name": "PizzaOrderingApp",
          "alias": "$LATEST",
          "version": "$LATEST"
        },
        "outputDialogMode": "Text",
        "currentIntent": {
          "name": "OrderPizza",
          "slots": {
            "size": "large",
            "pizzaKind": "meat",
            "crust": "thin"
          },
          "confirmationStatus": "None"
        }
      }
      ```

1. 选择**创建**。

AWS Lambda 创建测试，然后返回到函数页面。选择**测试**，然后 Lambda 会运行您的 Lambda 函数。

在结果框中，选择 **Details**。控制台将在 **Execution result** 窗格中显示以下输出。

```
{
  "sessionAttributes": {},
  "dialogAction": {
    "type": "Close",
    "fulfillmentState": "Fulfilled",
    "message": {
      "contentType": "PlainText",
      "content": "Okay, I have ordered your large meat pizza on thin crust."
    }
}
```

## 下一个步骤
<a name="gs2-next-step-create-bot"></a>

[步骤 2：创建自动程序](gs2-create-bot.md)