Conversational bots/A simple echo bot

From Wikibooks, open books for an open world
Jump to navigation Jump to search

How to build a conversational bot? Bots are server apps that provide an API so you will need a publicly accessible server to host your bot(s). If you have none, you can use for example Amazon's EC2 which provides a free tier. In general, any server on which one can run apps written in Go can be used. You may also want to download this free iOS app in order to test out your code.

Below is the code of a simple echo bot that just outputs Echo: followed but the user's input. After saving it to echobot.go, run the code using 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)
    }
}