跳至內容

會話機器人/一個簡單的回顯機器人

來自 Wikibooks,為開放世界創作開放書籍

如何構建會話機器人?機器人是提供 API 的伺服器應用程式,因此你需要一個可以公開訪問的伺服器來託管你的機器人。如果你沒有,你可以使用例如提供免費層的 Amazon 的 EC2。通常情況下,可以使用執行用 Go 編寫的應用程式的所有伺服器。你也許還希望下載此免費iOS 應用程式以測試你的程式碼。

以下是簡單回顯機器人的程式碼,它只輸出回顯:後跟使用者輸入。在將其儲存到echobot.go後,使用go run echobot.go執行該程式碼。

package main

import (
    "net/http"
    "log"
    "encoding/json"
    "fmt"
)

func Server(w http.ResponseWriter, req *http.Request) {
    if req.Method == "GET" {
        if req.RequestURI == "/info" {
            data := map[string]interface{}{ "name": "Echo Bot", "info": "A simple echo bot" }
            b,_ := json.Marshal(data)
            w.Header().Set("Content-Type", "text/plain;charset=utf-8")
            w.Write(b)
        }
    }
    if req.Method == "POST" {
        if req.RequestURI == "/msg" {
            decoder := json.NewDecoder(req.Body)
            var data interface{}
            err := decoder.Decode(&data)
            if err != nil {
                fmt.Println("couldn't decode JSON data")
            } else {
                m := data.(map[string]interface{})
                //user := m["user"].(string)
                text := m["text"].(string)
                resp := "Echo: " + text
                data := map[string]interface{}{ "text": resp }
                b,_ := json.Marshal(data)
                w.Header().Set("Content-Type", "text/plain;charset=utf-8")
                w.Write(b)
            }
        }
    }
}

func main() {
    http.HandleFunc("/", Server)
    err := http.ListenAndServe(":8090", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
華夏公益教科書