tss/telegram/telegram.go

100 lines
2.2 KiB
Go
Raw Normal View History

2022-05-01 23:28:54 -04:00
package telegram
import (
"bytes"
2022-05-02 13:24:29 -04:00
"context"
2022-05-01 23:28:54 -04:00
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
2022-05-02 13:24:29 -04:00
"time"
2022-05-01 23:28:54 -04:00
"go.balki.me/tss/log"
2022-05-02 13:24:29 -04:00
"golang.org/x/time/rate"
2022-05-01 23:28:54 -04:00
)
type TelegramSender interface {
SendLink(link, channel, rhash string) error
}
type telegramSender struct {
2022-05-02 13:24:29 -04:00
client *http.Client
authToken string
rateLimiterPerMin *rate.Limiter
rateLimiterPerSec *rate.Limiter
2022-05-01 23:28:54 -04:00
}
func (ts *telegramSender) SendLink(link string, channel string, rhash string) error {
msg := struct {
ChatID string `json:"chat_id"`
Text string `json:"text"`
ParseMode string `json:"parse_mode"`
2022-05-01 23:28:54 -04:00
}{
ChatID: channel,
Text: fmt.Sprintf(`<a href="%s">➢</a> <a href="%s">Link</a>`, genIVLink(link, rhash), link),
ParseMode: "HTML",
2022-05-01 23:28:54 -04:00
}
data, err := json.Marshal(msg)
if err != nil {
return err
}
apiUrl := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", ts.authToken)
2022-05-02 13:24:29 -04:00
err = ts.rateLimiterPerMin.Wait(context.TODO())
if err != nil {
return err
}
err = ts.rateLimiterPerSec.Wait(context.TODO())
if err != nil {
return err
}
2022-05-01 23:28:54 -04:00
res, err := ts.client.Post(apiUrl, "application/json", bytes.NewReader(data))
if err != nil {
return err
}
defer res.Body.Close()
responseText, err := io.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
log.Error("telegram send failed", "status", res.Status, "request", data, "response", responseText)
return errors.New("telegram send failed")
}
log.Info("sent message on telegram", "link", link, "channel", channel, "response", responseText)
return nil
}
func NewTelegramSender(transport http.RoundTripper, authToken string) TelegramSender {
return &telegramSender{
client: &http.Client{Transport: transport},
authToken: authToken,
2022-05-02 13:24:29 -04:00
// 20 requests per min with some buffer
rateLimiterPerMin: rate.NewLimiter(rate.Every(65*time.Second), 20),
// 1 msg per sec with some buffer
rateLimiterPerSec: rate.NewLimiter(rate.Every(1050*time.Millisecond), 1),
2022-05-01 23:28:54 -04:00
}
}
func genIVLink(link, rhash string) string {
2022-05-03 18:32:23 -04:00
if rhash == "" {
return link
}
2022-05-01 23:28:54 -04:00
query := url.Values{}
query.Set("url", link)
query.Set("rhash", rhash)
u := url.URL{
Scheme: "https",
Host: "t.me",
Path: "iv",
RawQuery: query.Encode(),
}
return u.String()
}