-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
171 lines (138 loc) · 4.31 KB
/
handler.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"os"
)
const botName string = "@carRegionBot"
const startCommand string = "/start"
const startInfo string = "Now you can enter registation region code (ex. 01, 05, 18)."
const telegramApiBaseUrl string = "https://api.telegram.org/bot"
var telegramApi string = telegramApiBaseUrl + os.Getenv("TELEGRAM_BOT_TOKEN") + "/sendMessage"
// Update Telegram object
// See: https://core.telegram.org/bots/api#update
type Update struct {
UpdateId int `json:"update_id"`
Message Message `json:"message"`
}
// Implements the fmt.String interface to get the representation of an Update as a string.
func (u Update) String() string {
return fmt.Sprintf("(update id: %d, message: %s)", u.UpdateId, u.Message)
}
// Message is a Telegram object that can be found in an update.
// Note that not all Update contains a Message. Update for an Inline Query doesn't.
type Message struct {
Text string `json:"text"`
Chat Chat `json:"chat"`
}
// A Chat indicates the conversation to which the Message belongs.
type Chat struct {
Id int `json:"id"`
}
// Implements the fmt.String interface to get the representation of a Chat as a string.
func (c Chat) String() string {
return fmt.Sprintf("(id: %d)", c.Id)
}
//
type Regions struct {
Regions []Region `json:"data"`
}
type Region struct {
Regioncode string `json:"regioncode"`
Offname string `json:"offname"`
Shortname string `json:"shortname"`
}
/**
* Handle Telegram webhook request
*/
func HandleTelegramWebHook(w http.ResponseWriter, r *http.Request) {
// Parse incoming request
var update, err = parseTelegramRequest(r)
if err != nil {
log.Printf("Error parsing update, %s", err.Error())
return
}
// Send start instrutions
var text = botName + ": Invalid code";
if (update.Message.Text == startCommand) {
text = startInfo;
} else if _, err := strconv.Atoi(update.Message.Text); err == nil {
text = getRegionName(update.Message.Text)
}
// Send region name to Telegram
var telegramResponseBody, errTelegram = sendTextToTelegramChat(update.Message.Chat.Id, text)
if errTelegram != nil {
log.Printf("Got error %s from telegram, response body is %s", errTelegram.Error(), telegramResponseBody)
} else {
log.Printf("Message %s successfully distributed to chat id %d", text, update.Message.Chat.Id)
}
}
/**
* Handles incoming update from the Telegram web hook
*/
func parseTelegramRequest(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
}
if update.UpdateId == 0 {
log.Printf("Invalid update id, got update id = 0")
return nil, errors.New("Invalid update id of 0 indicates failure to parse incoming update")
}
return &update, nil
}
/**
* Get region name by code
*/
func getRegionName(code string) string {
// Open our jsonFile
// Source http://basicdata.ru/api/json/fias/addrobj
jsonFile, err := os.Open(os.Getenv("REGIONS_JSON_PATH") + "regions.json")
// If we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
}
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var regions Regions
json.Unmarshal(byteValue, ®ions)
for i := 0; i < len(regions.Regions); i++ {
if (regions.Regions[i].Regioncode == code) {
return fmt.Sprintf("%s (%s)", regions.Regions[i].Offname, regions.Regions[i].Shortname)
}
}
log.Printf("Сode does not exist.")
return botName + ": Сode does not exist."
}
/**
* Sends a text message to the Telegram chat identified by its chat Id
*/
func sendTextToTelegramChat(chatId int, text string) (string, error) {
log.Printf("Sending %s to chat_id: %d", text, chatId)
response, err := http.PostForm(
telegramApi,
url.Values{
"chat_id": {strconv.Itoa(chatId)},
"text": {text},
})
if err != nil {
log.Printf("Error when posting text to the chat: %s", err.Error())
return "", err
}
defer response.Body.Close()
var bodyBytes, errRead = ioutil.ReadAll(response.Body)
if errRead != nil {
log.Printf("Error in parsing telegram answer %s", errRead.Error())
return "", err
}
bodyString := string(bodyBytes)
return bodyString, nil
}