DarkThroneApi

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 29, 2025 License: MIT Imports: 10 Imported by: 0

README

DarkThroneApi

Disclaimer: This project is provided as-is. The author is not responsible for how this library is used. Users are solely responsible for ensuring their usage complies with the Dark Throne Reborn site's Terms and Conditions.

DarkThroneApi is a Go client library for interacting with the Dark Throne Reborn MMO API. It provides convenient methods for authentication, player management, banking, and more.

Features

  • User authentication (login, register, logout)
  • Player management (fetch, create, assume, unassume)
  • Banking operations (deposit, withdraw gold)
  • Structure upgrades and proficiency points (planned)
  • Configurable logging
  • Designed for automation and integration

Installation

go get github.com/Rihoj/DarkThroneApi

Usage

import "github.com/Rihoj/DarkThroneApi"

func main() {
    api := DarkThroneApi.New(&DarkThroneApi.Config{Logger: nil})
    // Use api methods, e.g. api.DepositGold(...)
}

See GoDocs for full API reference. If published, you can also browse the API at pkg.go.dev.

Linting & Commit Requirements

  • Node.js and npm are required for development tooling (commit hooks, semantic-release, etc.), but not for using the Go library itself.
  • All commits must follow Conventional Commits style. This is enforced by commitlint in CI and via a pre-commit hook.
  • Linting is enforced on every commit using staticcheck for Go code. Commits will be blocked if linting fails.
  • You must have staticcheck installed and available in your PATH. Install it with:
go install honnef.co/go/tools/cmd/staticcheck@latest
  • Node.js dev dependencies for commit linting and hooks are managed in package.json:
    • @commitlint/cli, @commitlint/config-conventional, husky

Development

  • Requires Go 1.24+
  • Run tests: go test ./...
  • Lint: staticcheck ./...

License

MIT


Suggestions for Contributors
  • If you wish to contribute, please ensure you have Node.js, npm, and Go installed.
  • Make sure your staticcheck binary is in your PATH (e.g., add export PATH="$HOME/go/bin:$PATH" to your shell profile if needed).
  • For more information on GoDoc, see pkg.go.dev.
  • If you have questions or suggestions, feel free to open an issue or pull request.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ApiRequest

type ApiRequest[Req any, Resp any] struct {
	Method   string
	Endpoint string
	Headers  map[string]string
	Body     Req
	Config   *ApiRequestConfig // Optional config for request-level settings
}

ApiRequest represents an API request with generic request and response types.

func (ApiRequest[Req, Resp]) DoRequest

func (req ApiRequest[Req, Resp]) DoRequest() (Resp, error)

DoRequest executes the API request and returns the response or an error.

func (*ApiRequest[Req, Resp]) GetUrl

func (req *ApiRequest[Req, Resp]) GetUrl() string

GetUrl constructs the full URL for the API request.

type ApiRequestConfig

type ApiRequestConfig struct {
	BaseURL string
	Logger  *slog.Logger
}

ApiRequestConfig holds configuration for API requests, such as the base URL and logger.

type AttackResponse

type AttackResponse struct {
	IsAttackerVictor bool `json:"isAttackerVictor"`
}

AttackResponse represents the result of an attack action.

type BankDepositRequest

type BankDepositRequest struct {
	PlayerID string `json:"playerId"`
	Amount   int    `json:"amount"`
}

BankDepositRequest represents the payload to deposit gold.

type BankResponse

type BankResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Balance int    `json:"balance"`
}

BankResponse represents the response from a bank operation.

type BankWithdrawRequest

type BankWithdrawRequest struct {
	PlayerID string `json:"playerId"`
	Amount   int    `json:"amount"`
}

BankWithdrawRequest represents the payload to withdraw gold.

type Config

type Config struct {
	Logger *slog.Logger
}

Config holds configuration for the DarkThroneApi client, such as the logger.

type CreatePlayerRequest

type CreatePlayerRequest struct {
	Name     string `json:"name"`
	Race     string `json:"race"`
	Password string `json:"password"`
}

CreatePlayerRequest represents the payload to create a player.

type CurrentUserResponse

type CurrentUserResponse struct {
	Player Player `json:"player"`
}

CurrentUserResponse represents the response for the current user API call.

type DarkThroneApi

type DarkThroneApi struct {
	// contains filtered or unexported fields
}

DarkThroneApi is the main client for interacting with the Dark Throne API.

func GetInstance

func GetInstance() *DarkThroneApi

GetInstance returns the singleton instance of DarkThroneApi. Panics if not initialized.

func New

func New(config *Config) *DarkThroneApi

New creates a new instance of DarkThroneApi with the provided configuration.

func (*DarkThroneApi) AssumePlayer

func (d *DarkThroneApi) AssumePlayer(playerID string) (Player, error)

AssumePlayer assumes the given player ID and returns the Player. It sends a POST request to the assume player endpoint and returns the assumed Player or an error.

func (*DarkThroneApi) AttackPlayer

func (d *DarkThroneApi) AttackPlayer(targetID string) (bool, error)

AttackPlayer attacks a player by ID. It returns true if the attack was successful, or false and an error otherwise.

func (*DarkThroneApi) CreatePlayer

func (d *DarkThroneApi) CreatePlayer(req CreatePlayerRequest) (Player, error)

CreatePlayer creates a new player.

func (*DarkThroneApi) DepositGold

func (d *DarkThroneApi) DepositGold(req BankDepositRequest) (BankResponse, error)

DepositGold deposits gold into the bank.

func (*DarkThroneApi) FetchAllMatchingIDs

func (d *DarkThroneApi) FetchAllMatchingIDs(ids []string) ([]Player, error)

FetchAllMatchingIDs fetches all matching player IDs.

func (*DarkThroneApi) FetchAllPlayers

func (d *DarkThroneApi) FetchAllPlayers(page, pageSize int) ([]Player, error)

FetchAllPlayers fetches all players (paginated).

func (*DarkThroneApi) FetchAllWarHistory

func (d *DarkThroneApi) FetchAllWarHistory() ([]WarHistory, error)

FetchAllWarHistory fetches all war history.

func (*DarkThroneApi) FetchPlayerByID

func (d *DarkThroneApi) FetchPlayerByID(id string) (Player, error)

FetchPlayerByID fetches a player by ID.

func (*DarkThroneApi) FetchWarHistoryByID

func (d *DarkThroneApi) FetchWarHistoryByID(id string) (WarHistory, error)

FetchWarHistoryByID fetches war history by ID.

func (*DarkThroneApi) GetCurrentUser

func (d *DarkThroneApi) GetCurrentUser() (CurrentUserResponse, error)

GetCurrentUser fetches the current authenticated user. TODO: Move implementation from darkthrone.api.go and remove from there.

func (*DarkThroneApi) GetCurrentUserAPI

func (d *DarkThroneApi) GetCurrentUserAPI() (CurrentUserResponse, error)

GetCurrentUserAPI fetches the current user (not player) from the API. Returns the CurrentUserResponse or an error if the request fails.

func (*DarkThroneApi) GetPlayerByIndex

func (d *DarkThroneApi) GetPlayerByIndex(index int) (Player, error)

GetPlayerByIndex retrieves a player by index from the user's player list and assumes that player. If the index is out of range, it returns an error.

func (*DarkThroneApi) GetPlayersForCurrentUser

func (d *DarkThroneApi) GetPlayersForCurrentUser() ([]Player, error)

GetPlayersForCurrentUser fetches the list of players for the current user. It returns a slice of Player and an error if the request fails.

func (*DarkThroneApi) Login

func (d *DarkThroneApi) Login(lr LoginRequest) (string, error)

Login authenticates the user and returns a token. Returns the authentication token or an error if login fails.

func (*DarkThroneApi) Logout

func (d *DarkThroneApi) Logout() error

Logout logs out the current user. It clears the authentication token and returns an error if the logout fails.

func (*DarkThroneApi) Ping

func (d *DarkThroneApi) Ping() (latencyMs int64, err error)

Ping checks if the Dark Throne API server can be reached by making a HEAD request to the base URL. It returns the latency in milliseconds if successful, or an error if not.

func (*DarkThroneApi) Register

Register registers a new user.

func (*DarkThroneApi) SpendProficiencyPoints

func (d *DarkThroneApi) SpendProficiencyPoints(req ProficiencyPointsRequest) (ProficiencyPointsResponse, error)

SpendProficiencyPoints spends proficiency points for the current player. Returns an error indicating the feature is not released yet. When released, this will POST to the proficiency-points endpoint.

func (*DarkThroneApi) TrainUnits

TrainUnits trains units for the current player.

func (*DarkThroneApi) UnassumePlayer

func (d *DarkThroneApi) UnassumePlayer() error

UnassumePlayer unassumes the current player. It sends a POST request to the unassume player endpoint and returns an error if the operation fails.

func (*DarkThroneApi) UntrainUnits

UntrainUnits untrains units for the current player.

func (*DarkThroneApi) UpgradeStructure

UpgradeStructure upgrades a structure for the current player. Returns an error indicating the feature is not released yet. When released, this will POST to the structures/upgrade endpoint.

func (*DarkThroneApi) ValidatePlayerName

func (d *DarkThroneApi) ValidatePlayerName(name string) (bool, error)

ValidatePlayerName validates a player name.

func (*DarkThroneApi) WithdrawGold

func (d *DarkThroneApi) WithdrawGold(req BankWithdrawRequest) (BankResponse, error)

WithdrawGold withdraws gold from the bank.

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

LoginRequest represents the payload for a login request.

type LoginResponse

type LoginResponse struct {
	Session struct {
		Id                  string  `json:"id"`
		Email               string  `json:"email"`
		Player_id           *string `json:"playerID"`
		Has_confirmed_email bool    `json:"hasConfirmedEmail"`
		Server_time         string  `json:"serverTime"`
	} `json:"session"`
	Token string `json:"token"`
}

LoginResponse represents the response from a login request.

type Player

type Player struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Gold        int    `json:"gold"`
	Level       int    `json:"level"`
	ArmySize    int    `json:"armySize"`
	Units       []Unit `json:"units"`
	AttackTurns int    `json:"attackTurns"`
}

Player represents a player in the Dark Throne game.

type PlayersListResponse

type PlayersListResponse struct {
	Items []Player `json:"items"`
}

PlayersListResponse represents a paginated list of players.

type ProficiencyPointsRequest

type ProficiencyPointsRequest struct {
	PlayerID        string `json:"playerId"`
	PointsToSpend   int    `json:"pointsToSpend"`
	ProficiencyType string `json:"proficiencyType"`
}

ProficiencyPointsRequest represents the payload to spend proficiency points.

type ProficiencyPointsResponse

type ProficiencyPointsResponse struct {
	Success         bool   `json:"success"`
	Message         string `json:"message"`
	RemainingPoints int    `json:"remainingPoints"`
}

ProficiencyPointsResponse represents the response from spending proficiency points.

type RegisterRequest

type RegisterRequest struct {
	Email           string `json:"email"`
	Password        string `json:"password"`
	ConfirmPassword string `json:"confirmPassword"`
	Username        string `json:"username"`
}

RegisterRequest represents the payload for user registration.

type RegisterResponse

type RegisterResponse struct {
	Session struct {
		Id                  string  `json:"id"`
		Email               string  `json:"email"`
		Player_id           *string `json:"playerID"`
		Has_confirmed_email bool    `json:"hasConfirmedEmail"`
		Server_time         string  `json:"serverTime"`
	} `json:"session"`
	Token string `json:"token"`
}

RegisterResponse represents the response for user registration.

type TrainUnitsRequest

type TrainUnitsRequest struct {
	PlayerID string        `json:"playerId"`
	Units    []UnitRequest `json:"units"`
}

TrainUnitsRequest represents the payload to train units.

type TrainUnitsResponse

type TrainUnitsResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

TrainUnitsResponse represents the response from training units.

type Unit

type Unit struct {
	UnitType string `json:"unitType"`
	Quantity int    `json:"quantity"`
}

Unit represents a unit in a player's army.

type UnitRequest

type UnitRequest struct {
	UnitType string `json:"unitType"`
	Quantity int    `json:"quantity"`
}

UnitRequest represents a unit and quantity for training/untraining.

type UntrainUnitsRequest

type UntrainUnitsRequest struct {
	PlayerID string        `json:"playerId"`
	Units    []UnitRequest `json:"units"`
}

UntrainUnitsRequest represents the payload to untrain units.

type UntrainUnitsResponse

type UntrainUnitsResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}

UntrainUnitsResponse represents the response from untraining units.

type UpgradeStructureRequest

type UpgradeStructureRequest struct {
	StructureID  string `json:"structureId"`
	UpgradeLevel int    `json:"upgradeLevel"`
}

UpgradeStructureRequest represents the payload to upgrade a structure.

type UpgradeStructureResponse

type UpgradeStructureResponse struct {
	Success     bool   `json:"success"`
	Message     string `json:"message"`
	StructureID string `json:"structureId"`
	NewLevel    int    `json:"newLevel"`
}

UpgradeStructureResponse represents the response from upgrading a structure.

type UserPlayersListResponse

type UserPlayersListResponse []Player

UserPlayersListResponse represents a list of players for the current user.

type WarHistory

type WarHistory struct {
	ID        string `json:"id"`
	PlayerID  string `json:"playerId"`
	Opponent  string `json:"opponent"`
	Result    string `json:"result"`
	Timestamp string `json:"timestamp"`
}

WarHistory represents a war history record.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL