mvp before debug
This commit is contained in:
80
telegram/telegram.go
Normal file
80
telegram/telegram.go
Normal file
@ -0,0 +1,80 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"go.balki.me/tss/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("vim-go")
|
||||
}
|
||||
|
||||
type TelegramSender interface {
|
||||
SendLink(link, channel, rhash string) error
|
||||
}
|
||||
|
||||
type telegramSender struct {
|
||||
client *http.Client
|
||||
authToken string
|
||||
}
|
||||
|
||||
func (ts *telegramSender) SendLink(link string, channel string, rhash string) error {
|
||||
|
||||
msg := struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
Text string `json:"text"`
|
||||
}{
|
||||
ChatID: channel,
|
||||
Text: fmt.Sprintf(`<a href="%s">➢</a> <a href="%s">Link</a>`, genIVLink(link, rhash), link),
|
||||
}
|
||||
data, err := json.Marshal(msg)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
apiUrl := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", ts.authToken)
|
||||
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 {
|
||||
//TODO: Rate limit
|
||||
return &telegramSender{
|
||||
client: &http.Client{Transport: transport},
|
||||
authToken: authToken,
|
||||
}
|
||||
}
|
||||
|
||||
func genIVLink(link, rhash string) string {
|
||||
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()
|
||||
}
|
Reference in New Issue
Block a user