如何使用 Bird 的可编程对话 API 构建一个用于待办事项的 WhatsApp 机器人

2020年2月5日

WhatsApp

1 min read

如何使用 Bird 的可编程对话 API 构建一个用于待办事项的 WhatsApp 机器人

关键要点

    • Bird’s Programmable Conversations API 统一了WhatsApp、Messenger 和 SMS 到一个单一通信层,简化了多渠道机器人的开发。

    • 您可以使用webhooks简单的 POST 请求 快速原型化一个 WhatsApp 任务清单机器人。

    • ngrok 这样的工具可以让您暴露本地服务器,用于 webhook 测试,而无需复杂的托管设置。

    • API 处理 跨多个渠道的对话,允许一个逻辑基础来应对 WhatsApp、WeChat 和其他应用程序。

    • 使用 archiveConversation 端点来 关闭对话 或“主题”,这对于支持或工作流程跟踪非常理想。

    • 机器人逻辑可以借助一个简单的数据结构安全地 在内存中管理并发对话

    • 同一个 webhook 处理程序适用于所有渠道—Bird 自动根据发起的对话 ID 路由回复。

Q&A 精华

  • 使用Bird的API构建一个WhatsApp bot有多难?

    这其实很简单。通过一个 webhook 和几个 API 调用,您可以在几分钟内建立一个读取和回复消息的功能性机器人。

  • 我需要特殊设置才能接收消息吗?

    是的 — 机器人必须可以从互联网访问。像 ngrok 这样的工具有助于从本地机器创建一个安全的通道。

  • 我可以使用相同的代码库用于不同的消息应用程序吗?

    绝对可以。Conversations API 抽象了渠道,因此您的 bot 可以在 WhatsApp、WeChat 或 Messenger 上使用相同的逻辑运行。

  • 我如何关闭或重置聊天线程?

    发送 PATCH 请求到会话的终端点并使用适当的状态来将其存档。任何新消息会自动打开一个新会话。

  • 我在哪里可以找到示例代码?

    A: 完整的工作演示—Wabot on GitHub—展示了消息处理、并发和存档的实现。

Bird 最近推出了可编程对话。它使公司能够将 WhatsApp、Messenger 和 SMS 等通信平台融入他们的系统——使用一个单一的 API。

Bird最近推出了Programmable Conversations。它让公司能够将像WhatsApp、Messenger和SMS这样的通信平台融合到他们的系统中——使用单一的API。

我想试试,所以我构建了一个WhatsApp机器人待办事项列表,因为谁不需要一个自动化的待办事项列表来帮助整理他们的日子呢?这听起来可能很复杂,但实际上很简单,我想告诉你们关于它的一切。

现在,我在MessageBird工作,所以我可以直接开始构建。如果你尝试这个,你需要申请提前访问。但是一旦你设置了WhatsApp频道,你可以登录MessageBird网站上的Dashboard并开始。

我首先做的事情是阅读文档。我了解到,为了从机器人获取消息,我必须使用一个webhook。这意味着我的机器人需要能够从互联网访问。在构建这样的API时,遵循API版本化最佳实践对可维护性至关重要。由于我才开始编写代码,我决定使用ngrok。它创建了一个从公共互联网到你亲爱的localhost端口5007的隧道。参与!

ngrok http 5007 -region eu -subdomain todobot

接下来,我需要调用Programmable Conversations API以创建webhook。这是发送一个POST到https://conversations.messagebird.com/v1/webhooks,看起来像这样:


func main() {// define the webhook json payload
  wh := struct {
         Events    []string `json:"events"`
         ChannelID string   `json:"channelId"`
         URL       string   `json:"url"`
  } {
    // we would like to be notified on the URL
    URL:       "https://todobot.eu.ngrok.io/create-hook",
    // whenever a message gets created
    Events:    []string{"message.created"},
    // on the WhatsApp channel with ID
    ChannelID: "23a780701b8849f7b974d8620a89a279",
  }
  
  // encode the payload to json
  var b bytes.Buffer
  err := json.NewEncoder(&b).Encode(&wh)
  if err != nil {
    panic(err)
  }
  
  // create the http request and set authorization header
  req, err := http.NewRequest("POST", "https://conversations.messagebird.com/v1/webhooks", &b)
  req.Header.Set("Authorization", "AccessKey todo-your-access-key")
  req.Header.Set("Content-Type", "application/json") // fire the http request
  client := &http.Client{}
  resp, err := client.Do(req)
  if err != nil {
         panic(err)
  }
  defer resp.Body.Close()// is everything ok?
  body, _ := ioutil.ReadAll(resp.Body)
  if resp.StatusCode >= http.StatusBadRequest {
    panic(fmt.Errorf("Bad response code from api when trying to create webhook: %s. Body: %s", resp.Status, string(body)))
  } else {
    log.Println("All good. response body: ", string(body))
  }
}

很好。现在Conversations API将对其发送一个POST请求至:

https://todobot.eu.ngrok.io/create-hook每当在你之前设置的WhatsApp频道上创建新的消息。

这是webhook payload的样子:


{
  "conversation":{
    "id":"55c66895c22a40e39a8e6bd321ec192e",
    "contactId":"db4dd5087fb343738e968a323f640576",
    "status":"active",
    "createdDatetime":"2018-08-17T10:14:14Z",
    "updatedDatetime":"2018-08-17T14:30:31.915292912Z",
    "lastReceivedDatetime":"2018-08-17T14:30:31.898389294Z"
  },
  "message":{
    "id":"ddb150149e2c4036a48f581544e22cfe",
    "conversationId":"55c66895c22a40e39a8e6bd321ec192e",
    "channelId":"23a780701b8849f7b974d8620a89a279",
    "status":"received",
    "type":"text",
    "direction":"received",
    "content":{
      "text":"add buy milk"
    },
    "createdDatetime":"2018-08-17T14:30:31.898389294Z",
    "updatedDatetime":"2018-08-17T14:30:31.915292912Z"
  },
  "type":"message.created"
}

我们想回答这些消息。让我们从回显它们开始,你说呢?


// define the structs where we'll parse the webhook payload into
type whPayload struct {
  Conversation conversation `json:"conversation"`
  Message      message      `json:"message"`
  Type         string       `json:"type"`
}

type message struct {
  ID        string  `json:"id"`
  Direction string  `json:"direction"`
  Type      string  `json:"type"`
  Content   content `json:"content"`
}

type content struct {
  Text string `json:"text"`
}

type conversation struct {
  ID string `json:"id"`
}

func main() {
  http.HandleFunc("/create-hook", createHookHandler)
  log.Fatal(http.ListenAndServe(*httpListenAddress, nil))
}
// createHookHandler is an http handler that will handle webhook requests
func createHookHandler(w http.ResponseWriter, r *http.Request) {
  // parse the incoming json payload
  whp := &whPayload{}
  err := json.NewDecoder(r.Body).Decode(whp)
  if err != nil {
    log.Println("Err: got weird body on the webhook")
    w.WriteHeader(http.StatusInternalServerError)
    fmt.Fprintf(w, "Internal Server Error")
    return
  } 
  if whp.Message.Direction != "received" {
    // you will get *all* messages on the webhook. Even the ones this bot sends to the channel. We don't want to answer those.
    fmt.Fprintf(w, "ok")
    return
  } // echo: respond what we get
  err = respond(whp.Conversation.ID, whp.Message.Content.Text)
  
  if err != nil {
    log.Println("Err: ", err)
    w.WriteHeader(http.StatusInternalServerError)
    fmt.Fprintf(w, "Internal Server Error")return
  }
  w.WriteHeader(http.StatusOK)
  fmt.Fprintf(w, "ok")
}

现在,到了有趣的部分。执行POST请求至:

https://conversations.messagebird.com/v1/conversations/<conversationID>/messages以回答请求。


func respond(conversationID, responseBody string) error {
  u := fmt.Sprintf("https://conversations.messagebird.com/v1/conversations/%s/messages", conversationID)msg := message{
  Content: content{
    Text: responseBody,
  },
  Type: "text",
  }
  var b bytes.Buffer
  err := json.NewEncoder(&b).Encode(&msg)
  if err != nil {
    return fmt.Errorf("Error encoding buffer: %v", err)
  }
  req, err := http.NewRequest("POST", u.String(), &b)
  req.Header.Set("Authorization", "AccessKey todo-your-access-key")
  req.Header.Set("Content-Type", "application/json")client := &http.Client{}
  resp, err := client.Do(req)
  if err != nil {
    return err
  }
  defer resp.Body.Close()body, _ := ioutil.ReadAll(resp.Body)
  if resp.StatusCode != http.StatusCreated {
    return fmt.Errorf("Bad response code from api when trying to create message: %s. Body: %s", resp.Status, string(body))
  }
  log.Println("All good. Response body: ", string(body))
  return nil
}

好了。这就是你创建一个像5岁人类行为的机器人的全部所需部分。

现在,让我们推动构建整个待办事项列表。首先,稍微修改createHookHandler函数,使其调用新的handleMessage函数而不是respond。

func createHookHandler(w http.ResponseWriter, r *http.Request) {
  ...
  err = handleMessage(whp)
  ...
}

handle将简单地解析消息,做一些工作,并选择响应。让我们来看“add”命令:

func handleMessage(whp *whPayload) error {
  // every conversation has a todo list
  list := manager.fetch(whp.Conversation.ID)
  // parse the command from the message body: it's the first word
  text := whp.Message.Content.Text
  text = regexp.MustCompile(" +").ReplaceAllString(text, " ")
  parts := strings.Split(text, " ")
  command := strings.ToLower(parts[0])
  // default message
  responseBody := "I don't understand. Type 'help' to get help."
  switch command {
  ...
  case "add":
    if len(parts) < 2 {
           return respond(whp.Conversation.ID, "err... the 'add' command needs a second param: the todo item you want to save. Something like 'add buy milk'.")
    }
    // get the item from the message body
    item := strings.Join(parts[1:], " ")list.add(item)
    responseBody = "added."
  ...
  return respond(whp.Conversation.ID, responseBody)
}

这里,我们设置了:list := manager.fetch(whp.Conversation.ID)。基本上,“manager”是一个并发安全的映射,将conversation ID映射到待办事项列表。

待办事项列表是一个并发安全的字符串片段。全部在内存中!

另一件重要的事情!你可以归档对话。在一些应用程序中,例如CRM,记住某些互动很重要——例如跟踪客户支持员工的有效性。Conversations API让你可以归档一个对话来“关闭”主题。如果用户/客户发送另一条消息,Conversations API将自动打开一个新主题。

此外,执行PATCH请求到https://conversations.messagebird.com/v1/conversations/{id}并在正文中设置正确的状态可以让你归档带该id的对话。我们使用“bye”命令来实现:

case "bye":
  archiveConversation(whp.Conversation.ID)
  manager.close(whp.Conversation.ID)
  responseBody = "bye!"

archiveConversation将执行PATCH请求,manager.close(whp.Conversation.ID)将删除待办事项列表对话。

但是嘿,Programmable Conversations是一个全渠道解决方案。如果你想为不同的平台,如WeChat重复利用机器人的代码,该怎么办?这种多渠道方法是将问询转移到降低成本渠道策略的一部分。你会如何去做呢?

只需创建一个新的webhook以目标该频道即可!一个发送请求到我们为WhatsApp使用的同一个https://todobot.eu.ngrok.io/create-hook URL的webhook!

这将行得通,因为处理代码总是使用来自webhook payload的conversationID来回答消息,而不是硬编码的channelID。MessageBird的Conversations API将自动确定对话所在的频道,以便发送你的消息。

你想创建自己的机器人吗?查看Github上的完整代码:Wabot on Github,访问WhatsApp页面并点击联系销售按钮填写表格,申请提前访问WhatsApp。祝努力编写机器人愉快!

其他新闻

阅读更多来自此类别的内容

A person is standing at a desk while typing on a laptop.

这个完整的AI原生平台可以随着您的业务进行扩展。

© 2025 Bird

A person is standing at a desk while typing on a laptop.

这个完整的AI原生平台可以随着您的业务进行扩展。

© 2025 Bird