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

58 lines
1.3 KiB
Go

package telegram
import (
"context"
"fmt"
"log"
"strconv"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"git.3crabs.ru/VLADIMIR/butler/internal/modules/messenger"
)
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
msg := &messenger.Message{
ChatID: fmt.Sprintf("%d", tgMsg.Message.Chat.ID),
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
}