GithubHelp home page GithubHelp logo

fuzzystatic / blizzard Goto Github PK

View Code? Open in Web Editor NEW
57.0 2.0 18.0 1.66 MB

Go client library for Blizzard API data

License: MIT License

Go 100.00%
diablo3 d3 world-of-warcraft worldofwarcraft wow wow-api blizzard blizzard-api blizzard-data starcraft-ii

blizzard's Introduction

blizzard

Go Reference Go Report Card

This is a Go client library for gathering Blizzard API reference data

Table of Contents

Getting Started

First, download the Blizzard library:

go get github.com/FuzzyStatic/blizzard/v3

Start using the library by initiating a new Blizzard config structure for your desired region and locale (client_id and client_secret can be acquired through your developer account at https://develop.battle.net/) and requesting an access token:

usBlizzClient, err := blizzard.NewClient(blizzard.Config{
  ClientID:     "my_client_id",
  ClientSecret: "my_client_secret",
  HTTPClient:   http.DefaultClient,
  Region:       blizzard.US,
  Locale:       blizzard.EnUS,
})

err = usBlizzClient.AccessTokenRequest(ctx)
if err != nil {
  fmt.Println(err)
}

euBlizzClient, err := blizzard.NewClient(blizzard.Config{
  ClientID:     "my_client_id",
  ClientSecret: "my_client_secret",
  HTTPClient:   http.DefaultClient,
  Region:       blizzard.EU,
  Locale:       blizzard.EnGB,
})

err = euBlizzClient.AccessTokenRequest(ctx)
if err != nil {
  fmt.Println(err)
}

Fetching Diablo 3 Data

You can use the functions prefixed with "D3" to acquire Diablo 3 information. For example, you can get information about the current D3 hardcore necromancer leaderboards:

dat, _, err := usBlizzClient.D3SeasonLeaderboardHardcoreNecromancer(ctx, 15)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Fetching Hearthstone Data

You can use the functions prefixed with "HS" to acquire Hearthstone information. For example, you can get information about all the Hearthstone cards:

dat, _, err := usBlizzClient.HSCardsAll(ctx)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Fetching Overwatch League Data

You can use the functions prefixed with "OWL" to acquire Overwatch League information. For example, you can get information about the Overwatch League:

dat, _, err := usBlizzClient.OWLSummaryData(ctx)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Fetching StarCraft 2 Data

You can use the functions prefixed with "SC2" to acquire StarCraft 2 information. For example, you can get information about the current SC2 grandmaster ladder:

dat, _, err := usBlizzClient.SC2LadderGrandmaster(ctx, blizzard.EU)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Fetching World of Warcraft Data

You can use the functions prefixed with "WoW" to acquire World of Warcraft information. For example, you can get information about your WoW character profile:

dat, _, err := usBlizzClient.WoWCharacterProfileSummary(ctx, "illidan", "wildz")
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

or get information about specific spells:

dat, _, err := usBlizzClient.WoWSpell(ctx, 17086)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

or the PvP leaderboards:

dat, _, err := usBlizzClient.WoWCharacterPvPBracketStatistics(ctx, wowp.Bracket3v3)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Fetching World of Warcraft Classic Data

You can use the functions prefixed with "ClassicWoW" to acquire World of Warcraft Classic information. For example, you can get information about WoW Classic creature data:

dat, _, err := usBlizzClient.ClassicWoWCreature(ctx, 30)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Authorization for User Data

To use the UserInfoHeader or WoWUserCharacters functions to acquire data about other users (and not your own), you must use the OAuth2 redirect method to get an authorized token. This is useful for building websites that display more personal or individualized data. The following code snippet is an example on how to acquire authorized tokens for other users. A working example can be found in the examples/authCodeFlow directory. Before the redirect URI will work, you will have to add it to your client settings at https://develop.battle.net/access:

package main

import (
  "context"
  "encoding/json"
  "fmt"
  "log"
  "net/http"

  "github.com/FuzzyStatic/blizzard/v3"
  "github.com/FuzzyStatic/blizzard/v3/oauth"
  "golang.org/x/oauth2"
)

var (
  cfg           oauth2.Config
  usBlizzClient *blizzard.Client
)

// Homepage
func HomePage(w http.ResponseWriter, r *http.Request) {
  fmt.Println("Homepage Hit!")
  u := cfg.AuthCodeURL("my_random_state")
  http.Redirect(w, r, u, http.StatusFound)
}

// Authorize
func Authorize(w http.ResponseWriter, r *http.Request) {
  err := r.ParseForm()
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  state := r.Form.Get("state")
  if state != "my_random_state" {
    http.Error(w, "State invalid", http.StatusBadRequest)
    return
  }

  code := r.Form.Get("code")
  if code == "" {
    http.Error(w, "Code not found", http.StatusBadRequest)
    return
  }

  token, err := cfg.Exchange(context.Background(), code)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  e := json.NewEncoder(w)
  e.SetIndent("", "  ")
  err = e.Encode(*token)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  dat1, _, err := usBlizzClient.UserInfoHeader(token)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  fmt.Printf("%+v\n", dat1)

  dat2, _, err := usBlizzClient.WoWUserCharacters(token)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  fmt.Printf("%+v\n", dat2)
}

func main() {
  blizz = blizzard.NewClient("client_id", "client_secret", blizzard.US, blizzard.EnUS)
  cfg = usBlizzClient.AuthorizeConfig("http://<mydomain>:9094/oauth2", oauth.ProfileD3, oauth.ProfileSC2, oauth.ProfileWoW)

  http.HandleFunc("/", HomePage)
  http.HandleFunc("/oauth2", Authorize)

  // We start up our Client on port 9094
  log.Println("Client is running at 9094 port.")
  log.Fatal(http.ListenAndServe(":9094", nil))
}

Fetching OAuth Data

Now you can validate those tokens with the OAuth API:

dat, _, err := usBlizzClient.TokenValidation(ctx, token)
if err != nil {
  fmt.Println(err)
}

fmt.Printf("%+v\n", dat)

Header Information

Each API call will return HTTP response header information, if any. Use the second return variable to get a structure containing the response header information.

dat, header, err := usBlizzClient.WoWAuctions(context.Background(), 1138)
if err != nil {
  fmt.Println(err)
}

fmt.Println(header.BattlenetNamespace)
fmt.Println(header.LastModified)
...

Documentation

See the Blizzard API reference and the Go reference for all the different datasets that can be acquired. For questions and discussion about the blizzard API go to the Blizzard API Forum.

Special Thanks

Thanks to JSON-to-Go for making JSON to Go structure creation simple.

Thanks to all who contribute to keep this package current.

blizzard's People

Contributors

alexmeuer avatar ccod avatar dependabot[bot] avatar floppy012 avatar fryyyyy avatar fuzzystatic avatar ianlopshire avatar jriegner avatar kelwing avatar msadowskigraduate avatar nerothos avatar novikovroman avatar roffe avatar shaneajeffery avatar w1ck3dg0ph3r avatar zifre avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

blizzard's Issues

Test failing

These 2 mythic keystone endpoints are returning 404 for me for some reason, does this happend on your end as well?

2021/05/24 00:48:19 Output will not be printed for tests.
404 Not Found
--- FAIL: TestMythicKeystoneSeasonDetails (0.16s)
404 Not Found
--- FAIL: TestWoWCharacterMythicKeystoneProfileSeason (0.16s)
FAIL
FAIL    github.com/FuzzyStatic/blizzard/v2      145.600s
?       github.com/FuzzyStatic/blizzard/v2/d3c  [no test files]
?       github.com/FuzzyStatic/blizzard/v2/d3gd [no test files]
?       github.com/FuzzyStatic/blizzard/v2/hsgd [no test files]
?       github.com/FuzzyStatic/blizzard/v2/oauth        [no test files]
?       github.com/FuzzyStatic/blizzard/v2/sc2c [no test files]
?       github.com/FuzzyStatic/blizzard/v2/sc2gd        [no test files]
?       github.com/FuzzyStatic/blizzard/v2/wowcgd       [no test files]
?       github.com/FuzzyStatic/blizzard/v2/wowgd        [no test files]
?       github.com/FuzzyStatic/blizzard/v2/wowp [no test files]
ok      github.com/FuzzyStatic/blizzard/v2/wowsearch    (cached)
FAIL

Unable to pull the latest version

Hello!

I'm unable to pull the latest version (v3.0.2) with go get -u github.com/FuzzyStatic/[email protected] command:

go: github.com/FuzzyStatic/[email protected]: invalid version: module contains a go.mod file, so module path must match major version ("github.com/FuzzyStatic/blizzard/v3")

go get -u github.com/FuzzyStatic/blizzard/[email protected] does not work too.

It seems you pushed the v3.x.x tag but didn't update the module path to handle v3 versions (module in go.mod and imports).

Wrong time format used for date parsing for header.LastModified / Date

Hi again

Been having weird issues today, and I think I found the cause:

in header.go:

	if httpHeader.Get(HeaderKeyLastModified) != "" {
		header.LastModified, err = time.Parse(time.RFC1123, httpHeader.Get(HeaderKeyLastModified))
		if err != nil {
			header.LastModified = time.Time{}
		}
	}

If httpHeader.Get(HeaderKeyLastModified) returns this string: "Sat, 3 Apr 2021 20:06:56 GMT" time.Parse() gives this error:

parsing time "Sat, 3 Apr 2021 20:06:56 GMT" as "Mon, 02 Jan 2006 15:04:05 MST": cannot parse "3 Apr 2021 20:06:56 GMT" as "02"

If instead of using time.RFC1123 I try with a custom format "Mon, _2 Jan 2006 15:04:05 MST" then it works! Not sure if this still works if the day is > 9. I think so as it's how they handle it in Go's format.go

Http context propagation

Hey @FuzzyStatic, thanks for making this package available :).

I have one question.

Is there any reason why you chosen to not allow for context propagation when performing http requests against blizzard APIs?

This would be in certain contexts like cancellation.

I would be keen on making such changes in a PR but they will be breaking changes since the APIs will go from:

func (c *Client) getURLBody(url, namespace string) ([]byte, error) {}

To:

func (c *Client) getURLBody(ctx context.Context, url, namespace string) ([]byte, error) {}

So the release of a new version via creating a v2.0.0 would be required.

Looking forward to hearing from you :).

json: cannot unmarshal string into Go struct field CharacterProfileSummary.active_title

I'm running into some weird issues with some characters:

json: cannot unmarshal string into Go struct field CharacterProfileSummary.active_title of type struct { Key struct { Href string "json:\"href\"" } "json:\"key\""; Name string "json:\"name\""; ID int "json:\"id\""; DisplayString string "json:\"display_string\"" }`

Example characters where it happens:

us/hyjal/Deydorayn
us/bonechewer/Chaitwa
us/kiljaeden/Fearnøevil
us/emerald-dream/Heldin
eu/kazzak/Moonjumper

I have retry logic with back-off and the same error happens 10 times in a row on these characters so I don't think it was a temporary glitch

SC2 Ladder data for specific division's ladderID

Hi!
There is an undocumented endpoint /data/sc2/ladder/{ladderID}, that can be used to get the player list for given division. While not 100% stable, it is widely used by sites like rankedftw and such.
Are you interested in a PR adding this endpoint?

WoW Auction House: Last-Modified response header

Hi again!

Been working on my pet-project using your libray, everything is working great so far

In the WoW auction house API call, there is a header named "Last-Modified" in the response, that tells us when the data has been updated (it's usually once every hour).

Is there a way for me to access response headers from the api calls? I've quickly looked at the code and I couldn't find anything on my end.

Thanks!

Error in BlizzClient.TokenValidation

Hi, im sorry to not be able to give more information but i found a strange error:

when using:

	validation, _, err := euBlizzClient.TokenValidation(context.Background(), token)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

	err = e.Encode(validation)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

i get the following output:

invalid character '<' looking for beginning of value
{
  "exp": 0,
  "user_name": "",
  "authorities": null,
  "client_id": "",
  "scope": null
}

i can validate the received token myself and use it for other functions like Userinfo just fine, only the validation function seems to have a problem.
i am using the following settings:

	euBlizzClient, err = blizzard.NewClient(blizzard.Config{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		HTTPClient:   http.DefaultClient,
		Region:       blizzard.EU,
		Locale:       blizzard.DeDE,

while trying to find why this happens, i checked the wow dev documentation, they say:

We strongly recommend that developers use the more secure POST /oauth/check_token method.

The problem with card searching in HSBattlegroundsCardsSearch()

First I want to thank u for cool library.
Second I am not sure that it doesn't work right and maybe I just made the mistake.
I want to search all 52 heroes from battlegrounds mode, but I get only 40.
Maybe, do u know why it happens?
dat, _, err := blizz.HSBattlegroundsCardsSearch( context.Background(), "", "", "", "", "", []int{}, []int{}, []int{}, 0, 0, []hsgd.Tier{hsgd.TierHero}, "", "", "",)

Missing information with the WoW Auction House

Hello!

I noticed that the AuctionHouse.Auctions struct is missing some information.

Some examples:

{"id":2064367368,"item":{"id":172329,"context":63,"bonus_lists":[6716,7193,1487]},"buyout":14770000,"quantity":1,"time_left":"VERY_LONG"}

The bonus_list would be nice to have, it allows us to calculate an item's item level, secondary stats, sockets, etc.

Also notice this one has buyout instead of unit_price. Materials have a unit_price, but everything else has a buyout. This is because of the new Auction House in patch 8.3, the UI is also different in-game for these 2 kind of auctions. It would be nice to have access to both buyout and unit_price via this package.

{"id":2064014647,"item":{"id":82800,"context":0,"modifiers":[{"type":6,"value":58613}],"pet_breed_id":21,"pet_level":1,"pet_quality_id":3,"pet_species_id":1577}

Information on pets would be useful! They all have the same item id (82800, which is a cage). The information about the pet itself is in those other values (pet_*)

Hopefully these make sense!

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.