butler/internal/modules/messenger/telegram/telegram.go

65 lines
1.5 KiB
Go
Raw Normal View History

package telegram
import (
"context"
"fmt"
2023-08-13 08:36:27 +00:00
"log"
"strconv"
"git.3crabs.ru/VLADIMIR/butler/internal/modules/messenger"
2023-09-17 16:06:00 +00:00
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
2023-08-13 08:36:27 +00:00
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
2023-08-13 08:36:27 +00:00
updates := bot.GetUpdatesChan(u)
return &messengerTelegram{
bot: bot,
updates: updates,
}, nil
}
func (m *messengerTelegram) GetMessage(ctx context.Context) (*messenger.Message, error) {
2023-08-13 08:36:27 +00:00
tgMsg := <-m.updates
2023-09-17 16:31:39 +00:00
log.Printf("get grom tg: %+v", tgMsg)
2023-09-17 16:06:00 +00:00
chatID := int64(0)
2023-09-17 16:12:58 +00:00
if tgMsg.Message != nil && tgMsg.Message.Chat != nil {
2023-09-17 16:06:00 +00:00
chatID = tgMsg.Message.Chat.ID
}
if chatID == 0 {
return nil, fmt.Errorf("get chat id error %+v", tgMsg)
}
2023-08-13 08:36:27 +00:00
msg := &messenger.Message{
2023-09-17 16:06:00 +00:00
ChatID: fmt.Sprintf("%d", chatID),
2023-08-13 08:36:27 +00:00
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 {
2023-08-13 08:36:27 +00:00
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
}