stappabot/scryfall.go
2018-12-13 12:01:24 +01:00

95 lines
2.6 KiB
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
type CardSearchResults struct {
TotalCards int `json:"total_cards"`
HasMore bool `json:"has_more"`
Data []CardData `json:"data"`
NextPage string `json:"next_page"`
}
type CardImage struct {
Small string `json:"small"`
Normal string `json:"normal"`
Large string `json:"large"`
Png string `json:"png"`
ArtCrop string `json:"art_crop"`
BorderCrop string `json:"border_crop"`
}
type CardFaces struct {
ImageUris CardImage `json:"image_uris"`
}
type CardData struct {
ID string `json:"id"`
Name string `json:"name"`
URI string `json:"uri"`
ScryfallURI string `json:"scryfall_uri"`
Layout string `json:"layout"`
HighresImage bool `json:"highres_image"`
ImageUris CardImage `json:"image_uris"`
CardFaces []CardFaces `json:"card_faces"`
Eur string `json:"eur"`
EdhrecRank *int `json:"edhrec_rank"`
RelatedUris struct {
Gatherer string `json:"gatherer"`
TcgplayerDecks string `json:"tcgplayer_decks"`
Edhrec string `json:"edhrec"`
Mtgtop8 string `json:"mtgtop8"`
} `json:"related_uris"`
PurchaseUris struct {
Amazon string `json:"amazon"`
Ebay string `json:"ebay"`
Tcgplayer string `json:"tcgplayer"`
Cardmarket string `json:"cardmarket"`
Cardhoarder string `json:"cardhoarder"`
CardKingdom string `json:"card_kingdom"`
MtgoTraders string `json:"mtgo_traders"`
Coolstuffinc string `json:"coolstuffinc"`
} `json:"purchase_uris"`
}
var netClient = &http.Client{
Timeout: time.Second * 20,
}
func scryfallSearch(query string, offset int) (results CardSearchResults, err error) {
query = url.QueryEscape(query)
page := offset / 175
cardoffset := offset % 175
requrl := fmt.Sprintf("https://api.scryfall.com/cards/search?include_multilingual=true&order=name&page=%d&q=%s", page, query)
response, err := netClient.Get(requrl)
if err != nil {
return
}
defer response.Body.Close()
err = json.NewDecoder(response.Body).Decode(&results)
maxoffset := cardoffset + 50
if maxoffset > len(results.Data) {
maxoffset = len(results.Data)
}
results.Data = results.Data[cardoffset:maxoffset]
return
}
func scryfallGetCard(cardname string) (card CardData, err error) {
cardname = url.QueryEscape(cardname)
requrl := fmt.Sprintf("https://api.scryfall.com/cards/named?fuzzy=%s", cardname)
response, err := netClient.Get(requrl)
if err != nil {
return
}
defer response.Body.Close()
err = json.NewDecoder(response.Body).Decode(&card)
return
}