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

58 lines
1.3 KiB
Go
Raw Normal View History

package telegram
import (
"context"
"fmt"
2023-08-13 08:36:27 +00:00
"log"
"strconv"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"git.3crabs.ru/VLADIMIR/butler/internal/modules/messenger"
)
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
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 {
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
}