wizlib

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: May 29, 2023 License: MIT Imports: 17 Imported by: 0

README

WizLib

Go Reference

WizLib is a Go package that provides utilities for working with wizard names and game data in the magical world of Wizard101.

Installation

To use WizLib in your Go project, you can simply import it using Go modules:

go get github.com/astridalia/wizlib@v1.0.4

Features

  • Mediawiki: Get information from the wiki.
  • Name Generation: Generate valid wizard names based on an accepted names list.
  • Game Data Retrieval: Fetch player rankings and tournament information from the Wizard101 website.
  • Clean Architecture: Well-organized codebase following clean architecture principles.

Usage

Mediawiki Retrieval
package main

import (
	"fmt"

	"github.com/astridalia/wizlib"
)

func main() {
	service := wizlib.NewWikiService()
	content, err := service.GetWikiText("Item:4th_Age_Balance_Talisman")
	if err != nil {
		fmt.Println("Failed to fetch wiki text:", err)
		return
	}
	fmt.Println(content)
}
Name Generation
package main

import (
	"fmt"
	"github.com/astridalia/wizlib"
)

func main() {
	nameGenerator := wizlib.NewNameGenerator()

	name, err := nameGenerator.GenerateName("Merle Ambrose")
	if err != nil {
		fmt.Println("Failed to generate name:", err)
		return
	}

	fmt.Println("Generated name:", name)
}
Game Data Retrieval
package main

import (
	"fmt"
	"github.com/astridalia/wizlib"
)

func main() {
	rankingRepo := wizlib.NewRepository(wizlib.NewHTTPDocumentFetcher(), "https://www.wizard101.com/pvp/pvp-rankings?age=4&levels=1-10&filter=storm")
	rankings, err := rankingRepo.FetchRankings()
	if err != nil {
		fmt.Println("Failed to fetch player rankings:", err)
		return
	}
	consolePresenter := &wizlib.ConsolePresenter{}
	consolePresenter.PresentRankings(rankings)
}

For detailed documentation, refer to the GoDoc.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareFactors

func CompareFactors(petOne, petTwo int64) int64

CompareFactors compares two factors and returns a result based on a formula.

func ExtractInfoboxData added in v1.0.4

func ExtractInfoboxData(infobox string) map[string]string

ExtractInfoboxData extracts key-value pairs from the infobox.

func FindHeader added in v1.0.4

func FindHeader(data string) string

FindHeader returns the infobox header from the WikiText content.

func ReplaceInfoboxHeader added in v1.0.4

func ReplaceInfoboxHeader(data, template string) string

ReplaceInfoboxHeader removes the infobox header and footer from the WikiText content.

Types

type APIClient added in v1.0.3

type APIClient struct {
	Client *http.Client
}

APIClient provides methods for making HTTP requests.

func NewAPIClient added in v1.0.3

func NewAPIClient() *APIClient

NewAPIClient creates a new instance of APIClient.

func (*APIClient) Get added in v1.0.3

func (c *APIClient) Get(url string) ([]byte, error)

Get makes a GET request to the specified URL.

type AcceptedNames

type AcceptedNames struct {
	Names []string `json:"names"`
}

type Cache added in v1.0.3

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

Cache represents a cache for storing fetched data.

func NewCache added in v1.0.3

func NewCache(duration time.Duration) *Cache

NewCache creates a new instance of Cache.

func (*Cache) Get added in v1.0.3

func (c *Cache) Get() (interface{}, bool)

Get retrieves the data from the cache if it is not expired.

func (*Cache) Set added in v1.0.3

func (c *Cache) Set(data interface{}, expiry time.Time)

Set stores the data in the cache with the specified expiry time.

type CacheRaidRepository added in v1.0.3

type CacheRaidRepository struct {
	Repository RaidRepository
	Cache      *Cache
}

func (*CacheRaidRepository) GetRaid added in v1.0.3

func (c *CacheRaidRepository) GetRaid(guildID string) (*Raid, error)

GetRaid retrieves a raid by guild ID from the cache if available; otherwise, it fetches the raid using the wrapped RaidRepository and stores it in the cache.

func (*CacheRaidRepository) SaveRaid added in v1.0.3

func (c *CacheRaidRepository) SaveRaid(raid *Raid) error

SaveRaid saves a raid using the wrapped RaidRepository and updates the cache accordingly.

type ConsolePresenter added in v0.0.7

type ConsolePresenter struct{}

ConsolePresenter presents player rankings and tournaments on the console.

func (*ConsolePresenter) PresentRankings added in v0.0.7

func (p *ConsolePresenter) PresentRankings(rankings []PlayerRanking)

PresentRankings prints the player rankings.

func (*ConsolePresenter) PresentTournaments added in v0.0.7

func (p *ConsolePresenter) PresentTournaments(tournaments []Tournament)

PresentTournaments prints the tournament information.

type DefaultTimeFormatter added in v0.0.7

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

DefaultTimeFormatter is a default implementation of TimeFormatter.

func NewDefaultTimeFormatter added in v0.0.7

func NewDefaultTimeFormatter(layout string) *DefaultTimeFormatter

NewDefaultTimeFormatter creates a new instance of DefaultTimeFormatter.

func (*DefaultTimeFormatter) ParseTime added in v0.0.7

func (f *DefaultTimeFormatter) ParseTime(timeString string) (string, error)

ParseTime parses a time string into the desired format.

type DocumentFetcher added in v0.0.7

type DocumentFetcher interface {
	Fetch(url string) (*goquery.Document, error)
}

DocumentFetcher retrieves HTML documents from a source.

type FetcherCache added in v1.0.3

type FetcherCache struct {
	DocumentFetcher DocumentFetcher
	Cache           *Cache
}

FetcherCache is a wrapper around DocumentFetcher that adds caching functionality.

func (*FetcherCache) Fetch added in v1.0.3

func (c *FetcherCache) Fetch(url string) (*goquery.Document, error)

Fetch retrieves the HTML document from the cache if available; otherwise, it fetches the document using the wrapped DocumentFetcher and stores it in the cache.

type Gate

type Gate struct {
	Status  int64                  `json:"status"`
	Date    string                 `json:"date"`
	Members map[string]*RaidMember `json:"members"`
}

Gate represents a gate in a raid.

func GetGate

func GetGate(raid *Raid, gateNum int) (*Gate, error)

GetGate retrieves a specific gate from the raid based on the gate number.

func (*Gate) AddMember

func (g *Gate) AddMember(userID string, raidPosition string, backup bool)

AddMember adds a new raid member to the gate.

func (*Gate) GetMember

func (g *Gate) GetMember(userID string) *RaidMember

GetMember retrieves a raid member from the gate based on the user ID.

func (*Gate) RemoveMember

func (g *Gate) RemoveMember(userID string)

RemoveMember removes a raid member from the gate.

type HTTPDocumentFetcher added in v0.0.7

type HTTPDocumentFetcher struct {
	Client *APIClient
}

HTTPDocumentFetcher provides methods for fetching HTML documents.

func NewHTTPDocumentFetcher added in v1.0.4

func NewHTTPDocumentFetcher() *HTTPDocumentFetcher

NewHTTPDocumentFetcher creates a new instance of HTTPDocumentFetcher.

func (*HTTPDocumentFetcher) Fetch added in v0.0.7

func (f *HTTPDocumentFetcher) Fetch(url string) (*goquery.Document, error)

Fetch fetches the HTML document from the specified URL.

type JSONNameRepository added in v0.0.7

type JSONNameRepository struct {
	FilePath string
}

JSONNameRepository is an implementation of the NameRepository using a JSON file.

func (*JSONNameRepository) GetNames added in v0.0.7

func (r *JSONNameRepository) GetNames() (AcceptedNames, error)

GetNames retrieves the accepted names from a JSON file.

type Kiosk

type Kiosk struct {
	Id          string                          `json:"user_id"`
	Title       string                          `json:"title"`
	KioskItems  map[string]map[string]KioskItem `json:"items"`
	LastUpdated int64                           `json:"last_updated"`
}

type KioskCache added in v1.0.3

type KioskCache struct {
	Manager *KioskManager
	Cache   *Cache
}

func NewKioskCache added in v1.0.3

func NewKioskCache(manager *KioskManager, duration time.Duration) *KioskCache

NewKioskCache creates a new instance of KioskCache.

func (*KioskCache) AddItem added in v1.0.3

func (kc *KioskCache) AddItem(name, itemType string, item KioskItem)

AddItem adds a new item to the kiosk and updates the cache accordingly.

func (*KioskCache) GetItem added in v1.0.3

func (kc *KioskCache) GetItem(name string) (KioskItem, error)

GetItem retrieves an item from the kiosk based on its name. It first checks the cache and returns the item if found. If not found in the cache, it retrieves the item from the underlying KioskManager and updates the cache.

func (*KioskCache) GetKiosk added in v1.0.3

func (kc *KioskCache) GetKiosk() (Kiosk, error)

GetKiosk returns a copy of the kiosk from the cache. If the cache is empty, it retrieves the kiosk from the underlying KioskManager and updates the cache.

func (*KioskCache) GetLastUpdated added in v1.0.3

func (kc *KioskCache) GetLastUpdated() int64

GetLastUpdated returns the last updated timestamp of the kiosk.

func (*KioskCache) RemoveItem added in v1.0.3

func (kc *KioskCache) RemoveItem(name, itemType string) error

RemoveItem removes an item from the kiosk based on its name and item type. It updates the cache after removing the item.

type KioskItem

type KioskItem struct {
	Image       string `json:",omitempty"`
	Stock       int64  `json:"stock"`
	Price       int64  `json:"price"`
	LastUpdated int64  `json:"last_updated"`
}

type KioskManager added in v0.0.7

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

KioskManager provides methods for managing the kiosk and its items.

func NewKioskManager added in v0.0.7

func NewKioskManager(id, title string) *KioskManager

NewKioskManager creates a new instance of KioskManager with an empty kiosk.

func (*KioskManager) AddItem added in v0.0.7

func (km *KioskManager) AddItem(name, itemType string, item KioskItem)

AddItem adds a new item to the kiosk.

func (*KioskManager) GetItem added in v0.0.7

func (km *KioskManager) GetItem(name string) (KioskItem, error)

GetItem retrieves an item from the kiosk based on its name.

func (*KioskManager) GetKiosk added in v0.0.7

func (km *KioskManager) GetKiosk() Kiosk

GetKiosk returns a copy of the kiosk.

func (*KioskManager) GetLastUpdated added in v0.0.7

func (km *KioskManager) GetLastUpdated() int64

GetLastUpdated returns the last updated timestamp of the kiosk.

func (*KioskManager) RemoveItem added in v0.0.7

func (km *KioskManager) RemoveItem(name, itemType string) error

RemoveItem removes an item from the kiosk based on its name and item type.

type Name

type Name struct {
	First  string
	Middle string
	Last   string
}

type NameGenerator added in v0.0.7

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

NameGenerator provides methods for generating valid names based on the input and the accepted names list.

func NewNameGenerator added in v0.0.7

func NewNameGenerator(repo NameRepository) (*NameGenerator, error)

NewNameGenerator creates a new instance of NameGenerator and retrieves the default accepted names from the provided URL.

func (*NameGenerator) GenerateName added in v0.0.7

func (g *NameGenerator) GenerateName(input string) (string, error)

GenerateName generates a valid name based on the input and the accepted names list.

func (*NameGenerator) GetDefaultNames added in v1.0.4

func (g *NameGenerator) GetDefaultNames() []string

type NameRepository added in v0.0.7

type NameRepository interface {
	GetNames() (AcceptedNames, error)
}

NameRepository defines the contract for accessing name data.

type PetAttributes

type PetAttributes struct {
	Strength     int64 `json:"strength"`
	Willpower    int64 `json:"will"`
	Intelligence int64 `json:"intelligence"`
	Power        int64 `json:"power"`
	Agility      int64 `json:"agility"`
	Happiness    int64 `json:"happiness"`
}

type PetCalculator added in v0.0.7

type PetCalculator struct{}

PetCalculator provides methods for calculating various attributes based on pet attributes.

func NewPetCalculator added in v0.0.7

func NewPetCalculator() *PetCalculator

NewPetCalculator creates a new instance of PetCalculator.

func (*PetCalculator) Calculate added in v0.0.7

func (c *PetCalculator) Calculate(pa *PetAttributes) map[string]map[string]interface{}

Calculate calculates various attributes based on pet attributes.

type PlayerRanking added in v0.0.6

type PlayerRanking struct {
	Position string `json:"position"`
	Name     string `json:"name"`
	Level    string `json:"level"`
	School   string `json:"school"`
	Wins     string `json:"wins"`
	Rating   string `json:"rating"`
}

PlayerRanking represents the ranking information of a player.

type Presenter added in v0.0.7

type Presenter interface {
	PresentRankings(rankings []PlayerRanking)
	PresentTournaments(tournaments []Tournament)
}

Presenter is responsible for presenting data.

type Raid

type Raid struct {
	GuildID string `json:"guild_id"`
	Gates   []Gate `json:"gates"`
}

Raid represents a raid with multiple gates.

func (*Raid) AddGate

func (r *Raid) AddGate(date string)

AddGate adds a new gate to the raid with the specified date if it doesn't already exist.

func (*Raid) GetGate

func (r *Raid) GetGate(date string) *Gate

GetGate retrieves a gate from the raid based on the date.

type RaidMember

type RaidMember struct {
	RaidPosition string `json:"raid_position"`
	Backup       bool   `json:"backup"`
}

RaidMember represents a member of a raid.

func (*RaidMember) IsBackup

func (r *RaidMember) IsBackup() bool

IsBackup checks if a raid member is a backup.

type RaidRepository added in v0.0.7

type RaidRepository interface {
	GetRaid(guildID string) (*Raid, error)
	SaveRaid(raid *Raid) error
}

RaidRepository provides methods for accessing raid data.

type RaidService added in v0.0.7

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

RaidService provides methods for performing raid-related operations.

func NewRaidService added in v0.0.7

func NewRaidService(repository RaidRepository) *RaidService

NewRaidService creates a new instance of RaidService.

func (*RaidService) GetRaid added in v0.0.7

func (s *RaidService) GetRaid(guildID string) (*Raid, error)

GetRaid retrieves a raid by guild ID.

func (*RaidService) SaveRaid added in v0.0.7

func (s *RaidService) SaveRaid(raid *Raid) error

SaveRaid saves a raid.

type Repository added in v0.0.7

type Repository struct {
	DocumentFetcher DocumentFetcher
	URL             string
}

Repository retrieves data from a source.

func NewRepository added in v0.0.7

func NewRepository(fetcher DocumentFetcher, url string) *Repository

NewRepository creates a new instance of Repository.

func (*Repository) FetchRankings added in v0.0.7

func (r *Repository) FetchRankings() ([]PlayerRanking, error)

FetchRankings retrieves the player rankings.

func (*Repository) FetchTournaments added in v0.0.7

func (r *Repository) FetchTournaments() ([]Tournament, error)

FetchTournaments retrieves the tournaments.

type TimeFormatter added in v0.0.7

type TimeFormatter interface {
	ParseTime(timeString string) (string, error)
}

TimeFormatter provides methods for formatting time.

type TimeService added in v0.0.7

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

TimeService provides methods for working with time.

func NewTimeService added in v0.0.7

func NewTimeService(formatter TimeFormatter) *TimeService

NewTimeService creates a new instance of TimeService.

func (*TimeService) ParseTime added in v0.0.7

func (s *TimeService) ParseTime(timeString string) (string, error)

ParseTime parses a time string into the desired format.

type Tournament added in v0.0.4

type Tournament struct {
	Name      string `json:"name"`
	Levels    string `json:"levels"`
	StartTime string `json:"start_time"`
	Duration  string `json:"duration"`
}

Tournament represents the information of a tournament.

type URLGenerator added in v0.0.7

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

URLGenerator is responsible for generating URLs with parameters.

func NewURLGenerator added in v0.0.7

func NewURLGenerator(baseURL string) *URLGenerator

NewURLGenerator creates a new instance of URLGenerator.

func (*URLGenerator) GenerateURL added in v0.0.7

func (g *URLGenerator) GenerateURL() (string, error)

GenerateURL generates a URL with the provided parameters.

func (*URLGenerator) WithParams added in v0.0.7

func (g *URLGenerator) WithParams(params *URLParams) *URLGenerator

WithParams sets the parameters for the URLGenerator.

type URLNameRepository added in v0.0.7

type URLNameRepository struct {
	URL string
}

URLNameRepository is an implementation of the NameRepository using a remote URL.

func (*URLNameRepository) GetNames added in v0.0.7

func (r *URLNameRepository) GetNames() (AcceptedNames, error)

GetNames retrieves the accepted names from a remote URL.

type URLParams added in v0.0.7

type URLParams struct {
	Age    string
	Levels string
	Filter string
}

URLParams contains the parameters for a URL.

type URLParser added in v0.0.7

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

URLParser is responsible for parsing URL parameters.

func NewURLParser added in v0.0.7

func NewURLParser(rawURL string) *URLParser

NewURLParser creates a new instance of URLParser.

func (*URLParser) ParseURL added in v0.0.7

func (p *URLParser) ParseURL() (*URLParams, error)

ParseURL parses the URL and extracts the relevant parameters.

type WikiResponse added in v1.0.3

type WikiResponse struct {
	Parse struct {
		Title    string   `json:"title"`
		Images   []string `json:"images"`
		WikiText WikiText `json:"wikitext"`
	} `json:"parse"`
}

type WikiService added in v1.0.3

type WikiService struct {
	Client *APIClient
}

WikiService provides methods for interacting with the Wizard101 Central Wiki.

func NewWikiService added in v1.0.3

func NewWikiService() *WikiService

NewWikiService creates a new instance of WikiService.

func (*WikiService) GetWikiText added in v1.0.3

func (s *WikiService) GetWikiText(pageID string) (WikiResponse, error)

GetWikiText returns the WikiText content of the specified page.

func (*WikiService) ParseToJson added in v1.0.4

func (s *WikiService) ParseToJson(pageID string) ([]byte, error)

ParseToJson converts the infobox in the WikiText content to a JSON string.

func (*WikiService) ParseWikiText added in v1.0.4

func (s *WikiService) ParseWikiText(body []byte) (*WikiResponse, error)

ParseWikiText parses the response body into a WikiResponse struct.

type WikiText added in v1.0.3

type WikiText struct {
	Content string `json:"*"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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