utils

package
v0.0.0-...-441339d Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2022 License: GPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BetTotal int64 = 0
View Source
var GameRunning = false
View Source
var PlayersArray []PlayerIdentity
View Source
var RankEmojis map[string]string
View Source
var Roles map[string]string
View Source
var ValidRegions map[string]string

Functions

func AddPlayer

func AddPlayer(discordID, discordName string, wager int64) error

func CalculateTaikoAcc

func CalculateTaikoAcc(topPlay *OsuTopPlay) string

func CheckValidRegion

func CheckValidRegion(region string) (string, error)

CheckValidRegion checks if a shorthand is a valid and return that actual string, also return a error, if there region is not valid

func ClearGame

func ClearGame()

func ComputeDistance

func ComputeDistance(a, b string) int

ComputeDistance returns the levenshtein distance between the strings a and b.

func DownloadOsuFile

func DownloadOsuFile(beatmapID string) error

func FormatCommand

func FormatCommand(command string) string

func FormatName

func FormatName(name []string) string

FormatName formats the given name array to ["install", "gentoo"] => "install_gentoo" | This the osu api format

func GetCurrentMap

func GetCurrentMap() string

func GetDatabase

func GetDatabase() *gorm.DB

GetDatabase returns a pointer to the local db variable.

func GetMods

func GetMods(modNumber string) (string, error)

func GetOsuUsername

func GetOsuUsername(discordId string, args []string) (string, error)

func InPlayers

func InPlayers(discordID string) (int, bool)

Return the index of the player, and a boolean value if they were found in the array

func InitAPI

func InitAPI()

func InitApiKey

func InitApiKey()

func InitCocAPI

func InitCocAPI()

InitCocAPI sets the local cocKey used by the Clash of Clans api.

func InitDatabase

func InitDatabase()

InitDatabase sets up the database given a few parameters from the environment variables.

func LogErrors

func LogErrors(errs []error)

LogErrors prints out all the errors from a list

func PrintPlayers

func PrintPlayers() string

func SetCurrentMap

func SetCurrentMap(currMapID string)

func SetPrefix

func SetPrefix(p string)

func StartGame

func StartGame()

func StartVote

func StartVote(content, startedBy string)

func UnFormatName

func UnFormatName(formattedName string) string

UnFormatName is the inverse of the FormatName function.

Types

type COCPlayer

type COCPlayer struct {
	Clan struct {
		Tag       string `json:"tag"`
		ClanLevel int    `json:"clanLevel"`
		Name      string `json:"name"`
	} `json:"clan"`
	League struct {
		Name string `json:"name"`
	} `json:"league"`
	AttackWins       int    `json:"attackWins"`
	DefenseWins      int    `json:"defenseWins"`
	TownHallLevel    int    `json:"townHallLevel"`
	TownHallWeapon   int    `json:"townHallWeaponLevel"`
	WarStars         int    `json:"warStars"`
	Name             string `json:"name"`
	Tag              string `json:"tag"`
	BuilderHallLevel int    `json:"builderHallLevel"`
	Trophies         int    `json:"trophies"`
	Spells           []struct {
		Name     string `json:"name"`
		Level    int    `json:"level"`
		MaxLevel int    `json:"maxLevel"`
		Village  string `json:"village"`
	} `json:"spells"`
	Heroes []struct {
		Name     string `json:"name"`
		Level    int    `json:"level"`
		MaxLevel int    `json:"maxLevel"`
		Village  string `json:"village"`
	} `json:"heroes"`
	Troop []struct {
		Name     string `json:"name"`
		Level    int    `json:"level"`
		MaxLevel int    `json:"maxLevel"`
		Village  string `json:"village"`
	} `json:"troops"`
}

COCPlayer is a golang struct that mimics the json response from the Clash of Clans api.

func GetCOCPlayerData

func GetCOCPlayerData(playerTag string) (*COCPlayer, error)

GetCOCPlayerData returns the data of a user given a playerTag.

type Champion

type Champion struct {
	Version string `json:"version"`
	ID      string `json:"id"`
	Key     string `json:"key"`
	Name    string `json:"name"`
	Title   string `json:"title"`
	Blurb   string `json:"blurb"`
	Info    struct {
		Attack     int `json:"attack"`
		Defense    int `json:"defense"`
		Magic      int `json:"magic"`
		Difficulty int `json:"difficulty"`
	} `json:"info"`
	Image struct {
		Full   string `json:"full"`
		Sprite string `json:"sprite"`
		Group  string `json:"group"`
		X      int    `json:"x"`
		Y      int    `json:"y"`
		W      int    `json:"w"`
		H      int    `json:"h"`
	} `json:"image"`
	Tags    []string `json:"tags"`
	Partype string   `json:"partype"`
	Stats   struct {
		Hp                   float64 `json:"hp"`
		Hpperlevel           float64 `json:"hpperlevel"`
		Mp                   float64 `json:"mp"`
		Mpperlevel           float64 `json:"mpperlevel"`
		Movespeed            float64 `json:"movespeed"`
		Armor                float64 `json:"armor"`
		Armorperlevel        float64 `json:"armorperlevel"`
		Spellblock           float64 `json:"spellblock"`
		Spellblockperlevel   float64 `json:"spellblockperlevel"`
		Attackrange          float64 `json:"attackrange"`
		Hpregen              float64 `json:"hpregen"`
		Hpregenperlevel      float64 `json:"hpregenperlevel"`
		Mpregen              float64 `json:"mpregen"`
		Mpregenperlevel      float64 `json:"mpregenperlevel"`
		Crit                 float64 `json:"crit"`
		Critperlevel         float64 `json:"critperlevel"`
		Attackdamage         float64 `json:"attackdamage"`
		Attackdamageperlevel float64 `json:"attackdamageperlevel"`
		Attackspeedperlevel  float64 `json:"attackspeedperlevel"`
		Attackspeed          float64 `json:"attackspeed"`
	} `json:"stats"`
}

Champion data model

type ChampionInfo

type ChampionInfo struct {
	FreeChampionIDsForNewPlayers []int `json:"freeChampionIDsForNewPlayers"`
	FreeChampionIDs              []int `json:"freeChampionIDs"`
	MaxNewPlayerLevel            int   `json:"maxNewPlayerLevel"`
}

type ChampionMastery

type ChampionMastery struct {
	ChestGranted                 bool   `json:"chestGranted"`
	ChampionLevel                int    `json:"championLevel"`
	ChampionPoints               int    `json:"championPoints"`
	ChampionID                   int    `json:"championId"`
	ChampionPointsUntilNextLevel int    `json:"championPointsUntilNextLevel"`
	LastPlayTime                 int    `json:"lastPlayTime"`
	TokensEarned                 int    `json:"tokensEarned"`
	ChampionPointsSinceLastLevel int    `json:"championPointsSinceLastLevel"`
	SummonerID                   string `json:"summonerId"`
}

type Champions

type Champions struct {
	Type    string               `json:"type"`
	Format  string               `json:"format"`
	Version string               `json:"version"`
	Data    map[string]*Champion `json:"data"`
}

Champions data model

func ParseChampions

func ParseChampions(sa *gorequest.SuperAgent) *Champions

ParseChampions parses champion data from the riot api

func (*Champions) GetChampionWithKey

func (champions *Champions) GetChampionWithKey(key string) *Champion

GetChampionWithKey loads champion with key, with this we can easily check champion names names

type CodeExecutionResponse

type CodeExecutionResponse struct {
	StatusCode int    `json:"statusCode"`
	Memory     string `json:"memory"`
	Output     string `json:"output"`
	CPUTime    string `json:"cpuTime"`
}

func ExecuteCodeRequest

func ExecuteCodeRequest(lang, code string) (CodeExecutionResponse, error)

type CurrentVote

type CurrentVote struct {
	Content   string
	Against   uint
	Agree     uint
	StartedBy string
}

func GetCurrentVote

func GetCurrentVote() *CurrentVote

type EconomyUser

type EconomyUser struct {
	gorm.Model
	DiscordID string `json:"discord_id"`
	Balance   int64  `json:"balance"`
}

EconomyUser data model

type LeagueUser

type LeagueUser struct {
	gorm.Model
	Username  string `json:"league_user"`
	DiscordID string `json:"discord_id"`
	Region    string `json:"region"`
}

LeagueUser database model

type LiveMatch

type LiveMatch struct {
	GameID            int64         `json:"gameId"`
	MapID             int           `json:"mapId"`
	GameMode          string        `json:"gameMode"`
	GameType          string        `json:"gameType"`
	GameQueueConfigID int           `json:"gameQueueConfigId"`
	Participants      []Participant `json:"participants"`
	Observers         struct {
		EncryptionKey string `json:"encryptionKey"`
	} `json:"observers"`
	PlatformID      string `json:"platformId"`
	BannedChampions []struct {
		ChampionID int `json:"championId"`
		TeamID     int `json:"teamId"`
		PickTurn   int `json:"pickTurn"`
	} `json:"bannedChampions"`
	GameStartTime int64 `json:"gameStartTime"`
	GameLength    int   `json:"gameLength"`
}

type MapResultPP

type MapResultPP struct {
	PlayPP float64 `json:"play_pp"`
	IfFCPP float64 `json:"if_fc"`
	Diff   float64 `json:"diff"`
}

func PrecalculatePP

func PrecalculatePP(scores []OsuScore, currentMapID string) ([]*MapResultPP, error)

The same as 'CalculatePP' for osu scores, but this is optimized for checking many maps, so that we don't have to: request a map, make a file, do calculations, delete file. With this function we can just do calculations for each map

type MatchParticipant

type MatchParticipant struct {
	ParticipantId int              `json:"participantId"`
	ChampionID    int              `json:"championId"`
	Stats         ParticipantStats `json:"stats"`
	TeamID        int              `json:"teamId"`
}

type MatchReference

type MatchReference struct {
	Lane       string `json:"lane"`
	GameID     int    `json:"gameId"`
	Champion   int    `json:"champion"`
	PlatformID string `json:"platformId"`
	Season     int    `json:"season"`
	Queue      int    `json:"queue"`
	Role       string `json:"role"`
	Timestamp  int64  `json:"timestamp"`
}

MatchReference contains information about a game by a single summoner

type Matches

type Matches struct {
	Matches []struct {
		PlatformID string `json:"platformId"`
		GameID     int64  `json:"gameId"`
		Champion   int    `json:"champion"`
		Queue      int    `json:"queue"`
		Season     int    `json:"season"`
		Timestamp  int64  `json:"timestamp"`
		Role       string `json:"role"`
		Lane       string `json:"lane"`
	} `json:"matches"`
	StartIndex int `json:"startIndex"`
	EndIndex   int `json:"endIndex"`
	TotalGames int `json:"totalGames"`
}

type Matchlist

type Matchlist struct {
	Matches    []*MatchReference `json:"matches"`
	TotalGames int               `json:"totalGames"`
	StartIndex int               `json:"startIndex"`
	EndIndex   int               `json:"endIndex"`
}

type OsuBeatmap

type OsuBeatmap struct {
	Approved     string `json:"approved"`
	BPM          string `json:"bpm"`
	Difficulty   string `json:"difficultyrating"`
	Created      string `json:"creator"`
	Artist       string `json:"artist"`
	Title        string `json:"title"`
	TotalLength  string `json:"total_length"`
	MaxCombo     string `json:"max_combo"`
	Version      string `json:"version"`
	BeatmapSetID string `json:"beatmapset_id"`
}

func GetOsuBeatmap

func GetOsuBeatmap(beatmapID string) (*OsuBeatmap, error)

func GetOsuBeatmapMods

func GetOsuBeatmapMods(beatmapID, mods string) (*OsuBeatmap, error)

type OsuGame

type OsuGame struct {
	GameID      string `json:"game_id"`
	StartTime   string `json:"start_time"`
	EndTime     string `json:"end_time"`
	BeatmapID   string `json:"beatmap_id"`
	PlayMode    string `json:"play_mode"`
	MatchType   string `json:"match_type"`
	ScoringType string `json:"scoring_type"`
	TeamType    string `json:"team_type"`
	Mods        string `json:"mods"`
	Scores      OsuGameScore
}

type OsuGameScore

type OsuGameScore struct {
	Slot        string `json:"slot"`
	Team        string `json:"team"`
	UserID      string `json:"user_id"`
	Score       string `json:"score"`
	MaxCombo    string `json:"max_combo"`
	Rank        string `json:"rank"`
	Count300    string `json:"count300"`
	Count100    string `json:"count100"`
	Count50     string `json:"count50"`
	CountMiss   string `json:"countmiss"`
	CountGeki   string `json:"countgeki"`
	CountKatu   string `json:"countkatu"`
	Pass        string `json:"pass"`
	EnabledMods string `json:"enabled_mods"`
}

type OsuMatch

type OsuMatch struct {
	MatchID   string `json:"match_id"`
	Name      string `json:"name"`
	StartTime string `json:"start_time"`
	EndTime   string `json:"end_time"`
}

type OsuMultiMatch

type OsuMultiMatch struct {
	Match OsuMatch
	Games []OsuGame
}

func GetMultiplayerGame

func GetMultiplayerGame(matchID string) (*OsuMultiMatch, error)

type OsuRecentPlay

type OsuRecentPlay struct {
	UserID      string `json:"user_id"`
	BeatmapID   string `json:"beatmap_id"`
	Score       string `json:"score"`
	MaxCombo    string `json:"maxcombo"`
	Count50     string `json:"count50"`
	Count100    string `json:"count100"`
	Count300    string `json:"count300"`
	CountMiss   string `json:"countmiss"`
	EnabledMods string `json:"enabled_mods"`
	Date        string `json:"date"`
	Rank        string `json:"rank"`
}

func GetRecentPlay

func GetRecentPlay(username string) (*OsuRecentPlay, error)

func (*OsuRecentPlay) CalculateAcc

func (rp *OsuRecentPlay) CalculateAcc() string

func (*OsuRecentPlay) CalculatePP

func (rp *OsuRecentPlay) CalculatePP() (*MapResultPP, error)

type OsuScore

type OsuScore struct {
	BeatmapID   string
	ScoreID     string `json:"score_id"`
	Score       string `json:"score"`
	Username    string `json:"username"`
	Count300    string `json:"count300"`
	Count100    string `json:"count100"`
	Count50     string `json:"count50"`
	CountMiss   string `json:"countmiss"`
	EnabledMods string `json:"enabled_mods"`
	UserID      string `json:"user_id"`
	Date        string `json:"date"`
	Rank        string `json:"rank"`
	PP          string `json:"pp"`
	MaxCombo    string `json:"maxcombo"`
}

func GetPlaysInBeatmapFromUser

func GetPlaysInBeatmapFromUser(beatmapID, userID string) ([]OsuScore, error)

func GetScoresForCurrentMap

func GetScoresForCurrentMap(username string) ([]OsuScore, error)

func (*OsuScore) CalculateAcc

func (rp *OsuScore) CalculateAcc() string

func (*OsuScore) CalculatePP

func (rp *OsuScore) CalculatePP(currentMapID string) (*MapResultPP, error)

type OsuTopPlay

type OsuTopPlay struct {
	BeatmapID   string `json:"beatmap_id"`
	ScoreID     string `json:"score_id"`
	Score       string `json:"score"`
	MaxCombo    string `json:"maxcombo"`
	Count50     string `json:"count50"`
	Count100    string `json:"count100"`
	Count300    string `json:"count300"`
	CountMiss   string `json:"countmiss"`
	Perfect     string `json:"perfect"`
	EnabledMods string `json:"enabled_mods"`
	Date        string `json:"date"`
	Rank        string `json:"rank"`
	PP          string `json:"pp"`
	UserID      string `json:"user_id"`
}

func GetModeTopPlays

func GetModeTopPlays(username, mode string) ([]OsuTopPlay, error)

func (*OsuTopPlay) CalculateAll

func (topPlay *OsuTopPlay) CalculateAll() (*MapResultPP, error)

func (*OsuTopPlay) CalculateDiff

func (topPlay *OsuTopPlay) CalculateDiff() (float64, error)

func (*OsuTopPlay) CalculateTopPlayAcc

func (tp *OsuTopPlay) CalculateTopPlayAcc() string

Acc calculations for different plays, could be placed into different functions, but usage is more clear when used as independent methods

type OsuUserResponse

type OsuUserResponse struct {
	Username      string `json:"username"`
	Playcount     string `json:"playcount"`
	RankedScore   string `json:"ranked_score"`
	PPRank        string `json:"pp_rank"`
	Level         string `json:"level"`
	Accuracy      string `json:"accuracy"`
	Country       string `json:"country"`
	SecondsPlayed string `json:"total_seconds_played"`
	PPCountryRank string `json:"pp_country_rank"`
	RawPP         string `json:"pp_raw"`
	UserID        string `json:"user_id"`
}

Since golang is a static typed language we need to create structs for the json requests note that we don't need to add a field for every single json field, just for those which we need

func GetUserFromOSU

func GetUserFromOSU(username string) (*OsuUserResponse, error)

type Participant

type Participant struct {
	TeamID                   uint8         `json:"teamId"`
	ChampionID               int           `json:"championId"`
	ProfileIconID            int           `json:"profileIconId"`
	SummonerName             string        `json:"summonerName"`
	Bot                      bool          `json:"bot"`
	SummonerID               string        `json:"summonerId"`
	GameCustomizationObjects []interface{} `json:"gameCustomizationObjects"`
	Perks                    struct {
		PerkIds      []int `json:"perkIds"`
		PerkStyle    int   `json:"perkStyle"`
		PerkSubStyle int   `json:"perkSubStyle"`
	} `json:"perks"`
}

type ParticipantStats

type ParticipantStats struct {
	LargestMultiKill int `json:"largestMultiKill"`
	ChampLevel       int `json:"champLevel"`
	Deaths           int `json:"deaths"`
	Kills            int `json:"kills"`
	Assists          int `json:"assists"`
}

type Player

type Player struct {
	ProfileIcon  int    `json:"profileIcon"`
	AccountID    string `json:"accountId"`
	SummonerName string `json:"summonerName"`
	SummonerID   string `json:"summonerId"`
}

type PlayerChance

type PlayerChance struct {
	Player    PlayerIdentity
	TopTicket float64
	MinTicket float64
}

type PlayerIdentity

type PlayerIdentity struct {
	DiscordID string `json:"discord_id"`
	Username  string `json:"username"`
	Wager     int64  `json:"wager"`
}

func ChooseWinner

func ChooseWinner() (PlayerIdentity, float64)

Return the Player struct with discord id and username, and also returns the winning ticket

type RiotClient

type RiotClient struct {
	BaseURL   string `json:"base_url"`
	Token     string `json:"token"`
	Champions Champions
}

func NewRiotClient

func NewRiotClient(region, token string) RiotClient

NewRiotClient returns an api client using a given reagion and a api authentication token.

func (*RiotClient) GetFreeRotation

func (c *RiotClient) GetFreeRotation() (*ChampionInfo, error)

GetFreeRotation returns the free rotations of champions.

func (*RiotClient) GetListOfMatches

func (c *RiotClient) GetListOfMatches(accountId string, begin, end int) (*Matchlist, error)

GetListOfMatches returns a list of matches from an account id, given an beginning and end index.

func (*RiotClient) GetLiveMatchBySummonerName

func (c *RiotClient) GetLiveMatchBySummonerName(summonerName string) ([]SanitizedRank, error)

GetLiveMatchBySummonerName searches for a live match given a summoner's name.

func (*RiotClient) GetSingleChampionMastery

func (c *RiotClient) GetSingleChampionMastery(summonerID, championID string) (
	*ChampionMastery, error)

GetSingleChampionMastery gets the amount of mastery points that a user has on a given champion.

func (*RiotClient) GetSingleMatch

func (c *RiotClient) GetSingleMatch(matchID string) (*SingleMatch, error)

GetSingleMatch returns information about a match given a match id.

func (*RiotClient) GetSummonerLiveMatch

func (c *RiotClient) GetSummonerLiveMatch(summoner *Summoner) (*LiveMatch, error)

GetSummonerLiveMatch finds the match data of the user in an active game.

func (*RiotClient) GetSummonerRankWithID

func (c *RiotClient) GetSummonerRankWithID(id string) ([]SummonerRank, error)

GetSummonerRankWithID returns the solo&duo and flex ranks of a summoner with param: id

func (*RiotClient) GetSummonerWithName

func (c *RiotClient) GetSummonerWithName(name string) (*Summoner, error)

GetSummonerWithName returns a summoner struct using their username.

func (*RiotClient) ListsSummonerMasteries

func (c *RiotClient) ListsSummonerMasteries(summonerID string) ([]*ChampionMastery, error)

ListsSummonerMasteries returns a list that has the amount of masteries the user has for each champion in the game.

func (*RiotClient) NewAgent

func (c *RiotClient) NewAgent(path string, query string) *gorequest.SuperAgent

NewAgent creates an returns a new request SuperAgent

func (*RiotClient) NewSanitizedRank

func (c *RiotClient) NewSanitizedRank(summonerName string, team uint8, championId int) SanitizedRank

NewSanitizedRank sanitizes user data into a table

type SanitizedRank

type SanitizedRank struct {
	SummonerName string
	Team         string
	Champion     string
	Solo         string
	Flex         string
}

type SingleMatch

type SingleMatch struct {
	GameID                int64              `json:"gameId"`
	QueueID               int64              `json:"queueId"`
	GameType              string             `json:"gameType"`
	GameDuration          int64              `json:"gameDuration"`
	PlatformID            string             `json:"platformId"`
	GameCreation          int64              `json:"gameCreation"`
	SeasionID             int                `json:"seasonId"`
	GameVersion           string             `json:"gameVersion"`
	MapID                 int                `json:"mapId"`
	GameMode              string             `json:"gameMode"`
	Participants          []MatchParticipant `json:"participants"`
	ParticipantIdentities []struct {
		ParticipantID int    `json:"participantId"`
		Player        Player `json:"player"`
	} `json:"participantIdentities"`
}

type Summoner

type Summoner struct {
	ID            string `json:"id"`
	AccountID     string `json:"accountid"`
	PUUID         string `json:"puuid"`
	Name          string `json:"name"`
	ProfileIconID int    `json:"profileiconid"`
	Revisiondate  int64  `json:"revisiondate"`
	SummonerLevel int    `json:"summonerlevel"`
}

type SummonerRank

type SummonerRank struct {
	LeagueID     string `json:"leagueId"`
	QueueType    string `json:"queueType"`
	Tier         string `json:"tier"`
	Rank         string `json:"rank"`
	SummonerID   string `json:"summonerId"`
	SummonerName string `json:"summonerName"`
	LeaguePoints int    `json:"leaguePoints"`
	Wins         int    `json:"wins"`
	Losses       int    `json:"losses"`
	Veteran      bool   `json:"veteran"`
	Inactive     bool   `json:"inactive"`
	FreshBlood   bool   `json:"freshBlood"`
	HotStreak    bool   `json:"hotStreak"`
	MiniSeries   struct {
		Target   int    `json:"target"`
		Wins     int    `json:"wins"`
		Losses   int    `json:"losses"`
		Progress string `json:"progress"`
	} `json:"miniSeries,omitempty"`
}

type User

type User struct {
	gorm.Model
	DiscordID string `json:"discord_id"`
	OsuName   string `json:"osu_name"`
}

User database model

func CheckIfSet

func CheckIfSet(userID string) (User, error)

CheckIfSet checks if a user already exists for a given discord_id

Jump to

Keyboard shortcuts

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