如何使用 Bird 的可编程对话 API 构建一个用于待办事项的 WhatsApp 机器人
鸟
2020年2月5日
1 min read

关键要点
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。
我想试试, 所以我创建了一个 WhatsApp 机器人待办事项列表,因为谁不需要一个自动化的待办事项列表来帮助组织他们的一天?这听起来可能很复杂,但实际上很简单,我想告诉你所有关于它的事情。
现在,我在 MessageBird 工作,所以我可以直接开始构建。如果你尝试这个,你将需要申请提前访问。但一旦你设置了一个 WhatsApp 渠道,你就可以登录 MessageBird 网站上的仪表盘并开始。
Bird 最近推出了可编程会话。它让公司能够将 WhatsApp、Messenger 和 SMS 等通信平台融合到他们的系统中——使用一个单一的 API。
我想试试, 所以我创建了一个 WhatsApp 机器人待办事项列表,因为谁不需要一个自动化的待办事项列表来帮助组织他们的一天?这听起来可能很复杂,但实际上很简单,我想告诉你所有关于它的事情。
现在,我在 MessageBird 工作,所以我可以直接开始构建。如果你尝试这个,你将需要申请提前访问。但一旦你设置了一个 WhatsApp 渠道,你就可以登录 MessageBird 网站上的仪表盘并开始。
Bird 最近推出了可编程会话。它让公司能够将 WhatsApp、Messenger 和 SMS 等通信平台融合到他们的系统中——使用一个单一的 API。
我想试试, 所以我创建了一个 WhatsApp 机器人待办事项列表,因为谁不需要一个自动化的待办事项列表来帮助组织他们的一天?这听起来可能很复杂,但实际上很简单,我想告诉你所有关于它的事情。
现在,我在 MessageBird 工作,所以我可以直接开始构建。如果你尝试这个,你将需要申请提前访问。但一旦你设置了一个 WhatsApp 渠道,你就可以登录 MessageBird 网站上的仪表盘并开始。
设置您的 WhatsApp bot 环境
The first thing I did was read the docs. 我了解到,为了从机器人获取消息,我必须使用一个webhook。这意味着我的机器人需要能够从互联网访问。构建这样的API时,遵循API versioning best practices对于可维护性非常重要。由于我刚刚开始编写代码,我决定使用ngrok。它会创建一个从公共互联网到你的本地端口5007的通道。Engage!
ngrok http 5007 -region eu -subdomain todobot
The first thing I did was read the docs. 我了解到,为了从机器人获取消息,我必须使用一个webhook。这意味着我的机器人需要能够从互联网访问。构建这样的API时,遵循API versioning best practices对于可维护性非常重要。由于我刚刚开始编写代码,我决定使用ngrok。它会创建一个从公共互联网到你的本地端口5007的通道。Engage!
ngrok http 5007 -region eu -subdomain todobot
The first thing I did was read the docs. 我了解到,为了从机器人获取消息,我必须使用一个webhook。这意味着我的机器人需要能够从互联网访问。构建这样的API时,遵循API versioning best practices对于可维护性非常重要。由于我刚刚开始编写代码,我决定使用ngrok。它会创建一个从公共互联网到你的本地端口5007的通道。Engage!
ngrok http 5007 -region eu -subdomain todobot
创建您的 webhook 并连接 Bird
接下来,我需要调用可编程会话 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 负载的样子:
{ "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") }
接下来,我需要调用可编程会话 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 负载的样子:
{ "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") }
接下来,我需要调用可编程会话 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 负载的样子:
{ "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 }
就是这样。这是您需要创建一个像五岁小孩一样行为的机器人的所有内容。
以下是使用 Bird 的 Conversations API 让 WhatsApp 机器人开发快速且可扩展的原因:
功能 | 解决的问题 |
|---|---|
统一的会话 ID | 在 WhatsApp、微信、Messenger 等应用中维护单一线程 |
单一API适用于所有频道 | 无需为每个平台重写代码即可重用机器人逻辑 |
基于 Webhook 的自动化 | 快速处理响应,无需轮询 |
存档+重新打开话题 | 组织支持历史记录和工作流程 |
并发安全结构 | 可靠地同时处理多个聊天 |
现在,让我们推动建设整个待办事项列表。首先,稍微修改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”是一个并发安全的映射,它将会话ID映射到待办事项列表。
待办事项列表是一个并发安全的字符串切片。所有都在内存中!
现在,进入令人感兴趣的部分。执行一个 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 }
就是这样。这是您需要创建一个像五岁小孩一样行为的机器人的所有内容。
以下是使用 Bird 的 Conversations API 让 WhatsApp 机器人开发快速且可扩展的原因:
功能 | 解决的问题 |
|---|---|
统一的会话 ID | 在 WhatsApp、微信、Messenger 等应用中维护单一线程 |
单一API适用于所有频道 | 无需为每个平台重写代码即可重用机器人逻辑 |
基于 Webhook 的自动化 | 快速处理响应,无需轮询 |
存档+重新打开话题 | 组织支持历史记录和工作流程 |
并发安全结构 | 可靠地同时处理多个聊天 |
现在,让我们推动建设整个待办事项列表。首先,稍微修改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”是一个并发安全的映射,它将会话ID映射到待办事项列表。
待办事项列表是一个并发安全的字符串切片。所有都在内存中!
现在,进入令人感兴趣的部分。执行一个 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 }
就是这样。这是您需要创建一个像五岁小孩一样行为的机器人的所有内容。
以下是使用 Bird 的 Conversations API 让 WhatsApp 机器人开发快速且可扩展的原因:
功能 | 解决的问题 |
|---|---|
统一的会话 ID | 在 WhatsApp、微信、Messenger 等应用中维护单一线程 |
单一API适用于所有频道 | 无需为每个平台重写代码即可重用机器人逻辑 |
基于 Webhook 的自动化 | 快速处理响应,无需轮询 |
存档+重新打开话题 | 组织支持历史记录和工作流程 |
并发安全结构 | 可靠地同时处理多个聊天 |
现在,让我们推动建设整个待办事项列表。首先,稍微修改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”是一个并发安全的映射,它将会话ID映射到待办事项列表。
待办事项列表是一个并发安全的字符串切片。所有都在内存中!
归档对话并扩展您的bot
另一件重要的事!您可以存档对话。在某些应用程序中,例如 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) 将会删除待办列表的对话。
但是编程会话是一个全渠道解决方案。如果您想将机器人的代码重用于不同的平台,例如微信,该怎么办?这种多渠道方法是将询问引导至成本较低渠道战略的一部分。您将如何实现?
只需创建一个新的 webhook 来定位该渠道!一个发送请求到我们用于 WhatsApp 的相同 https://todobot.eu.ngrok.io/create-hook url 的 webhook!
这将有效,因为处理程序代码总是使用来自 webhook 负载的 conversationID 来回复消息,而不是硬编码的 channelID。MessageBird 的 Conversations API 将自动确定用于发送消息的对话渠道。
您想构建自己的机器人吗?请查看 Github 上的完整代码:Wabot on Github,访问WhatsApp 页面并点击联系销售按钮填写表格,以申请 WhatsApp 的早期访问。祝您愉快的机器人开发!
另一件重要的事!您可以存档对话。在某些应用程序中,例如 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) 将会删除待办列表的对话。
但是编程会话是一个全渠道解决方案。如果您想将机器人的代码重用于不同的平台,例如微信,该怎么办?这种多渠道方法是将询问引导至成本较低渠道战略的一部分。您将如何实现?
只需创建一个新的 webhook 来定位该渠道!一个发送请求到我们用于 WhatsApp 的相同 https://todobot.eu.ngrok.io/create-hook url 的 webhook!
这将有效,因为处理程序代码总是使用来自 webhook 负载的 conversationID 来回复消息,而不是硬编码的 channelID。MessageBird 的 Conversations API 将自动确定用于发送消息的对话渠道。
您想构建自己的机器人吗?请查看 Github 上的完整代码:Wabot on Github,访问WhatsApp 页面并点击联系销售按钮填写表格,以申请 WhatsApp 的早期访问。祝您愉快的机器人开发!
另一件重要的事!您可以存档对话。在某些应用程序中,例如 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) 将会删除待办列表的对话。
但是编程会话是一个全渠道解决方案。如果您想将机器人的代码重用于不同的平台,例如微信,该怎么办?这种多渠道方法是将询问引导至成本较低渠道战略的一部分。您将如何实现?
只需创建一个新的 webhook 来定位该渠道!一个发送请求到我们用于 WhatsApp 的相同 https://todobot.eu.ngrok.io/create-hook url 的 webhook!
这将有效,因为处理程序代码总是使用来自 webhook 负载的 conversationID 来回复消息,而不是硬编码的 channelID。MessageBird 的 Conversations API 将自动确定用于发送消息的对话渠道。
您想构建自己的机器人吗?请查看 Github 上的完整代码:Wabot on Github,访问WhatsApp 页面并点击联系销售按钮填写表格,以申请 WhatsApp 的早期访问。祝您愉快的机器人开发!



