This repository has been archived on 2023-07-05. You can view files and clone it, but cannot push or open issues or pull requests.
clessy/broker/telegram.go

70 lines
1.5 KiB
Go
Raw Normal View History

2016-02-08 16:52:13 +00:00
package main
import (
2016-02-08 17:05:46 +00:00
"encoding/json"
"errors"
2016-02-08 16:52:13 +00:00
"log"
"net/http"
"net/url"
2016-02-09 10:33:38 +00:00
"strconv"
2016-02-09 14:55:37 +00:00
"github.com/hamcha/clessy/tg"
2016-02-08 16:52:13 +00:00
)
const APIEndpoint = "https://api.telegram.org/"
type Telegram struct {
Token string
}
func mkAPI(token string) *Telegram {
tg := new(Telegram)
tg.Token = token
return tg
}
2016-02-09 10:33:38 +00:00
func (t Telegram) SetWebhook(webhook string) {
2016-02-08 16:52:13 +00:00
resp, err := http.PostForm(t.apiURL("setWebhook"), url.Values{"url": {webhook}})
2016-02-09 10:33:38 +00:00
if !checkerr("SetWebhook", err) {
2016-02-08 16:52:13 +00:00
defer resp.Body.Close()
2016-02-08 17:05:46 +00:00
var result tg.APIResponse
err = json.NewDecoder(resp.Body).Decode(&result)
2016-02-08 16:52:13 +00:00
if err != nil {
2016-02-09 10:33:38 +00:00
log.Println("[SetWebhook] Could not read reply: " + err.Error())
2016-02-08 17:05:46 +00:00
return
2016-02-08 16:52:13 +00:00
}
if result.Ok {
log.Println("Webhook successfully set!")
} else {
2016-02-09 10:33:38 +00:00
log.Printf("[SetWebhook] Error setting webhook (errcode %d): %s\n", *(result.ErrCode), *(result.Description))
panic(errors.New("Cannot set webhook"))
}
2016-02-08 16:52:13 +00:00
}
}
2016-02-09 10:33:38 +00:00
func (t Telegram) SendTextMessage(data tg.ClientTextMessageData) {
postdata := url.Values{
"chat_id": {strconv.Itoa(data.ChatID)},
"text": {data.Text},
"parse_mode": {"HTML"},
}
if data.ReplyID != nil {
postdata["reply_to_message_id"] = []string{strconv.Itoa(*(data.ReplyID))}
}
_, err := http.PostForm(t.apiURL("sendMessage"), postdata)
checkerr("SendTextMessage", err)
}
2016-02-08 16:57:27 +00:00
func (t Telegram) apiURL(method string) string {
2016-02-08 16:52:13 +00:00
return APIEndpoint + "bot" + t.Token + "/" + method
}
2016-02-08 16:57:27 +00:00
func checkerr(method string, err error) bool {
2016-02-08 16:52:13 +00:00
if err != nil {
log.Printf("Received error with call to %s: %s\n", method, err.Error())
return true
}
return false
}