65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
package telegram
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"strconv"
|
|
|
|
"git.3crabs.ru/VLADIMIR/butler/internal/modules/messenger"
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
)
|
|
|
|
type messengerTelegram struct {
|
|
bot *tgbotapi.BotAPI
|
|
updates tgbotapi.UpdatesChannel
|
|
}
|
|
|
|
func NewMessengerTelegram(token string) (messenger.IMessenger, error) {
|
|
bot, err := tgbotapi.NewBotAPI(token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
log.Printf("Authorized on account %s", bot.Self.UserName)
|
|
u := tgbotapi.NewUpdate(0)
|
|
u.Timeout = 60
|
|
|
|
updates := bot.GetUpdatesChan(u)
|
|
return &messengerTelegram{
|
|
bot: bot,
|
|
updates: updates,
|
|
}, nil
|
|
}
|
|
|
|
func (m *messengerTelegram) GetMessage(ctx context.Context) (*messenger.Message, error) {
|
|
tgMsg := <-m.updates
|
|
log.Printf("get grom tg: %+v", tgMsg)
|
|
chatID := int64(0)
|
|
if tgMsg.Message != nil && tgMsg.Message.Chat != nil {
|
|
chatID = tgMsg.Message.Chat.ID
|
|
}
|
|
if chatID == 0 {
|
|
return nil, fmt.Errorf("get chat id error %+v", tgMsg)
|
|
}
|
|
msg := &messenger.Message{
|
|
ChatID: fmt.Sprintf("%d", chatID),
|
|
UserID: tgMsg.Message.From.UserName,
|
|
Text: tgMsg.Message.Text,
|
|
}
|
|
log.Println("get:", msg)
|
|
return msg, nil
|
|
}
|
|
|
|
func (m *messengerTelegram) SendMessage(ctx context.Context, msg *messenger.Message) error {
|
|
chatID, err := strconv.ParseInt(msg.ChatID, 10, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tgMsg := tgbotapi.NewMessage(chatID, msg.Text)
|
|
if _, err = m.bot.Send(tgMsg); err != nil {
|
|
return err
|
|
}
|
|
log.Println("send:", msg)
|
|
return nil
|
|
}
|