Add tournament reports storage and karma changing function
This commit is contained in:
parent
0a5361ee09
commit
07c24b8822
@ -1,4 +1,7 @@
|
|||||||
# i2_bot: бот лиги Инстинкт игры @PokememBroBot
|
# i2_bot: бот лиги Инстинкт игры @PokememBroBot
|
||||||
|
|
||||||
|
[![Go Report Card](https://goreportcard.com/badge/source.wtfteam.pro/i2_bot/i2_bot)](https://goreportcard.com/report/source.wtfteam.pro/i2_bot/i2_bot)
|
||||||
|
|
||||||
Для запуска нужен правильный ``config.yml``.
|
Для запуска нужен правильный ``config.yml``.
|
||||||
Управление зависимостями осуществляет [dep](https://github.com/golang/dep).
|
Управление зависимостями осуществляет [dep](https://github.com/golang/dep).
|
||||||
|
|
||||||
|
@ -34,6 +34,7 @@ type DataCacheInterface interface {
|
|||||||
GetUserRolesInSquads(userID int) []dbmapping.SquadPlayerFull
|
GetUserRolesInSquads(userID int) []dbmapping.SquadPlayerFull
|
||||||
|
|
||||||
AddPlayer(player *dbmapping.Player) (int, error)
|
AddPlayer(player *dbmapping.Player) (int, error)
|
||||||
|
ChangePlayerKarma(addition int, playerID int) (*dbmapping.Player, error)
|
||||||
GetOrCreatePlayerByTelegramID(telegramID int) (*dbmapping.Player, error)
|
GetOrCreatePlayerByTelegramID(telegramID int) (*dbmapping.Player, error)
|
||||||
GetPlayerByID(playerID int) (*dbmapping.Player, error)
|
GetPlayerByID(playerID int) (*dbmapping.Player, error)
|
||||||
GetPlayerByTelegramID(telegramID int) (*dbmapping.Player, error)
|
GetPlayerByTelegramID(telegramID int) (*dbmapping.Player, error)
|
||||||
@ -45,6 +46,8 @@ type DataCacheInterface interface {
|
|||||||
GetProfileByID(profileID int) (*dbmapping.Profile, error)
|
GetProfileByID(profileID int) (*dbmapping.Profile, error)
|
||||||
GetProfileByPlayerID(playerID int) (*dbmapping.Profile, error)
|
GetProfileByPlayerID(playerID int) (*dbmapping.Profile, error)
|
||||||
|
|
||||||
|
AddTournamentReport(tournamentNumber int, playerID int, target string) (int, error)
|
||||||
|
|
||||||
GetElementByID(elementID int) (*datamapping.Element, error)
|
GetElementByID(elementID int) (*datamapping.Element, error)
|
||||||
FindElementIDBySymbol(symbol string) (int, error)
|
FindElementIDBySymbol(symbol string) (int, error)
|
||||||
|
|
||||||
|
@ -29,6 +29,10 @@ type DataCache struct {
|
|||||||
// Note: int in this array for player ID, not for profile ID
|
// Note: int in this array for player ID, not for profile ID
|
||||||
currentProfiles map[int]*dbmapping.Profile
|
currentProfiles map[int]*dbmapping.Profile
|
||||||
currentProfilesMutex sync.Mutex
|
currentProfilesMutex sync.Mutex
|
||||||
|
// Tournament reports
|
||||||
|
tournamentReports map[int]*dbmapping.TournamentReport
|
||||||
|
tournamentReportsByTournamentAndPlayer map[int]map[int]*dbmapping.TournamentReport
|
||||||
|
tournamentReportsMutex sync.Mutex
|
||||||
|
|
||||||
// Chats
|
// Chats
|
||||||
chats map[int]*dbmapping.Chat
|
chats map[int]*dbmapping.Chat
|
||||||
@ -84,6 +88,8 @@ func (dc *DataCache) Init() {
|
|||||||
dc.loadPlayers()
|
dc.loadPlayers()
|
||||||
dc.initProfiles()
|
dc.initProfiles()
|
||||||
dc.loadProfiles()
|
dc.loadProfiles()
|
||||||
|
dc.initTournamentReports()
|
||||||
|
dc.loadTournamentReports()
|
||||||
dc.initChats()
|
dc.initChats()
|
||||||
dc.loadChats()
|
dc.loadChats()
|
||||||
dc.initSquads()
|
dc.initSquads()
|
||||||
|
@ -58,6 +58,25 @@ func (dc *DataCache) AddPlayer(player *dbmapping.Player) (int, error) {
|
|||||||
return insertedPlayer.ID, nil
|
return insertedPlayer.ID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ChangePlayerKarma changes karma value for user
|
||||||
|
func (dc *DataCache) ChangePlayerKarma(addition int, playerID int) (*dbmapping.Player, error) {
|
||||||
|
if dc.players[playerID] == nil {
|
||||||
|
return nil, errors.New("There is no player with ID = " + strconv.Itoa(playerID))
|
||||||
|
}
|
||||||
|
|
||||||
|
dc.playersMutex.Lock()
|
||||||
|
dc.players[playerID].Karma += addition
|
||||||
|
dc.players[playerID].UpdatedAt = time.Now().UTC()
|
||||||
|
dc.playersMutex.Unlock()
|
||||||
|
|
||||||
|
_, err := c.Db.NamedExec("UPDATE `players` SET karma=:karma, updated_at=:updated_at WHERE id=:id", dc.players[playerID])
|
||||||
|
if err != nil {
|
||||||
|
c.Log.Error(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
return dc.players[playerID], nil
|
||||||
|
}
|
||||||
|
|
||||||
// GetOrCreatePlayerByTelegramID finds user by Telegram ID and creates one if not exist
|
// GetOrCreatePlayerByTelegramID finds user by Telegram ID and creates one if not exist
|
||||||
func (dc *DataCache) GetOrCreatePlayerByTelegramID(telegramID int) (*dbmapping.Player, error) {
|
func (dc *DataCache) GetOrCreatePlayerByTelegramID(telegramID int) (*dbmapping.Player, error) {
|
||||||
c.Log.Info("DataCache: Getting player with Telegram ID=", telegramID)
|
c.Log.Info("DataCache: Getting player with Telegram ID=", telegramID)
|
||||||
|
95
lib/datacache/tournament_reports.go
Normal file
95
lib/datacache/tournament_reports.go
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
// i2_bot – Instinct PokememBro Bot
|
||||||
|
// Copyright (c) 2018 Vladimir "fat0troll" Hodakov
|
||||||
|
|
||||||
|
package datacache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (dc *DataCache) initTournamentReports() {
|
||||||
|
c.Log.Info("Initializing Tournament Reports storage...")
|
||||||
|
dc.tournamentReports = make(map[int]*dbmapping.TournamentReport)
|
||||||
|
dc.tournamentReportsByTournamentAndPlayer = make(map[int]map[int]*dbmapping.TournamentReport)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dc *DataCache) loadTournamentReports() {
|
||||||
|
c.Log.Info("Load current TournamentReports data from database to DataCache...")
|
||||||
|
tournamentReports := []dbmapping.TournamentReport{}
|
||||||
|
err := c.Db.Select(&tournamentReports, "SELECT * FROM tournament_reports")
|
||||||
|
if err != nil {
|
||||||
|
// This is critical error and we need to stop immediately!
|
||||||
|
c.Log.Fatal(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
dc.tournamentReportsMutex.Lock()
|
||||||
|
for i := range tournamentReports {
|
||||||
|
dc.tournamentReports[tournamentReports[i].ID] = &tournamentReports[i]
|
||||||
|
if dc.tournamentReportsByTournamentAndPlayer[tournamentReports[i].TournamentNumber] == nil {
|
||||||
|
dc.tournamentReportsByTournamentAndPlayer[tournamentReports[i].TournamentNumber] = make(map[int]*dbmapping.TournamentReport)
|
||||||
|
}
|
||||||
|
|
||||||
|
dc.tournamentReportsByTournamentAndPlayer[tournamentReports[i].TournamentNumber][tournamentReports[i].PlayerID] = &tournamentReports[i]
|
||||||
|
}
|
||||||
|
c.Log.Info("Loaded tournament reports in DataCache: " + strconv.Itoa(len(dc.tournamentReports)))
|
||||||
|
dc.tournamentReportsMutex.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// External functions
|
||||||
|
|
||||||
|
// AddTournamentReport creates new tournament report in database
|
||||||
|
func (dc *DataCache) AddTournamentReport(tournamentNumber int, playerID int, target string) (int, error) {
|
||||||
|
if tournamentNumber < 3551 {
|
||||||
|
return 0, errors.New("Can't save tournament from the very past")
|
||||||
|
}
|
||||||
|
if dc.players[playerID] == nil {
|
||||||
|
return 0, errors.New("There is no player with ID = " + strconv.Itoa(playerID))
|
||||||
|
}
|
||||||
|
if target != "O" && target != "M" && target != "A" {
|
||||||
|
return 0, errors.New("Malformed report")
|
||||||
|
}
|
||||||
|
|
||||||
|
dc.tournamentReportsMutex.Lock()
|
||||||
|
if dc.tournamentReportsByTournamentAndPlayer[tournamentNumber] != nil {
|
||||||
|
if dc.tournamentReportsByTournamentAndPlayer[tournamentNumber][playerID] != nil {
|
||||||
|
dc.tournamentReportsMutex.Unlock()
|
||||||
|
return dc.tournamentReportsByTournamentAndPlayer[tournamentNumber][playerID].ID, errors.New("There is already this report in database")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
dc.tournamentReportsByTournamentAndPlayer[tournamentNumber] = make(map[int]*dbmapping.TournamentReport)
|
||||||
|
}
|
||||||
|
dc.tournamentReportsMutex.Unlock()
|
||||||
|
|
||||||
|
report := dbmapping.TournamentReport{}
|
||||||
|
report.PlayerID = playerID
|
||||||
|
report.TournamentNumber = tournamentNumber
|
||||||
|
report.Target = target
|
||||||
|
report.CreatedAt = time.Now().UTC()
|
||||||
|
|
||||||
|
c.Log.Debug("Saving report...")
|
||||||
|
_, err := c.Db.NamedExec("INSERT INTO tournament_reports VALUES(NULL, :player_id, :tournament_number, :target, :created_at)", &tournamentNumber)
|
||||||
|
if err != nil {
|
||||||
|
c.Log.Error(err.Error())
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
newReport := dbmapping.TournamentReport{}
|
||||||
|
err = c.Db.Get(&newReport, "SELECT * FROM tournament_reports WHERE player_id=? AND tournament_number=?", report.PlayerID, report.TournamentNumber)
|
||||||
|
if err != nil {
|
||||||
|
c.Log.Error(err.Error())
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dc.tournamentReportsMutex.Lock()
|
||||||
|
dc.tournamentReports[newReport.ID] = &newReport
|
||||||
|
dc.tournamentReportsByTournamentAndPlayer[tournamentNumber][playerID] = &newReport
|
||||||
|
dc.tournamentReportsMutex.Unlock()
|
||||||
|
|
||||||
|
dc.ChangePlayerKarma(3, newReport.PlayerID)
|
||||||
|
|
||||||
|
return newReport.ID, nil
|
||||||
|
}
|
@ -7,7 +7,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Alarm is a struct, which represents `alarms` table item in databse.
|
// Alarm is a struct, which represents `alarms` table item in database.
|
||||||
type Alarm struct {
|
type Alarm struct {
|
||||||
ID int `db:"id"`
|
ID int `db:"id"`
|
||||||
PlayerID int `db:"player_id"`
|
PlayerID int `db:"player_id"`
|
||||||
|
17
lib/dbmapping/tournament_reports.go
Normal file
17
lib/dbmapping/tournament_reports.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// i2_bot – Instinct PokememBro Bot
|
||||||
|
// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov
|
||||||
|
|
||||||
|
package dbmapping
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TournamentReport is a struct, which represents `tournament_reports` table item in database.
|
||||||
|
type TournamentReport struct {
|
||||||
|
ID int `db:"id"`
|
||||||
|
PlayerID int `db:"player_id"`
|
||||||
|
TournamentNumber int `db:"tournament_number"`
|
||||||
|
Target string `db:"target"`
|
||||||
|
CreatedAt time.Time `db:"created_at"`
|
||||||
|
}
|
39
lib/migrations/36_create_tournament_reports.go
Normal file
39
lib/migrations/36_create_tournament_reports.go
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
// i2_bot – Instinct PokememBro Bot
|
||||||
|
// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov
|
||||||
|
|
||||||
|
package migrations
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateTournamentReportsUp creates `tournament_reports` table
|
||||||
|
func CreateTournamentReportsUp(tx *sql.Tx) error {
|
||||||
|
request := "CREATE TABLE `tournament_reports` ("
|
||||||
|
request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID рапорта',"
|
||||||
|
request += "`player_id` int(11) NOT NULL COMMENT 'Игрок, который сходил на турнир',"
|
||||||
|
request += "`tournament_number` int(11) NOT NULL COMMENT 'Номер турнира в игре',"
|
||||||
|
request += "`target` varchar(191) NOT NULL COMMENT 'Цель атаки',"
|
||||||
|
request += "`created_at` datetime NOT NULL COMMENT 'Добавлен в базу',"
|
||||||
|
request += "PRIMARY KEY (`id`),"
|
||||||
|
request += "UNIQUE KEY `id` (`id`),"
|
||||||
|
request += "KEY `tournament_reports_player_id` (`player_id`),"
|
||||||
|
request += "KEY `tournament_repots_tournament_number` (`tournament_number`)"
|
||||||
|
request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Репорты результата Турнира лиг'"
|
||||||
|
_, err := tx.Exec(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateTournamentReportsDown drops `tournament_reports` table
|
||||||
|
func CreateTournamentReportsDown(tx *sql.Tx) error {
|
||||||
|
_, err := tx.Exec("DROP TABLE `tournament_reports`")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
@ -46,6 +46,7 @@ func (m *Migrations) Init() {
|
|||||||
goose.AddNamedMigration("33_delete_datamapped_tables.go", DeleteDataMappedTablesUp, DeleteDataMappedTablesDown)
|
goose.AddNamedMigration("33_delete_datamapped_tables.go", DeleteDataMappedTablesUp, DeleteDataMappedTablesDown)
|
||||||
goose.AddNamedMigration("34_delete_pokememes_tables.go", DeletePokememesTablesUp, DeletePokememesTablesDown)
|
goose.AddNamedMigration("34_delete_pokememes_tables.go", DeletePokememesTablesUp, DeletePokememesTablesDown)
|
||||||
goose.AddNamedMigration("35_add_karma_to_players.go", AddKarmaToPlayersUp, AddKarmaToPlayersDown)
|
goose.AddNamedMigration("35_add_karma_to_players.go", AddKarmaToPlayersUp, AddKarmaToPlayersDown)
|
||||||
|
goose.AddNamedMigration("36_create_tournament_reports.go", CreateTournamentReportsUp, CreateTournamentReportsDown)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Migrate migrates database to current version
|
// Migrate migrates database to current version
|
||||||
|
@ -32,7 +32,9 @@ func (w *Welcomer) groupWelcomeUser(update *tgbotapi.Update, newUser *tgbotapi.U
|
|||||||
w.alertUserWithoutProfile(update, newUser)
|
w.alertUserWithoutProfile(update, newUser)
|
||||||
}
|
}
|
||||||
|
|
||||||
message += "Приветствую тебя, гость лиги Инстинкт! Для регистрации в Лиге и получения доступа к ее ресурсам и чатам напиши скорее мне, @i2\\_bot, в личку и скинь свою статистику.\n\nГайд для игроков Инстинкта: http://telegra.ph/Dobro-pozhalovat-v-Instinkt-11-22"
|
message += "Приветствую тебя, гость лиги Инстинкт! Для регистрации в Лиге и получения доступа к ее ресурсам и чатам напиши скорее мне, @i2\\_bot, в личку и скинь свою статистику.\n\n"
|
||||||
|
|
||||||
|
message += "Алгоритм, как зарегистрироваться:\n\n1) Нажимаешь кнопку ниже, и выбираешь @PokememBroBot как цель для сообщения\n2) В ответ получаешь длинное сообщение-статистику.\n3) Полученное сообщение форвардишь в @i2\\_bot (не забудь заранее нажать там /start!)\n4) Готово, вы восхитительны."
|
||||||
|
|
||||||
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
|
msg := tgbotapi.NewMessage(update.Message.Chat.ID, message)
|
||||||
msg.ParseMode = "Markdown"
|
msg.ParseMode = "Markdown"
|
||||||
|
Reference in New Issue
Block a user