|
| 1 | +package gold |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "goirc/bot" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | +) |
| 10 | + |
| 11 | +type response struct { |
| 12 | + Timestamp int `json:"timestamp"` |
| 13 | + Metal string `json:"metal"` |
| 14 | + Currency string `json:"currency"` |
| 15 | + Exchange string `json:"exchange"` |
| 16 | + Symbol string `json:"symbol"` |
| 17 | + PrevClosePrice float64 `json:"prev_close_price"` |
| 18 | + OpenPrice float64 `json:"open_price"` |
| 19 | + LowPrice float64 `json:"low_price"` |
| 20 | + HighPrice float64 `json:"high_price"` |
| 21 | + OpenTime int `json:"open_time"` |
| 22 | + Price float64 `json:"price"` |
| 23 | + Ch float64 `json:"ch"` |
| 24 | + Chp float64 `json:"chp"` |
| 25 | + Ask float64 `json:"ask"` |
| 26 | + Bid float64 `json:"bid"` |
| 27 | + PriceGram24K float64 `json:"price_gram_24k"` |
| 28 | + PriceGram22K float64 `json:"price_gram_22k"` |
| 29 | + PriceGram21K float64 `json:"price_gram_21k"` |
| 30 | + PriceGram20K float64 `json:"price_gram_20k"` |
| 31 | + PriceGram18K float64 `json:"price_gram_18k"` |
| 32 | + PriceGram16K float64 `json:"price_gram_16k"` |
| 33 | + PriceGram14K float64 `json:"price_gram_14k"` |
| 34 | + PriceGram10K float64 `json:"price_gram_10k"` |
| 35 | +} |
| 36 | + |
| 37 | +func getGoldPrice(token string) (float64, error) { |
| 38 | + url := "https://www.goldapi.io/api/XAU/CAD" |
| 39 | + req, err := http.NewRequest("GET", url, nil) |
| 40 | + if err != nil { |
| 41 | + return 0.0, err |
| 42 | + } |
| 43 | + req.Header.Set("x-access-token", token) |
| 44 | + |
| 45 | + client := &http.Client{} |
| 46 | + resp, err := client.Do(req) |
| 47 | + if err != nil { |
| 48 | + return 0.0, err |
| 49 | + } |
| 50 | + defer resp.Body.Close() |
| 51 | + |
| 52 | + var obj response |
| 53 | + json.NewDecoder(resp.Body).Decode(&obj) |
| 54 | + |
| 55 | + fmt.Printf("Price: %f\n", obj.Price) |
| 56 | + |
| 57 | + return obj.Price, nil |
| 58 | +} |
| 59 | + |
| 60 | +func Handle(params bot.HandlerParams) error { |
| 61 | + price, err := getGoldPrice(os.Getenv("GOLD_API_TOKEN")) |
| 62 | + if err != nil { |
| 63 | + return err |
| 64 | + } |
| 65 | + |
| 66 | + params.Privmsgf(params.Target, "gold is $%.2f / oz t.", price) |
| 67 | + |
| 68 | + return nil |
| 69 | +} |
0 commit comments