Archived
1

Pokememes possibilities, some refactoring

This commit is contained in:
Vladimir Hodakov 2017-10-13 03:05:26 +04:00
parent 2849d16587
commit ef924d26c7
29 changed files with 438 additions and 293 deletions

View File

@ -12,7 +12,7 @@ import (
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
const VERSION = "0.25" const VERSION = "0.28"
type DatabaseConnection struct { type DatabaseConnection struct {
Host string `yaml:"host"` Host string `yaml:"host"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Elements struct { type Element struct {
Id int `db:"id"` Id int `db:"id"`
Symbol string `db:"symbol"` Symbol string `db:"symbol"`
Name string `db:"name"` Name string `db:"name"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Leagues struct { type League struct {
Id int `db:"id"` Id int `db:"id"`
Symbol string `db:"symbol"` Symbol string `db:"symbol"`
Name string `db:"name"` Name string `db:"name"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Levels struct { type Level struct {
Id int `db:"id"` Id int `db:"id"`
Max_exp int `db:"max_exp"` Max_exp int `db:"max_exp"`
Max_egg int `db:"max_egg"` Max_egg int `db:"max_egg"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Locations struct { type Location struct {
Id int `db:"id"` Id int `db:"id"`
Symbol string `db:"symbol"` Symbol string `db:"symbol"`
Name string `db:"name"` Name string `db:"name"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Players struct { type Player struct {
Id int `db:"id"` Id int `db:"id"`
Telegram_id int `db:"telegram_id"` Telegram_id int `db:"telegram_id"`
League_id int `db:"league_id"` League_id int `db:"league_id"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Pokememes struct { type Pokememe struct {
Id int `db:"id"` Id int `db:"id"`
Grade int `db:"grade"` Grade int `db:"grade"`
Name string `db:"name"` Name string `db:"name"`
@ -23,3 +23,11 @@ type Pokememes struct {
Player_id int `db:"player_id"` Player_id int `db:"player_id"`
Created_at time.Time `db:"created_at"` Created_at time.Time `db:"created_at"`
} }
// Type for handling pokememe with all informations about locations and elements
type PokememeFull struct {
Pokememe Pokememe
Locations []Location
Elements []Element
}

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type PokememesElements struct { type PokememeElement struct {
Id int `db:"id"` Id int `db:"id"`
Pokememe_id int `db:"pokememe_id"` Pokememe_id int `db:"pokememe_id"`
Element_id int `db:"element_id"` Element_id int `db:"element_id"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type PokememesLocations struct { type PokememeLocation struct {
Id int `db:"id"` Id int `db:"id"`
Pokememe_id int `db:"pokememe_id"` Pokememe_id int `db:"pokememe_id"`
Location_id int `db:"location_id"` Location_id int `db:"location_id"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Profiles struct { type Profile struct {
Id int `db:"id"` Id int `db:"id"`
Player_id int `db:"player_id"` Player_id int `db:"player_id"`
Nickname string `db:"nickname"` Nickname string `db:"nickname"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type ProfilesPokememes struct { type ProfilePokememe struct {
Id int `db:"id"` Id int `db:"id"`
Profile_id int `db:"profile_id"` Profile_id int `db:"profile_id"`
Pokememe_id int `db:"pokememe_id"` Pokememe_id int `db:"pokememe_id"`

View File

@ -1,14 +1,14 @@
// i2_bot Instinct PokememBro Bot // i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov // Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package dbmappings package dbmapping
import ( import (
// stdlib // stdlib
"time" "time"
) )
type Weapons struct { type Weapon struct {
Id int `db:"id"` Id int `db:"id"`
Name string `db:"name"` Name string `db:"name"`
Power int `db:"power"` Power int `db:"power"`

View File

@ -3,8 +3,20 @@
package gettersinterface package gettersinterface
import (
// local
"../../dbmapping"
)
type GettersInterface interface { type GettersInterface interface {
Init() Init()
// Player
GetOrCreatePlayer(telegram_id int) (dbmapping.Player, bool)
// Profile
GetProfile(player_id int) (dbmapping.Profile, bool)
// Pokememes
GetPokememes() ([]dbmapping.PokememeFull, bool)
GetPokememeByID(pokememe_id string) (dbmapping.PokememeFull, bool)
// Possibilities // Possibilities
PossibilityRequiredPokeballs(location int, grade int, lvl int) int PossibilityRequiredPokeballs(location int, grade int, lvl int) (float64, int)
} }

38
lib/getters/player.go Normal file
View File

@ -0,0 +1,38 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package getters
import (
// stdlib
"log"
"time"
// local
"../dbmapping"
)
func (g *Getters) GetOrCreatePlayer(telegram_id int) (dbmapping.Player, bool) {
player_raw := dbmapping.Player{}
err := c.Db.Get(&player_raw, c.Db.Rebind("SELECT * FROM players WHERE telegram_id=?"), telegram_id)
if err != nil {
log.Printf("Message user not found in database.")
log.Printf(err.Error())
// Create "nobody" user
player_raw.Telegram_id = telegram_id
player_raw.League_id = 0
player_raw.Squad_id = 0
player_raw.Status = "nobody"
player_raw.Created_at = time.Now().UTC()
player_raw.Updated_at = time.Now().UTC()
_, err = c.Db.NamedExec("INSERT INTO players VALUES(NULL, :telegram_id, :league_id, :squad_id, :status, :created_at, :updated_at)", &player_raw)
if err != nil {
log.Printf(err.Error())
return player_raw, false
}
} else {
log.Printf("Message user found in database.")
}
return player_raw, true
}

143
lib/getters/pokememes.go Normal file
View File

@ -0,0 +1,143 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package getters
import (
// stdlib
"log"
"strconv"
// local
"../dbmapping"
)
func (g *Getters) GetPokememes() ([]dbmapping.PokememeFull, bool) {
pokememes_full := []dbmapping.PokememeFull{}
pokememes := []dbmapping.Pokememe{}
err := c.Db.Select(&pokememes, "SELECT * FROM pokememes ORDER BY grade asc, name asc");
if err != nil {
log.Println(err)
return pokememes_full, false
}
elements := []dbmapping.Element{}
err = c.Db.Select(&elements, "SELECT * FROM elements");
if err != nil {
log.Println(err)
return pokememes_full, false
}
locations := []dbmapping.Location{}
err = c.Db.Select(&locations, "SELECT * FROM locations");
if err != nil {
log.Println(err)
return pokememes_full, false
}
pokememes_elements := []dbmapping.PokememeElement{}
err = c.Db.Select(&pokememes_elements, "SELECT * FROM pokememes_elements");
if err != nil {
log.Println(err)
return pokememes_full, false
}
pokememes_locations := []dbmapping.PokememeLocation{}
err = c.Db.Select(&pokememes_locations, "SELECT * FROM pokememes_locations");
if err != nil {
log.Println(err)
return pokememes_full, false
}
for i := range(pokememes) {
full_pokememe := dbmapping.PokememeFull{}
elements_listed := []dbmapping.Element{}
locations_listed := []dbmapping.Location{}
for j := range(pokememes_locations) {
if pokememes_locations[j].Pokememe_id == pokememes[i].Id {
for l := range(locations) {
if pokememes_locations[j].Location_id == locations[l].Id {
locations_listed = append(locations_listed, locations[l])
}
}
}
}
for k := range(pokememes_elements) {
if pokememes_elements[k].Pokememe_id == pokememes[i].Id {
for e := range(elements) {
if pokememes_elements[k].Element_id == elements[e].Id {
elements_listed = append(elements_listed, elements[e])
}
}
}
}
full_pokememe.Pokememe = pokememes[i]
full_pokememe.Elements = elements_listed
full_pokememe.Locations = locations_listed
pokememes_full = append(pokememes_full, full_pokememe)
}
return pokememes_full, true
}
func (g *Getters) GetPokememeByID(pokememe_id string) (dbmapping.PokememeFull, bool) {
pokememe_full := dbmapping.PokememeFull{}
pokememe := dbmapping.Pokememe{}
err := c.Db.Get(&pokememe, c.Db.Rebind("SELECT * FROM pokememes WHERE id=?"), pokememe_id)
if err != nil {
log.Println(err)
return pokememe_full, false
}
elements := []dbmapping.Element{}
err = c.Db.Select(&elements, "SELECT * FROM elements");
if err != nil {
log.Println(err)
return pokememe_full, false
}
locations := []dbmapping.Location{}
err = c.Db.Select(&locations, "SELECT * FROM locations");
if err != nil {
log.Println(err)
return pokememe_full, false
}
pokememes_elements := []dbmapping.PokememeElement{}
err = c.Db.Select(&pokememes_elements, "SELECT * FROM pokememes_elements WHERE pokememe_id='" + strconv.Itoa(pokememe.Id) + "'");
if err != nil {
log.Println(err)
return pokememe_full, false
}
pokememes_locations := []dbmapping.PokememeLocation{}
err = c.Db.Select(&pokememes_locations, "SELECT * FROM pokememes_locations WHERE pokememe_id='" + strconv.Itoa(pokememe.Id) + "'");
if err != nil {
log.Println(err)
return pokememe_full, false
}
elements_listed := []dbmapping.Element{}
locations_listed := []dbmapping.Location{}
for j := range(pokememes_locations) {
if pokememes_locations[j].Pokememe_id == pokememe.Id {
for l := range(locations) {
if pokememes_locations[j].Location_id == locations[l].Id {
locations_listed = append(locations_listed, locations[l])
}
}
}
}
for k := range(pokememes_elements) {
if pokememes_elements[k].Pokememe_id == pokememe.Id {
for e := range(elements) {
if pokememes_elements[k].Element_id == elements[e].Id {
elements_listed = append(elements_listed, elements[e])
}
}
}
}
pokememe_full.Pokememe = pokememe
pokememe_full.Elements = elements_listed
pokememe_full.Locations = locations_listed
return pokememe_full, true
}

View File

@ -8,9 +8,10 @@ import (
"log" "log"
) )
func (g *Getters) PossibilityRequiredPokeballs(location int, grade int, lvl int) int { func (g *Getters) PossibilityRequiredPokeballs(location int, grade int, lvl int) (float64, int) {
var base_possibility float64 = 0.00 var base_possibility float64 = 0.00
var required_pokeballs int = 0 var required_pokeballs int = 0
var percentile = 0.00
if lvl > 3 { if lvl > 3 {
switch { switch {
@ -70,8 +71,9 @@ func (g *Getters) PossibilityRequiredPokeballs(location int, grade int, lvl int)
} }
if base_possibility != 0 && number_of_pokememes != 0 { if base_possibility != 0 && number_of_pokememes != 0 {
required_pokeballs = int(1.0 / (base_possibility / float64(number_of_pokememes))) percentile = base_possibility * 100.0 / float64(number_of_pokememes)
required_pokeballs = int(100.0 / percentile)
} }
return required_pokeballs return percentile, required_pokeballs
} }

22
lib/getters/profile.go Normal file
View File

@ -0,0 +1,22 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package getters
import (
// stdlib
"log"
// local
"../dbmapping"
)
func (g *Getters) GetProfile(profile_id int) (dbmapping.Profile, bool) {
profile_raw := dbmapping.Profile{}
err := c.Db.Get(&profile_raw, c.Db.Rebind("SELECT * FROM profiles WHERE player_id=? ORDER BY created_at DESC LIMIT 1"), profile_id)
if err != nil {
log.Println(err)
return profile_raw, false
}
return profile_raw, true
}

View File

@ -0,0 +1,27 @@
// i2_bot Instinct PokememBro Bot
// Copyright (c) 2017 Vladimir "fat0troll" Hodakov
package migrations
import (
// stdlib
"database/sql"
)
func FixTimeElementUp(tx *sql.Tx) error {
_, err := tx.Exec("UPDATE `elements` SET league_id=3 WHERE symbol='⌛';")
if err != nil {
return err
}
return nil
}
func FixTimeElementDown(tx *sql.Tx) error {
_, err := tx.Exec("UPDATE `elements` SET league_id=1 WHERE symbol='⌛';")
if err != nil {
return err
}
return nil
}

View File

@ -28,6 +28,7 @@ func (m *Migrations) Init() {
goose.AddNamedMigration("11_profile_data_additions.go", ProfileDataAdditionsUp, ProfileDataAdditionsDown) goose.AddNamedMigration("11_profile_data_additions.go", ProfileDataAdditionsUp, ProfileDataAdditionsDown)
goose.AddNamedMigration("12_create_profile_relations.go", CreateProfileRelationsUp, CreateProfileRelationsDown) goose.AddNamedMigration("12_create_profile_relations.go", CreateProfileRelationsUp, CreateProfileRelationsDown)
goose.AddNamedMigration("13_create_weapons_and_add_wealth.go", CreateWeaponsAndAddWealthUp, CreateWeaponsAndAddWealthDown) goose.AddNamedMigration("13_create_weapons_and_add_wealth.go", CreateWeaponsAndAddWealthUp, CreateWeaponsAndAddWealthDown)
goose.AddNamedMigration("14_fix_time_element.go", FixTimeElementUp, FixTimeElementDown)
} }
func (m *Migrations) Migrate() error { func (m *Migrations) Migrate() error {

View File

@ -7,12 +7,12 @@ import (
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local // local
"../../dbmappings" "../../dbmapping"
) )
type ParsersInterface interface { type ParsersInterface interface {
ParsePokememe(text string, player_raw dbmappings.Players) string ParsePokememe(text string, player_raw dbmapping.Player) string
ParseProfile(update tgbotapi.Update, player_raw dbmappings.Players) string ParseProfile(update tgbotapi.Update, player_raw dbmapping.Player) string
ReturnPoints(points int) string ReturnPoints(points int) string
} }

View File

@ -11,7 +11,7 @@ import (
"strconv" "strconv"
"time" "time"
// local // local
"../dbmappings" "../dbmapping"
) )
// Internal functions // Internal functions
@ -34,7 +34,7 @@ func (p *Parsers) getPoints(points_str string) int {
// External functions // External functions
func (p *Parsers) ParsePokememe(text string, player_raw dbmappings.Players) string { func (p *Parsers) ParsePokememe(text string, player_raw dbmapping.Player) string {
var defendable_pokememe bool = false var defendable_pokememe bool = false
pokememe_info_strings := strings.Split(text, "\n") pokememe_info_strings := strings.Split(text, "\n")
pokememe_info_runed_strings := make([][]rune, 0) pokememe_info_runed_strings := make([][]rune, 0)
@ -47,7 +47,7 @@ func (p *Parsers) ParsePokememe(text string, player_raw dbmappings.Players) stri
} }
// Getting elements // Getting elements
elements := []dbmappings.Elements{} elements := []dbmapping.Element{}
element_emojis := make([]string, 0) element_emojis := make([]string, 0)
element_emojis = append(element_emojis, string(pokememe_info_runed_strings[4][11])) element_emojis = append(element_emojis, string(pokememe_info_runed_strings[4][11]))
if len(pokememe_info_runed_strings[4]) > 12 { if len(pokememe_info_runed_strings[4]) > 12 {
@ -75,7 +75,7 @@ func (p *Parsers) ParsePokememe(text string, player_raw dbmappings.Players) stri
defence := "0" defence := "0"
price := "0" price := "0"
locations := []dbmappings.Locations{} locations := []dbmapping.Location{}
purchaseable := false purchaseable := false
image := "" image := ""
@ -180,7 +180,7 @@ func (p *Parsers) ParsePokememe(text string, player_raw dbmappings.Players) stri
log.Printf("Image: " + image) log.Printf("Image: " + image)
// Building pokememe // Building pokememe
pokememe := dbmappings.Pokememes{} pokememe := dbmapping.Pokememe{}
// Checking if pokememe exists in database // Checking if pokememe exists in database
err3 := c.Db.Get(&pokememe, c.Db.Rebind("SELECT * FROM pokememes WHERE grade='" + grade + "' AND name='" + name + "';")) err3 := c.Db.Get(&pokememe, c.Db.Rebind("SELECT * FROM pokememes WHERE grade='" + grade + "' AND name='" + name + "';"))
if err3 != nil { if err3 != nil {
@ -227,7 +227,7 @@ func (p *Parsers) ParsePokememe(text string, player_raw dbmappings.Players) stri
return "fail" return "fail"
} }
for i := range(elements) { for i := range(elements) {
link := dbmappings.PokememesElements{} link := dbmapping.PokememeElement{}
link.Pokememe_id = pokememe.Id link.Pokememe_id = pokememe.Id
link.Element_id = elements[i].Id link.Element_id = elements[i].Id
link.Created_at = time.Now().UTC() link.Created_at = time.Now().UTC()
@ -239,7 +239,7 @@ func (p *Parsers) ParsePokememe(text string, player_raw dbmappings.Players) stri
} }
} }
for i := range(locations) { for i := range(locations) {
link := dbmappings.PokememesLocations{} link := dbmapping.PokememeLocation{}
link.Pokememe_id = pokememe.Id link.Pokememe_id = pokememe.Id
link.Location_id = locations[i].Id link.Location_id = locations[i].Id
link.Created_at = time.Now().UTC() link.Created_at = time.Now().UTC()

View File

@ -13,13 +13,13 @@ import (
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local // local
"../dbmappings" "../dbmapping"
) )
// Internal functions // Internal functions
func (p *Parsers) fillProfilePokememe(profile_id int, meme string, attack string, rarity string) { func (p *Parsers) fillProfilePokememe(profile_id int, meme string, attack string, rarity string) {
spk_raw := dbmappings.Pokememes{} spk_raw := dbmapping.Pokememe{}
err := c.Db.Get(&spk_raw, c.Db.Rebind("SELECT * FROM pokememes WHERE name='" + meme + "';")) err := c.Db.Get(&spk_raw, c.Db.Rebind("SELECT * FROM pokememes WHERE name='" + meme + "';"))
if err != nil { if err != nil {
log.Println(err) log.Println(err)
@ -32,7 +32,7 @@ func (p *Parsers) fillProfilePokememe(profile_id int, meme string, attack string
} }
level := int(float64(attack_int) / orig_attack) level := int(float64(attack_int) / orig_attack)
ppk := dbmappings.ProfilesPokememes{} ppk := dbmapping.ProfilePokememe{}
ppk.Profile_id = profile_id ppk.Profile_id = profile_id
ppk.Pokememe_id = spk_raw.Id ppk.Pokememe_id = spk_raw.Id
ppk.Pokememe_lvl = level ppk.Pokememe_lvl = level
@ -47,7 +47,7 @@ func (p *Parsers) fillProfilePokememe(profile_id int, meme string, attack string
// External functions // External functions
func (p *Parsers) ParseProfile(update tgbotapi.Update, player_raw dbmappings.Players) string { func (p *Parsers) ParseProfile(update tgbotapi.Update, player_raw dbmapping.Player) string {
text := update.Message.Text text := update.Message.Text
log.Println(text) log.Println(text)
@ -57,7 +57,7 @@ func (p *Parsers) ParseProfile(update tgbotapi.Update, player_raw dbmappings.Pla
profile_info_runed_strings = append(profile_info_runed_strings, []rune(profile_info_strings[i])) profile_info_runed_strings = append(profile_info_runed_strings, []rune(profile_info_strings[i]))
} }
league := dbmappings.Leagues{} league := dbmapping.League{}
telegram_nickname := update.Message.From.UserName telegram_nickname := update.Message.From.UserName
nickname := "" nickname := ""
@ -199,7 +199,7 @@ func (p *Parsers) ParseProfile(update tgbotapi.Update, player_raw dbmappings.Pla
} }
// Information is gathered, let's create profile in database! // Information is gathered, let's create profile in database!
weapon_raw := dbmappings.Weapons{} weapon_raw := dbmapping.Weapon{}
err2 := c.Db.Get(&weapon_raw, c.Db.Rebind("SELECT * FROM weapons WHERE name='" + weapon + "'")) err2 := c.Db.Get(&weapon_raw, c.Db.Rebind("SELECT * FROM weapons WHERE name='" + weapon + "'"))
if err2 != nil { if err2 != nil {
log.Println(err2) log.Println(err2)
@ -234,7 +234,7 @@ func (p *Parsers) ParseProfile(update tgbotapi.Update, player_raw dbmappings.Pla
} }
} }
profile_raw := dbmappings.Profiles{} profile_raw := dbmapping.Profile{}
profile_raw.Player_id = player_raw.Id profile_raw.Player_id = player_raw.Id
profile_raw.Nickname = nickname profile_raw.Nickname = nickname
profile_raw.TelegramNickname = telegram_nickname profile_raw.TelegramNickname = telegram_nickname

View File

@ -5,15 +5,11 @@ package router
import ( import (
// stdlib // stdlib
"fmt"
"log" "log"
"regexp" "regexp"
"strings" "strings"
"time"
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local
"../dbmappings"
) )
type Router struct {} type Router struct {}
@ -23,31 +19,12 @@ type Router struct {}
// If command doesn't exist, it's "fail" // If command doesn't exist, it's "fail"
func (r *Router) RouteRequest(update tgbotapi.Update) string { func (r *Router) RouteRequest(update tgbotapi.Update) string {
text := update.Message.Text text := update.Message.Text
user_id := update.Message.From.ID
player_raw := dbmappings.Players{} player_raw, ok := c.Getters.GetOrCreatePlayer(update.Message.From.ID)
err := c.Db.Get(&player_raw, c.Db.Rebind("SELECT * FROM players WHERE telegram_id=?"), user_id) if !ok {
if err != nil { // Silently fail
log.Printf("Message user not found in database.")
log.Printf(err.Error())
// Create "nobody" user
player_raw.Telegram_id = user_id
player_raw.League_id = 0
player_raw.Squad_id = 0
player_raw.Status = "nobody"
player_raw.Created_at = time.Now().UTC()
player_raw.Updated_at = time.Now().UTC()
_, erradd := c.Db.NamedExec("INSERT INTO players VALUES(NULL, :telegram_id, :league_id, :squad_id, :status, :created_at, :updated_at)", &player_raw)
if erradd != nil {
log.Printf(erradd.Error())
return "fail" return "fail"
} }
} else {
log.Printf("Message user found in database.")
}
fmt.Println(player_raw)
// Regular expressions // Regular expressions
var durakMsg = regexp.MustCompile("(Д|д)(У|у)(Р|р)(А|а|Е|е|О|о)") var durakMsg = regexp.MustCompile("(Д|д)(У|у)(Р|р)(А|а|Е|е|О|о)")

View File

@ -17,3 +17,13 @@ func (t *Talkers) AnyMessageUnauthorized(update tgbotapi.Update) {
c.Bot.Send(msg) c.Bot.Send(msg)
} }
func (t *Talkers) GetterError(update tgbotapi.Update) {
error_message := "Ой, внутренняя ошибка в боте :(\n\n"
error_message += "Напиши @fat0troll, приложив форвардом последние сообщения до этого.\n"
msg := tgbotapi.NewMessage(update.Message.Chat.ID, error_message)
msg.ParseMode = "Markdown"
c.Bot.Send(msg)
}

View File

@ -7,7 +7,7 @@ import (
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local // local
"../dbmappings" "../dbmapping"
) )
func (t *Talkers) HelloMessageUnauthorized(update tgbotapi.Update) { func (t *Talkers) HelloMessageUnauthorized(update tgbotapi.Update) {
@ -21,7 +21,7 @@ func (t *Talkers) HelloMessageUnauthorized(update tgbotapi.Update) {
c.Bot.Send(msg) c.Bot.Send(msg)
} }
func (t *Talkers) HelloMessageAuthorized(update tgbotapi.Update, player_raw dbmappings.Players) { func (t *Talkers) HelloMessageAuthorized(update tgbotapi.Update, player_raw dbmapping.Player) {
hello_message := "*Бот Инстинкта приветствует тебя. Снова.*\n\n" hello_message := "*Бот Инстинкта приветствует тебя. Снова.*\n\n"
hello_message += "Привет, " + update.Message.From.FirstName + " " + update.Message.From.LastName + "!\n" hello_message += "Привет, " + update.Message.From.FirstName + " " + update.Message.From.LastName + "!\n"
hello_message += "Последнее обновление информации о тебе: " + player_raw.Updated_at.Format("02.01.2006 15:04:05 -0700") hello_message += "Последнее обновление информации о тебе: " + player_raw.Updated_at.Format("02.01.2006 15:04:05 -0700")

View File

@ -15,7 +15,7 @@ func (t *Talkers) HelpMessage(update tgbotapi.Update) {
help_message += "Текущая версия: *" + config.VERSION + "*\n\n" help_message += "Текущая версия: *" + config.VERSION + "*\n\n"
help_message += "Список команд:\n\n" help_message += "Список команд:\n\n"
help_message += "+ /me посмотреть свой сохраненный профиль в боте\n" help_message += "+ /me посмотреть свой сохраненный профиль в боте\n"
help_message += "+ /pokedex получить список известных боту покемемов\n" help_message += "+ /pokedeks получить список известных боту покемемов\n"
help_message += "+ /help выводит данное сообщение\n" help_message += "+ /help выводит данное сообщение\n"
help_message += "\n\n" help_message += "\n\n"
help_message += "Связаться с автором: @fat0troll\n" help_message += "Связаться с автором: @fat0troll\n"

View File

@ -5,72 +5,83 @@ package talkers
import ( import (
// stdlib // stdlib
"log"
"strings" "strings"
"strconv" "strconv"
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local // local
"../dbmappings" "../dbmapping"
) )
type PokememeFull struct { // Internal functions
Pokememe dbmappings.Pokememes
Elements []dbmappings.Elements func (t *Talkers) pokememesListing(update tgbotapi.Update, page int, pokememes_full []dbmapping.PokememeFull) {
Locations []dbmappings.Locations message := "*Известные боту покемемы*\n"
message += "Список отсортирован по грейду и алфавиту.\n"
message += "Покедекс: " + strconv.Itoa(len(pokememes_full)) + " / 206\n"
message += "Отображаем покемемов с " + strconv.Itoa(((page - 1)*50)+1) + " по " + strconv.Itoa(page*50) + "\n"
if len(pokememes_full) > page*50 {
message += "Переход на следующую страницу: /pokedeks" + strconv.Itoa(page + 1)
}
if page > 1 {
message += "\nПереход на предыдущую страницу: /pokedeks" + strconv.Itoa(page - 1)
}
message += "\n\n"
for i := range(pokememes_full) {
if (i + 1 > 50*(page - 1)) && (i + 1 < (50*page) + 1) {
pk := pokememes_full[i].Pokememe
pk_e := pokememes_full[i].Elements
message += strconv.Itoa(i + 1) + ". " + strconv.Itoa(pk.Grade)
message += "⃣ *" + pk.Name
message += "* (" + c.Parsers.ReturnPoints(pk.HP) + "-" + c.Parsers.ReturnPoints(pk.MP) + ") ⚔️ *"
message += c.Parsers.ReturnPoints(pk.Attack) + "* \\["
for j := range(pk_e) {
message += pk_e[j].Symbol
}
message += "] " + c.Parsers.ReturnPoints(pk.Price) + "$ /pk" + strconv.Itoa(pk.Id)
message += "\n"
}
} }
func (t *Talkers) PokememeInfo(update tgbotapi.Update, player_raw dbmappings.Players) string { msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
pokememe_number := strings.Replace(update.Message.Text, "/pk", "", 1) msg.ParseMode = "Markdown"
var calculate_possibilites bool = false
profile_raw := dbmappings.Profiles{} c.Bot.Send(msg)
err := c.Db.Get(&profile_raw, c.Db.Rebind("SELECT * FROM profiles WHERE player_id=? ORDER BY created_at DESC LIMIT 1"), player_raw.Id)
if err != nil { }
log.Println(err)
// External functions
func (t *Talkers) PokememesList(update tgbotapi.Update, page int) {
pokememes_full, ok := c.Getters.GetPokememes()
if !ok {
t.GetterError(update)
} else { } else {
calculate_possibilites = true t.pokememesListing(update, page, pokememes_full)
}
} }
// Building pokememe func (t *Talkers) PokememeInfo(update tgbotapi.Update, player_raw dbmapping.Player) string {
pk := dbmappings.Pokememes{} pokememe_number := strings.Replace(update.Message.Text, "/pk", "", 1)
// Checking if pokememe exists in database var calculate_possibilites bool = true
err = c.Db.Get(&pk, c.Db.Rebind("SELECT * FROM pokememes WHERE id='" + pokememe_number + "'")) profile_raw, ok := c.Getters.GetProfile(player_raw.Id)
if err != nil { if !ok {
log.Println(err) calculate_possibilites = false
}
pokememe, ok := c.Getters.GetPokememeByID(pokememe_number)
if !ok {
return "fail" return "fail"
} }
elements := []dbmappings.Elements{} pk := pokememe.Pokememe
err = c.Db.Select(&elements, "SELECT * FROM elements");
if err != nil {
log.Println(err)
}
locations := []dbmappings.Locations{}
err = c.Db.Select(&locations, "SELECT * FROM locations");
if err != nil {
log.Println(err)
}
pokememes_elements := []dbmappings.PokememesElements{}
err = c.Db.Select(&pokememes_elements, "SELECT * FROM pokememes_elements WHERE pokememe_id='" + pokememe_number + "'");
if err != nil {
log.Println(err)
}
pokememes_locations := []dbmappings.PokememesLocations{}
err = c.Db.Select(&pokememes_locations, "SELECT * FROM pokememes_locations WHERE pokememe_id='" + pokememe_number + "'");
if err != nil {
log.Println(err)
}
message := strconv.Itoa(pk.Grade) + "⃣ *" + pk.Name + "*\n" message := strconv.Itoa(pk.Grade) + "⃣ *" + pk.Name + "*\n"
message += pk.Description + "\n\n" message += pk.Description + "\n\n"
message += "Элементы:" message += "Элементы:"
for i := range(pokememes_elements) { for i := range(pokememe.Elements) {
for j := range(elements) { message += " " + pokememe.Elements[i].Symbol
if pokememes_elements[i].Element_id == elements[j].Id {
message += " " + elements[j].Symbol
}
}
} }
message += "\n⚔ Атака: *" + c.Parsers.ReturnPoints(pk.Attack) message += "\n⚔ Атака: *" + c.Parsers.ReturnPoints(pk.Attack)
message += "*\n❤ HP: *" + c.Parsers.ReturnPoints(pk.HP) message += "*\n❤ HP: *" + c.Parsers.ReturnPoints(pk.HP)
@ -88,24 +99,21 @@ func (t *Talkers) PokememeInfo(update tgbotapi.Update, player_raw dbmappings.Pla
message += "Нельзя" message += "Нельзя"
} }
message += "*\nОбитает:" message += "*\nОбитает:"
for i := range(pokememes_locations) { for i := range(pokememe.Locations) {
for j := range(locations) { message += " *" + pokememe.Locations[i].Name + "*"
if pokememes_locations[i].Location_id == locations[j].Id { if (i + 1) < len(pokememe.Locations) {
message += " *" + locations[j].Name + "*"
if (i + 1) < len(pokememes_locations) {
message += "," message += ","
} }
} }
}
}
if calculate_possibilites { if calculate_possibilites {
if (pk.Grade < profile_raw.Level_id + 2) || (pk.Grade > profile_raw.Level_id - 3) {
message += "\nВероятность поимки:" message += "\nВероятность поимки:"
for i := range(pokememes_locations) { for i := range(pokememe.Locations) {
for j := range(locations) { percentile, pokeballs := c.Getters.PossibilityRequiredPokeballs(pokememe.Locations[i].Id, pk.Grade, profile_raw.Level_id)
if pokememes_locations[i].Location_id == locations[j].Id { message += "\n" + pokememe.Locations[i].Name + " "
message += "\n" + locations[j].Name + " " + strconv.Itoa(c.Getters.PossibilityRequiredPokeballs(locations[j].Id, pk.Grade, profile_raw.Level_id)) + "⭕" message += strconv.FormatFloat(percentile, 'f', 2, 64) + "% или "
} message += strconv.Itoa(pokeballs) + "⭕"
} }
} }
} }
@ -114,16 +122,12 @@ func (t *Talkers) PokememeInfo(update tgbotapi.Update, player_raw dbmappings.Pla
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message) msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
keyboard := tgbotapi.InlineKeyboardMarkup{} keyboard := tgbotapi.InlineKeyboardMarkup{}
for i := range(pokememes_locations) { for i := range(pokememe.Locations) {
for j := range(locations) {
if pokememes_locations[i].Location_id == locations[j].Id {
var row []tgbotapi.InlineKeyboardButton var row []tgbotapi.InlineKeyboardButton
btn := tgbotapi.NewInlineKeyboardButtonSwitch(locations[j].Symbol + locations[j].Name, locations[j].Symbol + locations[j].Name) btn := tgbotapi.NewInlineKeyboardButtonSwitch(pokememe.Locations[i].Symbol + pokememe.Locations[i].Name, pokememe.Locations[i].Symbol + pokememe.Locations[i].Name)
row = append(row, btn) row = append(row, btn)
keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, row) keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, row)
} }
}
}
msg.ReplyMarkup = keyboard msg.ReplyMarkup = keyboard
msg.ParseMode = "Markdown" msg.ParseMode = "Markdown"
@ -132,101 +136,3 @@ func (t *Talkers) PokememeInfo(update tgbotapi.Update, player_raw dbmappings.Pla
return "ok" return "ok"
} }
func (t *Talkers) PokememesList(update tgbotapi.Update, page int) {
pokememes := []dbmappings.Pokememes{}
err := c.Db.Select(&pokememes, "SELECT * FROM pokememes");
if err != nil {
log.Println(err)
}
pokememes_limited := []dbmappings.Pokememes{}
err = c.Db.Select(&pokememes_limited, "SELECT * FROM pokememes ORDER BY grade asc, name asc LIMIT 50 OFFSET " + strconv.Itoa(50*(page-1)));
if err != nil {
log.Println(err)
}
elements := []dbmappings.Elements{}
err = c.Db.Select(&elements, "SELECT * FROM elements");
if err != nil {
log.Println(err)
}
locations := []dbmappings.Locations{}
err = c.Db.Select(&locations, "SELECT * FROM locations");
if err != nil {
log.Println(err)
}
pokememes_elements := []dbmappings.PokememesElements{}
err = c.Db.Select(&pokememes_elements, "SELECT * FROM pokememes_elements");
if err != nil {
log.Println(err)
}
pokememes_locations := []dbmappings.PokememesLocations{}
err = c.Db.Select(&pokememes_locations, "SELECT * FROM pokememes_locations");
if err != nil {
log.Println(err)
}
pokememes_full := []PokememeFull{}
for i := range(pokememes_limited) {
full_pokememe := PokememeFull{}
elements_listed := []dbmappings.Elements{}
locations_listed := []dbmappings.Locations{}
for j := range(pokememes_locations) {
if pokememes_locations[j].Pokememe_id == pokememes_limited[i].Id {
for l := range(locations) {
if pokememes_locations[j].Location_id == locations[l].Id {
locations_listed = append(locations_listed, locations[l])
}
}
}
}
for k := range(pokememes_elements) {
if pokememes_elements[k].Pokememe_id == pokememes_limited[i].Id {
for e := range(elements) {
if pokememes_elements[k].Element_id == elements[e].Id {
elements_listed = append(elements_listed, elements[e])
}
}
}
}
full_pokememe.Pokememe = pokememes_limited[i]
full_pokememe.Elements = elements_listed
full_pokememe.Locations = locations_listed
pokememes_full = append(pokememes_full, full_pokememe)
}
message := "*Известные боту покемемы*\n"
message += "Список отсортирован по грейду и алфавиту.\n"
message += "Покедекс: " + strconv.Itoa(len(pokememes)) + " / 206\n"
message += "Отображаем покемемов с " + strconv.Itoa(((page - 1)*50)+1) + " по " + strconv.Itoa(page*50) + "\n"
if len(pokememes) > page*50 {
message += "Переход на следующую страницу: /pokedeks" + strconv.Itoa(page + 1)
}
if page > 1 {
message += "\nПереход на предыдущую страницу: /pokedeks" + strconv.Itoa(page - 1)
}
message += "\n\n"
for i := range(pokememes_full) {
pk := pokememes_full[i].Pokememe
pk_e := pokememes_full[i].Elements
message += strconv.Itoa(i + 1 + (50*(page-1))) + ". " + strconv.Itoa(pk.Grade)
message += "⃣ *" + pk.Name
message += "* (" + c.Parsers.ReturnPoints(pk.HP) + "-" + c.Parsers.ReturnPoints(pk.MP) + ") ⚔️ *"
message += c.Parsers.ReturnPoints(pk.Attack) + "* \\["
for j := range(pk_e) {
message += pk_e[j].Symbol
}
message += "] " + c.Parsers.ReturnPoints(pk.Price) + "$ /pk" + strconv.Itoa(pk.Id)
message += "\n"
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
msg.ParseMode = "Markdown"
c.Bot.Send(msg)
}

View File

@ -10,40 +10,38 @@ import (
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local // local
"../dbmappings" "../dbmapping"
) )
func (t *Talkers) ProfileMessage(update tgbotapi.Update, player_raw dbmappings.Players) string { func (t *Talkers) ProfileMessage(update tgbotapi.Update, player_raw dbmapping.Player) string {
profile_raw := dbmappings.Profiles{} profile_raw, ok := c.Getters.GetProfile(player_raw.Id)
err := c.Db.Get(&profile_raw, c.Db.Rebind("SELECT * FROM profiles WHERE player_id=? ORDER BY created_at DESC LIMIT 1"), player_raw.Id) if !ok {
if err != nil {
log.Println(err)
c.Talkers.AnyMessageUnauthorized(update) c.Talkers.AnyMessageUnauthorized(update)
return "fail" return "fail"
} }
league := dbmappings.Leagues{} league := dbmapping.League{}
err = c.Db.Get(&league, c.Db.Rebind("SELECT * FROM leagues WHERE id=?"), player_raw.League_id) err := c.Db.Get(&league, c.Db.Rebind("SELECT * FROM leagues WHERE id=?"), player_raw.League_id)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
level := dbmappings.Levels{} level := dbmapping.Level{}
err = c.Db.Get(&level, c.Db.Rebind("SELECT * FROM levels WHERE id=?"), profile_raw.Level_id) err = c.Db.Get(&level, c.Db.Rebind("SELECT * FROM levels WHERE id=?"), profile_raw.Level_id)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
weapon := dbmappings.Weapons{} weapon := dbmapping.Weapon{}
if profile_raw.Weapon_id != 0 { if profile_raw.Weapon_id != 0 {
err = c.Db.Get(&weapon, c.Db.Rebind("SELECT * FROM weapons WHERE id=?"), profile_raw.Weapon_id) err = c.Db.Get(&weapon, c.Db.Rebind("SELECT * FROM weapons WHERE id=?"), profile_raw.Weapon_id)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
} }
p_pk := []dbmappings.ProfilesPokememes{} p_pk := []dbmapping.ProfilePokememe{}
err = c.Db.Select(&p_pk, c.Db.Rebind("SELECT * FROM profiles_pokememes WHERE profile_id=?"), profile_raw.Id) err = c.Db.Select(&p_pk, c.Db.Rebind("SELECT * FROM profiles_pokememes WHERE profile_id=?"), profile_raw.Id)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
pokememes := []dbmappings.Pokememes{} pokememes := []dbmapping.Pokememe{}
err = c.Db.Select(&pokememes, c.Db.Rebind("SELECT * FROM pokememes")) err = c.Db.Select(&pokememes, c.Db.Rebind("SELECT * FROM pokememes"))
if err != nil { if err != nil {
log.Println(err) log.Println(err)

View File

@ -7,17 +7,17 @@ import (
// 3rd party // 3rd party
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
// local // local
"../../dbmappings" "../../dbmapping"
) )
type TalkersInterface interface { type TalkersInterface interface {
Init() Init()
// Commands // Commands
HelloMessageUnauthorized(update tgbotapi.Update) HelloMessageUnauthorized(update tgbotapi.Update)
HelloMessageAuthorized(update tgbotapi.Update, player_raw dbmappings.Players) HelloMessageAuthorized(update tgbotapi.Update, player_raw dbmapping.Player)
HelpMessage(update tgbotapi.Update) HelpMessage(update tgbotapi.Update)
PokememesList(update tgbotapi.Update, page int) PokememesList(update tgbotapi.Update, page int)
PokememeInfo(update tgbotapi.Update, player_raw dbmappings.Players) string PokememeInfo(update tgbotapi.Update, player_raw dbmapping.Player) string
// Returns // Returns
PokememeAddSuccessMessage(update tgbotapi.Update) PokememeAddSuccessMessage(update tgbotapi.Update)
@ -25,10 +25,11 @@ type TalkersInterface interface {
PokememeAddFailureMessage(update tgbotapi.Update) PokememeAddFailureMessage(update tgbotapi.Update)
ProfileAddSuccessMessage(update tgbotapi.Update) ProfileAddSuccessMessage(update tgbotapi.Update)
ProfileAddFailureMessage(update tgbotapi.Update) ProfileAddFailureMessage(update tgbotapi.Update)
ProfileMessage(update tgbotapi.Update, player_raw dbmappings.Players) string ProfileMessage(update tgbotapi.Update, player_raw dbmapping.Player) string
// Errors // Errors
AnyMessageUnauthorized(update tgbotapi.Update) AnyMessageUnauthorized(update tgbotapi.Update)
GetterError(update tgbotapi.Update)
// Easter eggs // Easter eggs
DurakMessage(update tgbotapi.Update) DurakMessage(update tgbotapi.Update)