大家好,今天在本文中,我们将介绍如何创建聊天机器人并将其与 WhatsApp Cloud API 集成。我们还将使用 OpenAI 模型为这个聊天机器人提供大脑。

先决条件

要创建 WhatsApp 聊天机器人,您需要一些先决条件:

  • 元商业账户

  • 元开发者账号

  • OpenAI 账户

您可以使用现有的 Facebook 帐户轻松创建这些帐户或创建一个新帐户。

一旦您准备好所有这些,我们就可以开始通过在 Meta Developer 帐户中进行配置以启用 WhatsApp 集成。

配置

创建元应用

由于https://developers.facebook.com/apps/。

创建一个新应用程序。

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--ZzcGDeks--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/i4q5okp52n4qfier5e4t.png)

选择业务

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--haAHzIHl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/wbv78kyiv4rafmvsmtqi.png)

选择您的业务经理帐户并输入其他详细信息

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--r9QiAa9A--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/drgxog3717gz99w8h5m9.png)

点击 Create App 并创建您的应用程序。

添加WhatsApp集成

打开您的应用页面,您将登陆此屏幕。

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--WPOE8eNC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/ezvo1x40gafq2bd7bxsb.png)

向下滚动并找到 WhatsApp。点击设置

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--ycWGnSwa--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/wmafaq9tsh92dxe59par.png)

WhatsApp 配置

您将看到此屏幕。在这里,您被分配了一个临时令牌一个测试 WhatsApp 号码。我们将使用这些在该测试 WhatsApp 号码上发送和接收消息。将来,如果您愿意,您也可以连接实数,这将是一个合适的 WhatsApp Business 帐户。

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--ybjEsrSM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/sc06lfikhta4zjald6rv.png)

您必须配置几个收件人 WhatsApp 号码进行测试,最多可以添加 5 个号码。

显示的电话号码 ID 稍后将用于使用 WhatsApp Cloud API,因此请随身携带。

身份验证令牌

最后一项配置是生成身份验证令牌,该令牌将在与元 API 通信时使用。

登录https://business.facebook.com/并打开您的业务设置。

从左侧菜单导航到系统用户部分

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--GR5WXq9K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/b7cvkdj1a34b77skacgv.png)

您可以添加一个用户,或者如果它已经存在,请单击 Generate New Token

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--j0JIjTsM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/0r8zum32vrtgm4lvjwuv.png)

选择您之前创建的应用并检查 whatsapp\business_managementwhatsapp\business\messaging 权限,然后复制此令牌。

申请

所以我们将使用 NodeJS 和 Express 开发我们的应用程序

我们将安装基本依赖项,例如express``morgan``helmet``cors``axios``dotenv

我们将创建两条 API 路由,一条用于验证 webhook(仅使用一次),一条用于接收来自 WhatsApp 的消息/更新

  • GET/api/webhook- 验证这个 webhook

  • POST/api/webhook- 接收来自 WhatsApp 的消息

因此,我们可以在 WhatsApp 中配置一个 webhook,以便每次收到消息或更新时,我们都会收到通知并做出相应的响应。

这个/api/webhook的 GET API 将用于验证这个 webhook,WhatsApp 将发送一个令牌和几个参数,我们将验证所有这些是否匹配我们服务器上配置的任何内容。它被称为验证令牌。我们创建一个随机长验证令牌并将其存储在我们服务器的环境变量中。

这将是我们的 GET/api/webhookAPI 路由

app.get("/api/webhook", (req, res) => {
  const VERIFY_TOKEN = process.env.VERIFY_TOKEN;

  // Parse params from the webhook verification request
  let mode = req.query["hub.mode"];
  let token = req.query["hub.verify_token"];
  let challenge = req.query["hub.challenge"];

  // Check if a token and mode were sent
  if (!mode || !token) {
    return res.status(403).send({ error: "Missing mode or token" });
  }

  // Check the mode and token sent are correct
  if (mode === "subscribe" && token === VERIFY_TOKEN) {
    // Respond with 200 OK and challenge token from the request
    console.log("WEBHOOK_VERIFIED");
    return res.status(200).send(challenge);
  } else {
    // Responds with '403 Forbidden' if verify tokens do not match
    return res.sendStatus(403);
  }
});

进入全屏模式 退出全屏模式

为了验证我们的 webhook,我们从 Meta App 页面转到 WhatsApp 配置

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--uDCOUaYu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/a2m3j0gr4uw34dydamo4.png)

添加 Webhook API URLVerification token 并点击 Verify and Save。如果您仍在开发中,您可以使用像 ngrok 这样的代理。 Webhook URL 必须是链中没有自签名证书的 HTTPS。

Webhook fields 中,订阅 messages

[图像描述](https://res.cloudinary.com/practicaldev/image/fetch/s--_YQbItKo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to- uploads.s3.amazonaws.com/uploads/articles/85eazr6civwi974zsp70.png)

现在对于接收消息 webhook,POST/api/webhook

app.post("/api/webhook", async (req, res) => {
  try {
    // Parse the request body from the POST
    const body = req.body;

    // Check the Incoming webhook message
    console.log("Incoming webhook: " + JSON.stringify(body));

    // Validate the webhook
    if (req.body.object) {
      // Handle the event
      if (req.body.object === "whatsapp_business_account") {
        const entry = req.body.entry[0];

        // Handle the message
        if (entry.changes) {
          for (const change of entry.changes) {
            if (
              change.value &&
              change.field === "messages" &&
              change.value.contacts &&
              change.value.messages
            ) {
              // Handle the value
              const value = change.value;

              const userName = value.contacts[0].profile.name;

              const messages = value.messages;

              // Handle messages
              for (const message of messages) {
                if (
                  message.type === "text" &&
                  message.text &&
                  message.text.body
                ) {
                  const waid = message.from;
                  const text = message.text.body;
                  const msgId = message.id;
                  console.log(
                    "Message from " + waid + " - " + userName + ": " + text
                  );
                }
              }
            }
          }
        }
      }
    }
  } catch (err) {
    console.error("Error occured " + err);
  }
});

进入全屏模式 退出全屏模式

这就是当用户在配置的号码上发送文本消息时,我们将从传入的 webhook 中提取消息的方式。我们可以使用这条短信,然后相应地回复。

对于我们的应用程序,我们将其作为提示传递给 OpenAPI 模型,然后从 AI 获得响应并响应用户。我们为此使用openai包。

为了响应用户,我们将使用https://graph.facebook.com/v13.0/<phonenumberid>/messagesAPI 端点和我们之前在 Headers 中收集的身份验证令牌,如下所示:

  await axios.post(
    process.env.WHATSAPP_SEND_MESSAGE_API,
    {
      messaging_product: "whatsapp",
      recipient_type: "individual",
      to: waid,
      type: "text",
      text: {
        preview_url: false,
        body: reply,
      },
    },
    {
      headers: {
        Authorization: "Bearer " + process.env.WHATSAPP_TOKEN,
      },
    }
  );

进入全屏模式 退出全屏模式

通过此响应将发送给用户。

结论

这就是我们将如何使用 WhatsApp Cloud API 并将 WhatsApp 与您的应用程序集成的方式。自从 Meta 最近将这个 API 提供给所有人以来,有无限的可能性,而这个 API 之前只提供给企业主或 BSP(业务服务合作伙伴)。

文档:https://developers.facebook.com/docs/whatsapp/cloud-api/reference

Logo

ModelScope旨在打造下一代开源的模型即服务共享平台,为泛AI开发者提供灵活、易用、低成本的一站式模型服务产品,让模型应用更简单!

更多推荐