-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook.go
More file actions
93 lines (70 loc) · 2 KB
/
webhook.go
File metadata and controls
93 lines (70 loc) · 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
package telebot
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/url"
)
// Set the webhook according to the bot config.
func (b *Bot) setWebhook() (string, error) {
// Set the webhook with Telegram /setWebhook API endpoint.
res, err := http.PostForm(
telegramApiBaseUrl+b.apiToken+setWebhookEndpoint,
url.Values{
"url": {b.config["WebhookUrl"] + b.apiToken},
"ip_address": {b.config["IPAddress"]},
})
if err != nil {
log.Printf("Error when posting to webhook endpoint: %s", err.Error())
return "", err
}
defer res.Body.Close()
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Error when parsing Telegram response: %s", err.Error())
return "", nil
}
bodyString := string(bodyBytes)
return bodyString, nil
}
// Delete Bot webhook with the Telegram /deleteWebhook API endpoint.
func (b *Bot) deleteWebhook() (string, error) {
res, err := http.PostForm(
telegramApiBaseUrl+b.apiToken+deleteWebhookEndpoint,
url.Values{},
)
if err != nil {
log.Printf("Error when delete webhook: %s", err.Error())
return "", err
}
defer res.Body.Close()
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Error when parsing Telegram response: %s", err.Error())
return "", nil
}
bodyString := string(bodyBytes)
log.Printf("Body of Telegram response: %s", bodyString)
return bodyString, nil
}
// Parse the request body of the Telegram webhook.
func parseTelegramWebhookRequest(r *http.Request) (*Update, error) {
var update Update
if err := json.NewDecoder(r.Body).Decode(&update); err != nil {
log.Printf("Could not decode incoming update %s", err.Error())
return nil, err
}
return &update, nil
}
// Handle the webhook http request from Telegram.
func (b *Bot) handleTelegramWebHook(w http.ResponseWriter, r *http.Request) {
// parse Update object
update, err := parseTelegramWebhookRequest(r)
if err != nil {
log.Printf("Error parsing update, %s", err.Error())
return
}
// Dispatch update.
b.dispatchUpdate(update)
}