cwapi

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2019 License: MIT Imports: 8 Imported by: 1

README

go-chatwars-api

GoDoc

Golang API Wrapper for Chat Wars Telegram MMORPG game. Contains full realization of Chat Wars API v0.10.0

Based on AMQP, so you need to code reactive, but almost all method have sync-version analogs. Fan-out Exchange Routing Keys are also supported.

Examples and other info you can read at GoDoc.

Feel free to contribute!

Documentation

Overview

Golang API Wrapper for Chat Wars Telegram MMORPG game

Examples

Async approach:

package main

import (
	"github.com/L11R/go-chatwars-api"
	"encoding/json"
	"log"
)

func main() {
	client, err := cwapi.NewClient("login", "password")
	if err != nil {
		log.Fatal(err)
	}

	// Async method, it just sends request
	err = client.CreateAuthCode(YourUserID)
	if err != nil {
		log.Fatal(err)
	}

	// Here you will get response
	for u := range client.Updates {
		if u.GetActionsEnum() == cwapi.CreateAuthCode {
			log.Println("Got response!")

			b, err := json.MarshalIndent(u, "", "\t")
			if err != nil {
				log.Fatal(err)
			}

			log.Println(string(b))
		}
	}
}

Sync approach:

package main

import (
	"github.com/L11R/go-chatwars-api"
	"log"
	"bufio"
	"os"
	"fmt"
	"encoding/json"
)

func main() {
	client, err := cwapi.NewClient("login", "password")
	if err != nil {
		log.Fatal(err)
	}

	userID := 123456

	res, err := client.CreateAuthCodeSync(userID)
	if err != nil {
		log.Fatal(err)
	}

	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter text: ")
	b, _, err := reader.ReadLine()
	if err != nil {
		log.Fatal(err)
	}

	authCode := string(b)

	res, err = client.GrantTokenSync(userID, authCode)
	if err != nil {
		log.Fatal(err)
	}

	res, err = client.RequestProfileSync(res.Payload.Token, userID)
	if err != nil {
		log.Fatal(err)
	}

	b, err = json.MarshalIndent(res.Payload, "", "\t")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(string(b))
}

Fan-out Exchange Routing Keys

If you want to deal with routing keys, there are a bunch of methods:

InitDeals()
InitOffers()
InitSexDigest()
InitYellowPages()

After initializing you need just to handle updates from those routes:

err := client.InitYellowPages()
if err != nil {
	log.Fatal(err)
}

for page := range client.YellowPages {
	log.Println("Got page from Yellow Pages!")

	b, err := json.MarshalIndent(page, "", "\t")
	if err != nil {
		log.Fatal(err)
	}

	log.Println(string(b))
}

Feedback

If you have any questions, you can ask them in Chat Wars Development chat: https://t.me/cwapi

Index

Constants

View Source
const (
	CW2 = "amqps://%s:%s@api.chatwars.me:5673/"
	CW3 = "amqps://%s:%s@api.chtwrs.com:5673/"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ActionEnum

type ActionEnum string
const (
	CreateAuthCode           ActionEnum = "createAuthCode"
	GrantToken               ActionEnum = "grantToken"
	AuthAdditionalOperation  ActionEnum = "authAdditionalOperation"
	GrantAdditionalOperation ActionEnum = "grantAdditionalOperation"
	AuthorizePayment         ActionEnum = "authorizePayment"
	Pay                      ActionEnum = "pay"
	Payout                   ActionEnum = "payout"
	GetInfo                  ActionEnum = "getInfo"
	ViewCraftbook            ActionEnum = "viewCraftbook"
	RequestProfile           ActionEnum = "requestProfile"
	RequestBasicInfo         ActionEnum = "requestBasicInfo"
	RequestGearInfo          ActionEnum = "requestGearInfo"
	RequestStock             ActionEnum = "requestStock"
	GuildInfo                ActionEnum = "guildInfo"
	WantToBuy                ActionEnum = "wantToBuy"

	// Unknown action for this lib, check Chat Wars docs
	UnknownAction ActionEnum = "unknownAction"
)

type AuctionDigestItem added in v1.1.0

type AuctionDigestItem struct {
	LotID        string         `json:"lotId"`
	ItemName     string         `json:"itemName"`
	SellerName   string         `json:"sellerName"`
	Quality      *string        `json:"quality"`
	SellerCastle string         `json:"sellerCastle"`
	StartedAt    time.Time      `json:"startedAt"`
	EndedAt      time.Time      `json:"endAt"`
	BuyerCastle  *string        `json:"buyerCastle"`
	Status       *string        `json:"status"`
	FinishedAt   *time.Time     `json:"finishedAt"`
	BuyerName    *string        `json:"buyerName"`
	Price        int            `json:"price"`
	Stats        map[string]int `json:"stats"`
}

au_digest block

type BasicProfile added in v1.1.0

type BasicProfile struct {
	Class   string `json:"class"`
	Attack  int    `json:"atk"`
	Defense int    `json:"def"`
}

type Client

type Client struct {
	User      string
	Password  string
	Updates   chan Response
	RabbitUrl string

	Deals         chan Deal
	Duels         chan Duel
	Offers        chan Offer
	SexDigest     chan []SexDigestItem
	YellowPages   chan []YellowPage
	AuctionDigest chan []AuctionDigestItem
	// contains filtered or unexported fields
}

func NewClient

func NewClient(user string, password string, server ...string) (*Client, error)

Create new client, you can set server optional param, defaults to Chat Wars 2 server (or EU), accepts those variants: cw2, eu, cw3, ru

func (*Client) AuthAdditionalOperation

func (c *Client) AuthAdditionalOperation(token string, operation string) error

Sends request to broaden tokens operations set to user.

func (*Client) AuthAdditionalOperationSync

func (c *Client) AuthAdditionalOperationSync(token string, operation string, userID int) (*Response, error)

Sync-version of AuthAdditionalOperation method.

func (*Client) AuthorizePayment

func (c *Client) AuthorizePayment(token string, transactionID string, pouchesAmount int) error

Sends authorization request to user with confirmation code in it.

func (*Client) AuthorizePaymentSync

func (c *Client) AuthorizePaymentSync(token string, transactionID string, pouchesAmount int, userID int) (*Response, error)

Sync-version of AuthorizePayment method.

func (*Client) CloseConnection

func (c *Client) CloseConnection() error

Close connection and active channel

func (*Client) CreateAuthCode

func (c *Client) CreateAuthCode(userID int) error

Access request from your application to the user.

func (*Client) CreateAuthCodeSync

func (c *Client) CreateAuthCodeSync(userID int) (*Response, error)

Sync-version of CreateAuthCode method.

func (*Client) GetInfo

func (c *Client) GetInfo() error

Request current info about your application. E.g. balance, limits, status.

func (*Client) GrantAdditionalOperation

func (c *Client) GrantAdditionalOperation(token string, requestedID string, authCode string) error

Completes the authAdditionalOperation action.

func (*Client) GrantAdditionalOperationSync

func (c *Client) GrantAdditionalOperationSync(token string, requestedID string, authCode string, userID int) (*Response, error)

Sync-version of GrantAdditionalOperation method.

func (*Client) GrantToken

func (c *Client) GrantToken(userID int, authCode string) error

Exchange auth code for access token.

func (*Client) GrantTokenSync

func (c *Client) GrantTokenSync(userID int, authCode string) (*Response, error)

Sync-version of GrantToken method.

func (*Client) GuildInfo added in v1.1.0

func (c *Client) GuildInfo(token string) error

Request users guild information. Common info and stock. Excluding roster.

func (*Client) GuildInfoSync added in v1.1.0

func (c *Client) GuildInfoSync(token string, userID int) (*Response, error)

Sync-version of GuildInfo method.

func (*Client) InitAuctionDigest added in v1.1.0

func (c *Client) InitAuctionDigest() error

Initializes au_digest public exchange.

func (*Client) InitDeals

func (c *Client) InitDeals() error

Initializes deals public exchange.

func (*Client) InitDuels added in v1.1.0

func (c *Client) InitDuels() error

Initializes offers public exchange.

func (*Client) InitOffers

func (c *Client) InitOffers() error

Initializes offers public exchange.

func (*Client) InitSexDigest

func (c *Client) InitSexDigest() error

Initializes sex_digest public exchange.

func (*Client) InitYellowPages

func (c *Client) InitYellowPages() error

Initializes yellow_pages public exchange.

func (*Client) Pay

func (c *Client) Pay(token string, transactionID string, pouchesAmount int, confirmCode string) error

Previously, transfers held an amount of gold from users account to application’s balance.

func (*Client) PaySync

func (c *Client) PaySync(token string, transactionID string, pouchesAmount int, confirmCode string, userID int) (*Response, error)

Sync-version of Pay method.

func (*Client) Payout

func (c *Client) Payout(token string, transactionID string, pouchesAmount int, message string) error

Transfers of a given amount of gold (or pouches) from the application’s balance to users account.

func (*Client) PayoutSync

func (c *Client) PayoutSync(token string, transactionID string, pouchesAmount int, message string, userID int) (*Response, error)

Sync-version of Payout method.

func (*Client) RequestBasicInfo added in v1.1.0

func (c *Client) RequestBasicInfo(token string) error

Request basic user stats. Base attack and defence (equipment bonuses are not included) and current class.

func (*Client) RequestBasicInfoSync added in v1.1.0

func (c *Client) RequestBasicInfoSync(token string, userID int) (*Response, error)

Sync-version of RequestBasicInfo method.

func (*Client) RequestGearInfo added in v1.1.0

func (c *Client) RequestGearInfo(token string) error

Request user’s current outfit. Keep in mind, that slot names and their amount can be changed without any notice.

func (*Client) RequestGearInfoSync added in v1.1.0

func (c *Client) RequestGearInfoSync(token string, userID int) (*Response, error)

Sync-version of RequestGearInfo method.

func (*Client) RequestProfile

func (c *Client) RequestProfile(token string) error

Request brief user profile information.

func (*Client) RequestProfileSync

func (c *Client) RequestProfileSync(token string, userID int) (*Response, error)

Sync-version of RequstProfile method.

func (*Client) RequestStock

func (c *Client) RequestStock(token string) error

Request users stock information.

func (*Client) RequestStockSync

func (c *Client) RequestStockSync(token string, userID int) (*Response, error)

Sync-version of RequestStock method.

func (*Client) ViewCraftbook added in v1.1.0

func (c *Client) ViewCraftbook(token string) error

Request the list of recipes known to user.

func (*Client) ViewCraftbookSync added in v1.1.0

func (c *Client) ViewCraftbookSync(token string, userID int) (*Response, error)

Sync-version of ViewCraftbook method.

func (*Client) WantToBuy

func (c *Client) WantToBuy(token string, itemCode string, quantity int, price int, exactPrice bool) error

Buys something on exchange.

func (*Client) WantToBuySync

func (c *Client) WantToBuySync(token string, itemCode string, quantity int, price int, exactPrice bool, userID int) (*Response, error)

Buys something on exchange.

type CraftRecord added in v1.1.0

type CraftRecord struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Price int    `json:"price"`
}

type Deal

type Deal struct {
	SellerID     string `json:"sellerId"`
	SellerCastle string `json:"sellerCastle"`
	SellerName   string `json:"sellerName"`
	BuyerID      string `json:"buyerId"`
	BuyerCastle  string `json:"buyerCastle"`
	BuyerName    string `json:"buyerName"`
	Item         string `json:"item"`
	Quantity     int    `json:"qty"`
	Price        int    `json:"price"`
}

Deals block

type Duel added in v1.1.0

type Duel struct {
	Winner      *Duelist `json:"winner"`
	Loser       *Duelist `json:"loser"`
	IsChallenge bool     `json:"isChallenge"`
	IsGuildDuel bool     `json:"isGuildDuel"`
}

type Duelist added in v1.1.0

type Duelist struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Tag    string `json:"tag"`
	Castle string `json:"castle"`
	Level  int    `json:"level"`
	HP     int    `json:"hp"`
}

Duels block

type Offer

type Offer struct {
	SellerID     string `json:"sellerId"`
	SellerCastle string `json:"sellerCastle"`
	SellerName   string `json:"sellerName"`
	Item         string `json:"item"`
	Quantity     int    `json:"qty"`
	Price        int    `json:"price"`
}

Offers block

type OfferItem

type OfferItem struct {
	Item  string `json:"item"`
	Price int    `json:"price"`
	Mana  int    `json:"mana"`
}

type Profile

type Profile struct {
	UserName   string `json:"userName"`
	Castle     string `json:"castle"`
	Level      int    `json:"lvl"`
	Experience int    `json:"exp"`
	Attack     int    `json:"atk"`
	Defense    int    `json:"def"`
	Gold       int    `json:"gold"`
	Pouches    int    `json:"pouches"`
	Guild      string `json:"guild"`
	GuildTag   string `json:"guild_tag"`
	Class      string `json:"class"`
	Mana       int    `json:"mana"`
	Stamina    int    `json:"stamina"`
}

type Request

type Request struct {
	Token   string          `json:"token"`
	Action  string          `json:"action"`
	Payload json.RawMessage `json:"payload"`
}

type ResAuthAdditionalOperation

type ResAuthAdditionalOperation struct {
	Operation string `json:"operation"`
	UserID    int    `json:"userId"`
}

type ResAuthorizePayment

type ResAuthorizePayment struct {
	Fee           map[string]int `json:"fee"`
	Debit         map[string]int `json:"debit"`
	UserID        int            `json:"userId"`
	TransactionId string         `json:"transactionId"`
}

type ResCreateAuthCode

type ResCreateAuthCode struct {
	UserID int `json:"userId"`
}

type ResGetInfo

type ResGetInfo struct {
	Balance int `json:"balance"`
}

type ResGrantAdditionalOperation

type ResGrantAdditionalOperation struct {
	RequestID string `json:"requestId"`
	UserID    int    `json:"userId"`
}

type ResGrantToken

type ResGrantToken struct {
	UserID int    `json:"userId"`
	ID     string `json:"id"`
	Token  string `json:"token"`
}

type ResGuildInfo added in v1.1.0

type ResGuildInfo struct {
	Tag        string         `json:"tag"`
	Level      int            `json:"level"`
	Castle     string         `json:"castle"`
	Glory      int            `json:"glory"`
	Members    int            `json:"members"`
	Name       string         `json:"name"`
	Lobby      string         `json:"lobby"`
	StockSize  int            `json:"stockSize"`
	StockLimit int            `json:"stockLimit"`
	Stock      map[string]int `json:"stock"`
	UserID     int            `json:"userId"`
}

type ResPay

type ResPay struct {
	Fee           map[string]int `json:"fee"`
	Debit         map[string]int `json:"debit"`
	UserID        int            `json:"userId"`
	TransactionId string         `json:"transactionId"`
}

type ResPayout

type ResPayout struct {
	UserID int `json:"userId"`
}

type ResRequestBasicInfo added in v1.1.0

type ResRequestBasicInfo struct {
	Profile *BasicProfile `json:"profile"`
	UserID  int           `json:"userId"`
}

type ResRequestGearInfo added in v1.1.0

type ResRequestGearInfo struct {
	Gear   map[string]string `json:"gear"`
	Ammo   map[string]int    `json:"ammo"`
	UserID int               `json:"userId"`
}

type ResRequestProfile

type ResRequestProfile struct {
	Profile *Profile `json:"profile"`
	UserID  int      `json:"userId"`
}

type ResRequestStock

type ResRequestStock struct {
	Stock  map[string]int `json:"stock"`
	UserID int            `json:"userId"`
}

type ResViewCraftbook added in v1.1.0

type ResViewCraftbook struct {
	Alchemy []*CraftRecord `json:"alchemy"`
	Craft   []*CraftRecord `json:"craft"`
	UserID  int            `json:"userId"`
}

type ResWantToBuy

type ResWantToBuy struct {
	ItemCode string `json:"itemCode"`
	Quantity int    `json:"quantity"`
	UserID   int    `json:"userId"`
}

type Response

type Response struct {
	UUID    string     `json:"uuid"`
	Action  string     `json:"action"`
	Result  string     `json:"result"`
	Payload resPayload `json:"payload"`
}

func (*Response) GetActionEnum

func (res *Response) GetActionEnum() ActionEnum

Returns constant with ActionEnum

func (*Response) GetResultEnum

func (res *Response) GetResultEnum() ResultEnum

Returns constant with ResultEnum

func (*Response) UnmarshalJSON

func (res *Response) UnmarshalJSON(b []byte) error

type ResultEnum

type ResultEnum string
const (
	// Everything is Ok
	Ok ResultEnum = "Ok"
	// Amount is either less than or equal zero
	BadAmount ResultEnum = "BadAmount"
	// The currency you chose is not allowed
	BadCurrency ResultEnum = "BadCurrency"
	// Message format is bad. It could be an invalid javascript, or types are wrong, or not all fields are sane
	BadFormat ResultEnum = "BadFormat"
	// The action you have requested is absent. Check spelling
	ActionNotFound ResultEnum = "ActionNotFound"
	// UserID is wrong, or user became inactive
	NoSuchUser ResultEnum = "NoSuchUser"
	// Your app is not yet registered
	NotRegistered ResultEnum = "NotRegistered"
	// Authorization code is incorrect
	InvalidCode ResultEnum = "InvalidCode"
	// Requested operation not exists
	NoSuchOperation ResultEnum = "NoSuchOperation"
	// If we have some technical difficulties, or bug and are willing for you to repeat request
	TryAgain ResultEnum = "TryAgain"
	// Some field of transaction is bad or confirmation code is wrong
	AuthorizationFailed ResultEnum = "AuthorizationFailed"
	// The player or application balance is insufficient
	InsufficientFunds ResultEnum = "InsufficientFunds"
	// The player is not a high enough level to do this action.
	LevelIsLow ResultEnum = "LevelIsLow"
	// The player is not in implied guild.
	NotInGuild ResultEnum = "NotInGuild"
	// No such token, might be revoked?
	InvalidToken ResultEnum = "InvalidToken"
	// Your app has no rights to execute this action with this token.
	// Payload will contain requiredOperation field.
	// We encourage you to use this field in following authAdditionalOperation, instead of enumerating existing ones
	Forbidden ResultEnum = "Forbidden"

	// Unknown result for this lib, check Chat Wars docs
	UnknownResult ResultEnum = "UnknownResult"
)

type SexDigestItem

type SexDigestItem struct {
	Name   string `json:"name"`
	Prices []int  `json:"prices"`
}

sex_digest block

type Specialization added in v1.1.0

type Specialization struct {
	Gloves int `json:"gloves"`
	Coat   int `json:"coat"`
	Helmet int `json:"helmet"`
	Boots  int `json:"boots"`
	Armor  int `json:"armor"`
	Weapon int `json:"weapon"`
	Shield int `json:"shield"`
}

yellow_pages block

type YellowPage

type YellowPage struct {
	Link               string          `json:"link"`
	Name               string          `json:"name"`
	OwnerName          string          `json:"ownerName"`
	OwnerCastle        string          `json:"ownerCastle"`
	Kind               string          `json:"kind"`
	Mana               int             `json:"mana"`
	Offers             []OfferItem     `json:"offers"`
	Specialization     *Specialization `json:"specialization"`
	GuildDiscount      int             `json:"guildDiscount"`
	CastleDiscount     int             `json:"castleDiscount"`
	MaintenanceEnabled bool            `json:"maintenanceEnabled"`
	MaintenanceCost    int             `json:"maintenanceCost"`
}

Jump to

Keyboard shortcuts

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