An interesting project is the perfect place to start a new language.

By writing a small robot that can chat, set memos/regular reminders, search for American TV series/movies and other functions, I quickly mastered the Go language and fell in love with it.

At the end of the article will be given a small robot source code and examples of the text code links.

1. Set a small goal — start with a conversation

Getting the robot to “talk” is the first step, using an API provided by a third party service to get answers locally via HTTP requests and return them.




There are basically no difficulties in this stage. Take Go as an example, the key part is solved by dozens of lines of code:

//get reply from tlAI func tlAI(info string) string { tuLingURL := fmt.Sprintf("http://www.tuling123.com/openapi/api?key=%s&info=%s", tlKey, url.QueryEscape(info)) resp, err := http.Get(tuLingURL) if err ! = nil { log.Println(err) return "" } defer resp.Body.Close() reply := new(tlReply) decoder := json.NewDecoder(resp.Body)  //decode reply from response body decoder.Decode(reply) return reply.Text } type tlReply struct { code int Text string `json:"text"` }Copy the code

2. Better to share music than to share it with friends

After the first step, the robot has the basic dialogue function, and can now start to recruit friends to flirt with them. While the Go language can compile executable files for multiple platforms for sharing (including but not limited to Linux, Windows, Mac OS), there are many more convenient and elegant ways to do it.

2.1 wechat official account

Register a public account through wechat developer platform, plus a little bit of the above code can make it have dialogue function:




2.2 Web Sharing

Make the conversation more personal with a few simple front-end techniques: show the address online (voice enabled if the browser grants permission)




The front and back ends use WebSocket to communicate:

//used by web samaritan robot func socketHandler(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err ! = nil { log.Print("upgrade:", err) return } defer c.Close() for { mt, in, err := c.ReadMessage() // read from user input if err ! = nil { log.Println("read:", err) break } ret := tlAI(string(in)) // get reply from tl AI robot for i := range ret { c.WriteMessage(mt, []byte(ret[i])) time.Sleep(time.Second) } c.WriteMessage(mt, []byte("")) } }Copy the code

Through the WebSocket push function, so that the dialogue return effect (segmentation, speed limit) become controllable.

3. Increase skill points

It’s just a chat bot, so we’re starting to add new features. Take the simple example of adding a memo:




// SaveMemo create a memo for user, saved in redis
// command '/memo'
func (rb *Robot) SaveMemo(update tgbotapi.Update, step int) (ret string) {
    user := update.Message.Chat.UserName
    tmpAction := userAction[user]
    switch step {
    case 0:
        tmpAction.ActionStep++
        userAction[user] = tmpAction
        ret = "Ok, what do you want to save?"
    case 1:
        defer delete(userAction, user)
        when := time.Now().Format("2006-1-02 15:04")
        memo := update.Message.Text
        go conn.CreateMemo(user, when, memo)
        ret = "Ok, type '/memos' to see all your memos"
    }
    return
}Copy the code

In interactive mode, different responses are given based on user interaction status. Create Redis records asynchronously using go conn.CreateMemo(user, when, Memo). :

// CreateMemo saves a memo func CreateMemo(user, when, memo string) { c := Pool.Get() defer c.Close() var setMemoLua = ` local id = redis.call("INCR", "memoIncrId") redis.call("RPUSH", KEYS[1].." :memos", id) redis.call("HMSET", "memo:".. id, "time", KEYS[2], "content", KEYS[3]) ` script := redis.NewScript(3, setMemoLua) script.Do(c, user, when, memo) }Copy the code

4. The last

At this point, the writing of a robot is over. It is interesting to create a small robot from zero to one, but what is really interesting is the process from one to N. The ability of the small robot is as big as the imagination.

If you have any other interesting ideas, feel free to develop and play with us.

Robot: Has found the following resources for you