-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
92 lines (77 loc) · 2.31 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// This file is part of Botgoram
// Botgoram is free software: see LICENSE.txt for more details.
package botgoram
import (
"fmt"
"log"
"os"
"github.com/Patrolavia/telegram"
)
// HelloState defines a state, in which we reply hello message to any user who send anything to bot.
type HelloState string
// this defines what we should do when entering this state
func (h HelloState) enter(msg *telegram.Message, current State, api telegram.API) error {
reply := fmt.Sprintf("Hello, %s.\nThe message type of previous message: %s",
msg.From.FirstName, current.Data().(string))
api.SendMessage(msg.From.Identifier(), reply, nil)
current.SetData(msgType(msg))
current.Transit(InitialState)
return nil
}
// this will register as fallback transitor, which will receive all messages if no other transitor.
func (h HelloState) fallbackTransitor(msg *telegram.Message, state State) (next string, err error) {
return string(h), nil
}
// state name
func (h HelloState) Name() string {
return string(h)
}
// fsm calls this method to register enter/leave actions.
func (h HelloState) Actions() (Action, Action) {
return h.enter, nil
}
// fsm calls this method to register transitors and/or generate state map
func (h HelloState) Transitors() []TransitorMap {
return []TransitorMap{
TransitorMap{
Transitor: h.fallbackTransitor,
State: "dispatch",
IsFallback: true,
},
TransitorMap{
IsHidden: true,
State: "",
Desc: "Work done, back to initial state",
},
}
}
func Example() {
token := os.Getenv("TOKEN")
if token == "" {
log.Fatal("Please fill your bot token into the environmental variable 'TOKEN' to use this example")
}
api := telegram.New(token, nil)
// validate token
if _, err := api.GetMe(); err != nil {
log.Fatalf("Failed to validate token: %s", err)
}
// create FSM
fsm := NewBySender(
api,
// store state data (a string) using default memory storage
MemoryStore(func(uid string) interface{} {
return "No previous message"
}),
10, // at most process 10 users' message at the same time
nil,
)
fsm.MakeState(HelloState("hello"))
// generate state map
fmt.Println(fsm.StateMap("initial state"))
// main loop, uncomment to do the real stuff
/*
for err := fsm.Start(30); err != nil; err = fsm.Resume() {
log.Printf("There is something goes wrong: %s", err)
}
*/
}