1
0
Fork 0

Little refactoring

This commit is contained in:
Michał Rudowicz 2024-03-10 23:30:15 +01:00
parent a7eb36aa92
commit 050dcbe72b
3 changed files with 71 additions and 30 deletions

31
main.go
View File

@ -21,33 +21,6 @@ const (
PersistenceFilename = "hs_wro_last_seen.bin"
)
type TgSender struct {
bot *tgbotapi.BotAPI
s SatelNameGetter
logger *log.Logger
chatIds []int64
}
func (self TgSender) Send(msg GenericMessage, tpl *template.Template) error {
if len(self.chatIds) == 0 {
return nil
}
message := msg.Format(tpl, self.s, self.logger)
for _, chatId := range self.chatIds {
toSend := tgbotapi.NewMessage(chatId, message)
toSend.ParseMode = "HTML"
_, err := self.bot.Send(toSend)
if err != nil {
return err
}
}
return nil
}
func sendTgMessage(tgEvents chan GenericMessage, msg []satel.BasicEventElement, chatId int64) {
tgEvents <- GenericMessage{msg}
}
type RealSleeper struct {
duration time.Duration
}
@ -162,9 +135,7 @@ func main() {
FilterByLastSeen(s.Events, &wg, &dataStore, log.New(os.Stderr, "FilterByLastSeen", log.Lmicroseconds)),
&wg, allowedTypes, allowedIndexes) {
logger.Print("Received change from SATEL: ", e)
for _, chatId := range chatIds {
sendTgMessage(tgEvents, e.BasicEvents, chatId)
}
tgEvents <- GenericMessage{e.BasicEvents}
}
close(tgEvents)

35
telegram_utils.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"html/template"
"log"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TelegramBotSender interface {
Send(c tgbotapi.Chattable) (tgbotapi.Message, error)
}
type TgSender struct {
bot TelegramBotSender
s SatelNameGetter
logger *log.Logger
chatIds []int64
}
func (self TgSender) Send(msg GenericMessage, tpl *template.Template) error {
if len(self.chatIds) == 0 {
return nil
}
message := msg.Format(tpl, self.s, self.logger)
for _, chatId := range self.chatIds {
toSend := tgbotapi.NewMessage(chatId, message)
toSend.ParseMode = "HTML"
_, err := self.bot.Send(toSend)
if err != nil {
return err
}
}
return nil
}

35
telegram_utils_test.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"html/template"
"io"
"log"
"testing"
"git.sr.ht/~michalr/go-satel"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/stretchr/testify/assert"
)
type MockTgBotAPI struct {
callCount int
}
func (self *MockTgBotAPI) Send(c tgbotapi.Chattable) (tgbotapi.Message, error) {
self.callCount += 1
return tgbotapi.Message{}, nil
}
var (
tgSenderMessageTest1 = satel.BasicEventElement{Type: satel.ArmedPartition, Index: 1, Value: true}
)
func TestTelegramSender_NoChatIdsWontSendAnything(t *testing.T) {
a := assert.New(t)
tpl := template.Must(template.New("TelegramMessage").Parse(""))
mockBot := MockTgBotAPI{0}
tested := TgSender{&mockBot, MockSatelNameGetter{"mockPart"}, log.New(io.Discard, "", 0), []int64{}}
tested.Send(GenericMessage{[]satel.BasicEventElement{tgSenderMessageTest1}}, tpl)
a.Equal(0, mockBot.callCount)
}