-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
86 lines (71 loc) · 2.73 KB
/
bot.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
package bf
import (
"sync"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var _ ChatBot = &ChatBotImpl{}
type ChatBotImpl struct {
// tgbot is a telegram bot api instance.
tgbot *tgbotapi.BotAPI
// chatHandlerLayers is a map of chat id to handler layer.
// Layer is set of handlers that are expected from some user.
// Example:
// John (id 1212) open "Say hi" screen. Now he can:
// - press button "Hi"
// - send text "Hello"
// - send voice message
// So for John there will be 3 handlers in layer "John". After John press button "Hi" layer will be wiped.
// Set with: RegisterIButton etc.
chatHandlerLayers map[int64]*HandlerLayer
// retryLayers previous layer.
retryLayers map[int64]*string
// defaultHandlerLayer is a layer that will be used if there is no chat-specific layer. Will not be wiped.
defaultHandlerLayer *HandlerLayer
layersMutex sync.RWMutex
retryLayersMutex sync.RWMutex
// middlewares that will be called before any handler. Set with RegisterMiddleware.
middlewares []MiddlewareFunc
// errorHandler is a function that will be called if any handler return error. Set with RegisterErrorHandler.
errorHandler ErrorHandlerFunc
// logger is a interface for logging. Use any logger that implements Logger interface.
// default is logrus.
logger Logger
// debug is a flag that enables debug features. Set with WithDebug.
debug bool
parseMode string
}
// NewBot creates new bot instance, base layer and starts cleaner.
// apikey - telegram bot api key generated by BotFather.
// opts - options for bot BotOption.
func NewBot(apikey string, opts ...BotOption) (*ChatBotImpl, error) {
chatBotInstance := &ChatBotImpl{
tgbot: nil,
chatHandlerLayers: make(map[int64]*HandlerLayer),
retryLayers: map[int64]*string{},
defaultHandlerLayer: nil,
layersMutex: sync.RWMutex{},
retryLayersMutex: sync.RWMutex{},
middlewares: make([]MiddlewareFunc, 0),
errorHandler: nil,
logger: logrus.New(),
debug: false,
parseMode: tgbotapi.ModeHTML,
}
for _, opt := range opts {
opt(chatBotInstance)
}
bot, err := tgbotapi.NewBotAPI(apikey)
if err != nil {
return chatBotInstance, errors.Wrap(err, "failed to create bot")
}
chatBotInstance.tgbot = bot
chatBotInstance.defaultHandlerLayer = chatBotInstance.NewLayer()
chatBotInstance.defaultHandlerLayer.ttl = time.Now().Add(time.Hour * 24 * 365 * 100) // we don't want to expire it
chatBotInstance.RegisterErrorHandler(chatBotInstance.defaultErrorHandler)
chatBotInstance.RegisterDefaultHandler(chatBotInstance.defaultEventHandler)
go chatBotInstance.cleaner()
return chatBotInstance, nil
}