Botstate
The easy way to manage bot states.
![GoDoc](https://godoc.org/github.com/gucastiliao/botstate?status.svg)
Simple Bot Flow with Botstate
![Botstate](https://github.com/gucastiliao/botstate/raw/HEAD/docs/botstate.png)
Examples
Installation
botstate requires a Go version with Modules support and uses import versioning. So please make sure to initialize a Go module before installing botstate:
go mod init
go get github.com/gucastiliao/botstate
Import:
import "github.com/gucastiliao/botstate"
Manage state
To manage states, botstate have a default client that uses go-redis, but you can make your own client to save state the way you prefer.
You need to initialize storage with your client.
This example is using go-redis with botstate.DefaultStorage:
r := redis.NewClient(&redis.Options{
Addr: mr.Addr(),
})
botstate.SetStorageClient(botstate.DefaultStorage(r))
If you have your own client:
var myClient botstate.Storager
...
botstate.SetStorageClient(myClient)
Simple Example
package main
import (
"fmt"
"github.com/go-redis/redis/v7"
"github.com/gucastiliao/botstate"
)
func main() {
redis := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", "127.0.0.1", "6379"),
Password: "",
})
botstate.SetStorageClient(
botstate.DefaultStorage(redis),
)
states := []botstate.State{
{
Name: "start",
Executes: Start,
Next: "add_product",
},
{
Name: "add_product",
Executes: AddProduct,
Callback: CallbackAddProduct,
Next: "confirmation",
},
{
Name: "confirmation",
Executes: Confirmation,
},
}
bot := botstate.New(states)
bot.Data.User(111)
bot.ExecuteState("start")
msg := bot.GetMessages()
fmt.Println(msg)
current, _ := bot.Data.GetCurrentState()
bot.ExecuteState(current)
msg = bot.GetMessages()
fmt.Println(msg)
current, _ = bot.Data.GetCurrentState()
bot.ExecuteState(current)
msg = bot.GetMessages()
fmt.Println(msg)
}
func Start(bot *botstate.Bot) bool {
bot.SendMessage([]string{
"Hello!",
"Starting...",
})
return true
}
func AddProduct(bot *botstate.Bot) bool {
bot.SendMessage([]string{
"Add Product...",
})
return true
}
func CallbackAddProduct(bot *botstate.Bot) bool {
fmt.Println("I'm in callback now!")
return true
}
func Confirmation(bot *botstate.Bot) bool {
bot.SendMessage([]string{
"Confirmation...",
})
bot.Data.ResetCurrentState()
return true
}
See more