/
bot.go
75 lines (60 loc) · 1.93 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
// Package bot handles bot activities.
package bot
import (
"context"
"fmt"
"github.com/barahouei/clean-architecture-telegram-bot/configs"
"github.com/barahouei/clean-architecture-telegram-bot/handlers"
"github.com/barahouei/clean-architecture-telegram-bot/pkg/logger"
"github.com/barahouei/clean-architecture-telegram-bot/repositories"
"github.com/barahouei/clean-architecture-telegram-bot/services/account"
"github.com/barahouei/clean-architecture-telegram-bot/services/callback"
"github.com/barahouei/clean-architecture-telegram-bot/services/command"
"github.com/barahouei/clean-architecture-telegram-bot/services/message"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type bot struct {
handler *handler
logger logger.Logger
}
// New creates a new bot.
func New(db repositories.DB, logger logger.Logger) handlers.Bot {
acc := account.New(db, logger)
msg := message.New(db, logger)
cmd := command.New(db, logger)
call := callback.New(db, logger)
handler := handler{
logger: logger,
account: acc,
message: msg,
command: cmd,
callback: call,
}
return &bot{handler: &handler, logger: logger}
}
// Start starts the bot.
func (b *bot) Start(ctx context.Context, cfg configs.App, debugMode bool) error {
b.logger.Info("Bot Starting...")
tgbot, err := tgbotapi.NewBotAPI(cfg.Token)
if err != nil {
b.logger.Error(fmt.Errorf("can't connect to the bot: %v", err))
return err
}
tgbot.Debug = debugMode
b.logger.Info(fmt.Sprintf("Authorized on account %s", tgbot.Self.UserName))
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates := tgbot.GetUpdatesChan(u)
for update := range updates {
if update.Message != nil && update.Message.IsCommand() {
go b.handler.Command(ctx, tgbot, update)
} else if update.CallbackQuery != nil {
go b.handler.Callback(ctx, tgbot, update)
} else if update.Message != nil {
go b.handler.Message(ctx, tgbot, update)
} else {
continue
}
}
return nil
}