Repository navigation
Expand file tree
/
Copy pathtelegram.go
More file actions
97 lines (85 loc) · 2.2 KB
/
Copy pathtelegram.go
File metadata and controls
97 lines (85 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type Telegram struct {
c *http.Client
t string
u string
}
func NewTelegram(c *http.Client, token string) (*Telegram, error) {
tc := &Telegram{c: c, t: token}
if tc.c == nil {
tc.c = http.DefaultClient
}
var obj struct {
Username string `json:"username"`
}
if err := tc.api("getMe", nil, &obj); err != nil {
return nil, err
} else {
tc.u = obj.Username
}
return tc, nil
}
func (tc *Telegram) GetUsername() string {
return tc.u
}
func (tc *Telegram) GetChatUsername(id string) (string, error) {
var obj struct {
Username string `json:"username"`
}
if err := tc.api("getChat", url.Values{
"chat_id": {id},
}, &obj); err != nil {
return "", fmt.Errorf("get chat %#v: %w", id, err)
}
return obj.Username, nil
}
func (tc *Telegram) SendMessage(id, text string) error {
if err := tc.api("sendMessage", url.Values{
"chat_id": {id},
"text": {text},
"parse_mode": {"HTML"},
"disable_web_page_preview": {"true"},
}, nil); err != nil {
return fmt.Errorf("send message to %#v: %w", id, err)
}
return nil
}
func (tc *Telegram) api(method string, params url.Values, out interface{}) error {
var p string
if params != nil {
p = "?" + params.Encode()
}
req, err := http.NewRequest("GET", "https://api.telegram.org/bot"+tc.t+"/"+method+p, nil)
if err != nil {
return fmt.Errorf("create request: %w", err)
}
req.Header.Set("User-Agent", "kfwproxy (github.com/pgaskin/kfwproxy)")
resp, err := tc.c.Do(req)
if err != nil {
return fmt.Errorf("do request: %w", err)
}
defer resp.Body.Close()
var obj struct {
OK bool `json:"ok"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
Result json.RawMessage `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&obj); err != nil {
return fmt.Errorf("read response json: %w", err)
} else if !obj.OK {
return fmt.Errorf("api error: %s: %s (%d)", method, obj.Description, obj.ErrorCode)
}
if out != nil {
if err = json.Unmarshal(obj.Result, &out); err != nil {
return fmt.Errorf("parse result json: %w", err)
}
}
return nil
}