farmstar-survey-backend/pkg/telegram/telegram.go

53 lines
818 B
Go
Raw Normal View History

2024-02-05 14:05:28 +01:00
package telegram
import (
"context"
"errors"
"github.com/carlmjohnson/requests"
)
const (
endpoint = "https://api.telegram.org"
)
type (
TelegramClient struct {
endpoint string
chatID string
}
MessageInput struct {
ChatID string `json:"chat_id"`
Text string `json:"text"`
}
TgResponse struct {
Ok bool `json:"ok"`
}
)
func New(apiKey string) *TelegramClient {
return &TelegramClient{
endpoint: endpoint + "/bot" + apiKey + "/",
}
}
func (tg *TelegramClient) SendMessage(ctx context.Context, payload MessageInput) (bool, error) {
var resp TgResponse
if err := requests.
URL(tg.endpoint + "sendMessage").
BodyJSON(&payload).
ToJSON(&resp).
Fetch(ctx); err != nil {
return false, err
}
if !resp.Ok {
return false, errors.New("telegram error")
}
return true, nil
}