-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (95 loc) · 2.59 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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"os"
"io/ioutil"
)
type Config struct {
Key string `json:"key"`
}
func readKey() string {
jsonFile, err := os.Open("config.json")
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var config Config
json.Unmarshal(byteValue, &config)
fmt.Println("Key: " + config.Key)
return config.Key
}
// 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"`
}
// This handler is called everytime telegram sends us a webhook event
func Handler(res http.ResponseWriter, req *http.Request) {
// First, decode the JSON response body
body := &webhookReqBody{}
if err := json.NewDecoder(req.Body).Decode(body); err != nil {
fmt.Println("could not decode request body", err)
return
}
// Check if the message contains the word "marco"
// if not, return without doing anything
if !strings.Contains(strings.ToLower(body.Message.Text), "marco") {
return
}
// If the text contains marco, call the `sayPolo` function, which
// is defined below
if err := contesta(body.Message.Chat.ID); err != nil {
fmt.Println("error in sending reply:", err)
return
}
// log a confirmation message if the message is sent successfully
fmt.Println("reply sent")
}
//The below code deals with the process of sending a response message
// to the user
// Create a struct to conform to the JSON body
// of the send message request
// https://core.telegram.org/bots/api#sendmessage
type sendMessageReqBody struct {
ChatID int64 `json:"chat_id"`
Text string `json:"text"`
}
// sayPolo takes a chatID and sends "polo" to them
func contesta(chatID int64) error {
// Create the request body struct
reqBody := &sendMessageReqBody{
ChatID: chatID,
Text: "Hola!",
}
// Create the JSON body from the struct
reqBytes, err := json.Marshal(reqBody)
if err != nil {
return err
}
key := readKey()
// Send a post request with your token
res, err := http.Post("https://api.telegram.org/bot"+key+"/sendMessage", "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return errors.New("unexpected status" + res.Status)
}
return nil
}
// Finally, the main funtion starts our server on port 3000
func main() {
readKey()
http.ListenAndServe(":3000", http.HandlerFunc(Handler))
}