/
webhook.go
65 lines (55 loc) · 1.46 KB
/
webhook.go
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
package helpers
import (
"bytes"
"encoding/json"
"fmt"
"log"
"github.com/aws/aws-lambda-go/events"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/yevhenshymotiuk/telegram-lambda-helpers/apigateway"
)
// SetWebhook provides function which sets Telegram webhook to get updates
func SetWebhook(
telegramToken string,
) func(request events.APIGatewayProxyRequest) (apigateway.Response, error) {
return func(request events.APIGatewayProxyRequest) (apigateway.Response, error) {
responseFail := apigateway.Response{StatusCode: 404}
bot, err := tgbotapi.NewBotAPI(telegramToken)
if err != nil {
return responseFail, err
}
url := fmt.Sprintf(
"https://%s/%s/",
request.Headers["Host"],
request.RequestContext.Stage,
)
_, err = bot.SetWebhook(tgbotapi.NewWebhook(url))
if err != nil {
return responseFail, err
}
info, err := bot.GetWebhookInfo()
if err != nil {
return responseFail, err
}
if info.LastErrorDate != 0 {
log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
}
var buf bytes.Buffer
body, err := json.Marshal(
map[string]interface{}{"message": "Webhook was successfully set!"},
)
if err != nil {
return responseFail, err
}
json.HTMLEscape(&buf, body)
resp := apigateway.Response{
StatusCode: 200,
IsBase64Encoded: false,
Body: buf.String(),
Headers: map[string]string{
"Content-Type": "application/json",
},
}
return resp, nil
}
}