This repository has been archived by the owner on Jan 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
118 lines (96 loc) · 2.16 KB
/
main.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
)
// Create a struct that mimics the webhook response body
// https://core.telegram.org/bots/api#update
type webhookReqBody struct {
Message struct {
Text string `json:"text"`
Chat struct {
ID int64 `json:"id"`
} `json:"chat"`
} `json:"message"`
}
func Handler(res http.ResponseWriter, req *http.Request) {
body := &webhookReqBody{}
if err := json.NewDecoder(req.Body).Decode(body); err != nil {
log.Printf("could not decode request body: %s", err)
return
}
if err := sendCompliment(body.Message.Chat.ID); err != nil {
log.Printf("error in sending reply: %s", err)
return
}
log.Println("reply sent")
}
type sendMessageReqBody struct {
ChatID int64 `json:"chat_id"`
Text string `json:"text"`
}
func sendCompliment(chatID int64) error {
msg, err := getCompliment()
if err != nil {
return err
}
reqBody := &sendMessageReqBody{
ChatID: chatID,
Text: msg.Text,
}
reqBytes, err := json.Marshal(reqBody)
if err != nil {
return err
}
client := http.Client{
Timeout: 2 * time.Second,
}
defer client.CloseIdleConnections()
apiKey := os.Getenv("BOT_KEY")
if apiKey == "" {
return errors.New("$BOT_KEY must be set")
}
res, err := client.Post("https://api.telegram.org/bot"+apiKey+"/sendMessage", "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status: %s", res.Status)
}
return nil
}
type Message struct {
Text string `json:"compliment"`
}
func getCompliment() (*Message, error) {
client := http.Client{
Timeout: 2 * time.Second,
}
defer client.CloseIdleConnections()
resp, err := client.Get("https://complimentr.com/api")
if err != nil {
return nil, err
}
defer resp.Body.Close()
msg := &Message{}
if err := json.NewDecoder(resp.Body).Decode(msg); err != nil {
return nil, err
}
return msg, nil
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
if err := http.ListenAndServe(":"+port, http.HandlerFunc(Handler)); err != nil {
log.Fatalln(err)
}
}