-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
276 lines (251 loc) · 6.41 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
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"sort"
"strconv"
"strings"
msg "golang.org/x/text/message"
)
type CoinsResponse struct {
Markets []Market `json:"markets"`
}
type Market struct {
Symbol string `json:"symbol"`
// Currency string `json:"currency"`
Product string `json:"product"`
// Bid string `json:"bid"`
Ask string `json:"ask"`
// ExpiresInSeconds int `json:"expires_in_seconds"`
Amt float64 `json:"amt"`
}
type Config struct {
Symbols []string `json:"symbols"` //list of symbols to parse
BotID string `json:"bot_id"` //telegram bot key
JbinSK string `json:"jbin_sk"` //json bin secret key
JbinID string `json:"jbin_id"` //json bin for old
BTCID string `json:"btc_id"` //telegam chat id for btc
AllID string `json:"all_id"` //telegram chat id for all
}
const TGURL = "https://api.telegram.org"
const JBINURL = "https://api.jsonbin.io/b"
const COINSURL = "https://quote.coins.ph/v2/markets?region=PH"
func main() {
configPath := flag.String("c", "config.json", "config file")
flag.Parse()
config := parseConfig(*configPath)
//fetch prices
response, err := fetchMarkets(COINSURL)
if err != nil {
log.Fatalf("[ERROR] %v", err)
return
}
markets := response.filterMarkets(config.Symbols)
old, err := fetchOld(JBINURL, config.JbinID, config.JbinSK)
if err != nil {
log.Fatalf("[ERROR] %v", err)
return
}
//send to all
message := constructMessage(markets, *old)
err = sendMessage(TGURL, config.BotID, config.AllID, message)
if err != nil {
log.Fatalf("[ERROR] %v", err)
return
}
// save
err = updateOld(JBINURL, config.JbinID, config.JbinSK, markets)
if err != nil {
log.Fatalf("[ERROR] %v", err)
return
}
//send to btc
btc := constructCurrencyMessage(markets, *old, "BTC-PHP")
sendMessage(TGURL, config.BotID, config.BTCID, btc)
}
func parseConfig(path string) Config {
configFile, err := os.Open(path)
if err != nil {
log.Fatal("Cannot open server configuration file: ", err)
}
defer configFile.Close()
dec := json.NewDecoder(configFile)
var config Config
if err = dec.Decode(&config); errors.Is(err, io.EOF) {
//do nothing
} else if err != nil {
log.Fatal("Cannot load server configuration file: ", err)
}
return config
}
func fetchMarkets(url string) (CoinsResponse, error) {
res, err := http.Get(url)
if err != nil {
return CoinsResponse{}, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return CoinsResponse{}, err
}
var markets CoinsResponse
err = json.Unmarshal(body, &markets)
if err != nil {
return CoinsResponse{}, err
}
return markets, nil
}
func (c *CoinsResponse) filterMarkets(symbols []string) []Market {
filtered := []Market{}
for _, m := range c.Markets {
if !checkContains(symbols, m.Symbol) {
continue
}
amt, err := strconv.ParseFloat(m.Ask, 64)
if err != nil {
log.Fatal(err)
}
m.Amt = amt
filtered = append(filtered, m)
}
sort.SliceStable(filtered, func(i, j int) bool {
return filtered[i].Amt > filtered[j].Amt
})
return filtered
}
func constructSingleMessage(new Market, old Market, printer *msg.Printer) string {
dif := new.Amt - old.Amt
amtStr := printer.Sprintf("₱%d", int(new.Amt))
if dif == 0 {
return amtStr
}
difStr := printer.Sprintf("₱%d", int(math.Abs(dif)))
if new.Amt < 1000 {
amtStr = printer.Sprintf("₱%.2f", new.Amt)
difStr = printer.Sprintf("₱%.2f", math.Abs(dif))
}
pctStr := printer.Sprintf("%.2f%%", 100*math.Abs(dif)/((new.Amt+old.Amt)/2))
if dif > 0 {
return printer.Sprintf("*%s (+%s [%s])* ", amtStr, pctStr, difStr)
}
return printer.Sprintf("`%s (-%s [%s])`", amtStr, pctStr, difStr)
}
func constructCurrencyMessage(markets []Market, old []Market, symbol string) string {
for _, m := range markets {
if m.Symbol != symbol {
continue
}
for _, o := range old {
if o.Symbol != symbol {
continue
}
return constructSingleMessage(m, o, msg.NewPrinter(msg.MatchLanguage("en")))
}
}
return ""
}
func constructMessage(markets []Market, old []Market) string {
message := []string{}
p := msg.NewPrinter(msg.MatchLanguage("en"))
for _, m := range markets {
for _, o := range old {
if o.Symbol != m.Symbol {
continue
}
message = append(message, fmt.Sprintf("%s: %s", m.Product, constructSingleMessage(m, o, p)))
break
}
}
return strings.Join(message, "\n")
}
func constructPayload(chatID string, message string) (*bytes.Reader, error) {
payload := map[string]interface{}{}
payload["chat_id"] = chatID
payload["text"] = message
payload["parse_mode"] = "markdown"
jsonValue, err := json.Marshal(payload)
return bytes.NewReader(jsonValue), err
}
func checkContains(slice []string, value string) bool {
for i := 0; i < len(slice); i++ {
if slice[i] == value {
return true
}
}
return false
}
func sendMessage(url string, bot string, chatID string, message string) error {
payload, err := constructPayload(chatID, message)
if err != nil {
return err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/bot%s/sendMessage", url, bot), payload)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
_, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return nil
}
func fetchOld(url string, id string, key string) (*[]Market, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s/latest", url, id), nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("secret-key", key)
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var markets CoinsResponse
err = json.Unmarshal(body, &markets)
if err != nil {
return nil, err
}
return &markets.Markets, nil
}
func updateOld(url string, id string, key string, markets []Market) error {
b, err := json.Marshal(CoinsResponse{markets})
if err != nil {
return err
}
req, err := http.NewRequest("PUT", fmt.Sprintf("%s/%s", url, id), bytes.NewBuffer(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("secret-key", key)
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
_, err = ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return nil
}