项目作者: dyrkin

项目描述 :
Design a bot's conversation flow
高级语言: Go
项目地址: git://github.com/dyrkin/flow.git
创建时间: 2018-11-22T20:22:08Z
项目社区:https://github.com/dyrkin/flow

开源协议:

下载


Flow - Design and control conversation flow

Overview

Model the structured conversation flow between the user and a chatbot, or between whatever you want.

A Simple Example

  1. import (
  2. "fmt"
  3. . "github.com/dyrkin/flow"
  4. )
  5. //Human data storage
  6. type UserData struct {
  7. login string
  8. password string
  9. }
  10. //bot emulator
  11. func newBot(humanChan chan string) *Flow {
  12. var awaitCommand *Step
  13. var askEmail *Step
  14. var askPassword *Step
  15. //wait for command from human
  16. awaitCommand =
  17. OnReply(func(msg Message, data Data) *NextStep {
  18. switch msg {
  19. case "register":
  20. return Goto(askEmail).Using(&UserData{})
  21. case "quit":
  22. return End()
  23. }
  24. return DefaultHandler()(msg, data)
  25. })
  26. //ask human for email
  27. askEmail =
  28. Ask(func(data Data) {
  29. humanChan <- "please send your email"
  30. }).OnReply(func(msg Message, data Data) *NextStep {
  31. email := msg.(string)
  32. humanData := data.(*UserData)
  33. humanData.login = email
  34. return Goto(askPassword)
  35. })
  36. //ask human for password
  37. askPassword =
  38. Ask(func(data Data) {
  39. humanChan <- "please send your password"
  40. }).OnReply(func(msg Message, data Data) *NextStep {
  41. password := msg.(string)
  42. humanData := data.(*UserData)
  43. humanData.password = password
  44. return End().Using(humanData)
  45. })
  46. return New(awaitCommand)
  47. }
  48. func main() {
  49. humanChan := make(chan string)
  50. //bot conversation flow
  51. bot := newBot(humanChan)
  52. go func() {
  53. messages := []string{"some@email.com", "some password"}
  54. index := 0
  55. for {
  56. select {
  57. case <-humanChan:
  58. bot.Send(messages[index])
  59. index++
  60. }
  61. }
  62. }()
  63. dataChan := bot.Start()
  64. bot.Send("register")
  65. collectedData := <-dataChan
  66. fmt.Println(collectedData)
  67. }

The basic strategy is to define Steps and specifying initial step while instantiating the Flow:

  • New(<initial step>) creates a flow with the initial step specified.
  • Start() starts the flow and returns a chan where the collected data will be sent after end of the flow.
  • Ask(<data fn>) executes immediately after Start() is called.
  • OnReply(<message fn>) executes when a data from the user is received.
  • <message fn> must return next step or end the flow

The code will produce the following output:

UserData{login: “some@email.com”, password: “some password”}

Full working example can be found there: example/conversation.go