rename ShowSelfConquers -> ShowInternals | send embed in new goroutine | make one big request to fetch ennoblements instead of separate requests

This commit is contained in:
Dawid Wysokiński 2020-07-27 17:54:51 +02:00 committed by Kichiyaki
parent 190d07249d
commit f1d3274e10
11 changed files with 64 additions and 43 deletions

View File

@ -40,5 +40,6 @@ func Attach(c *cron.Cron, cfg Config) {
h.checkBotServers()
h.deleteClosedTribalWarsServers()
h.updateBotStatus()
h.checkEnnoblements()
}()
}

View File

@ -27,12 +27,12 @@ func (e ennoblements) getLostVillagesByTribe(tribeID int) ennoblements {
return filtered
}
func (e ennoblements) getConqueredVillagesByTribe(tribeID int, showSelfConquers bool) ennoblements {
func (e ennoblements) getConqueredVillagesByTribe(tribeID int, showInternals bool) ennoblements {
filtered := ennoblements{}
for _, ennoblement := range e {
if isPlayerTribeNil(ennoblement.NewOwner) ||
ennoblement.NewOwner.Tribe.ID != tribeID ||
(!showSelfConquers && !isPlayerTribeNil(ennoblement.OldOwner) && ennoblement.OldOwner.Tribe.ID == tribeID) {
(!showInternals && !isPlayerTribeNil(ennoblement.OldOwner) && ennoblement.OldOwner.Tribe.ID == tribeID) {
continue
}
filtered = append(filtered, ennoblement)

View File

@ -2,6 +2,7 @@ package cron
import (
"context"
"fmt"
"log"
"time"
@ -31,11 +32,18 @@ type handler struct {
status string
}
func (h *handler) loadEnnoblements(servers []string) map[string]ennoblements {
func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, error) {
m := make(map[string]ennoblements)
query := ""
for _, w := range servers {
es, err := h.api.LiveEnnoblements.Browse(w, &sdk.LiveEnnoblementInclude{
query += fmt.Sprintf(`
%s: liveEnnoblements(server: "%s") {
%s
ennobledAt
}
`, w, w, sdk.LiveEnnoblementInclude{
NewOwner: true,
Village: true,
NewOwnerInclude: sdk.PlayerInclude{
@ -45,13 +53,17 @@ func (h *handler) loadEnnoblements(servers []string) map[string]ennoblements {
OldOwnerInclude: sdk.PlayerInclude{
Tribe: true,
},
})
if err != nil {
log.Printf("%s: %s", w, err.Error())
continue
}
}.String())
}
lastEnnoblementAt, ok := h.lastEnnoblementAt[w]
resp := make(map[string]ennoblements)
if err := h.api.Post(fmt.Sprintf(`query { %s }`, query), &resp); err != nil {
return m, errors.Wrap(err, "loadEnnoblements")
}
for server, ennoblements := range resp {
lastEnnoblementAt, ok := h.lastEnnoblementAt[server]
if !ok {
lastEnnoblementAt = time.Now().Add(-1 * time.Minute)
}
@ -59,16 +71,16 @@ func (h *handler) loadEnnoblements(servers []string) map[string]ennoblements {
lastEnnoblementAt = time.Now().Add(-60 * time.Minute)
}
m[w] = filterEnnoblements(es, lastEnnoblementAt)
m[server] = filterEnnoblements(ennoblements, lastEnnoblementAt)
lastEnnoblement := m[w].getLastEnnoblement()
lastEnnoblement := m[server].getLastEnnoblement()
if lastEnnoblement != nil {
lastEnnoblementAt = lastEnnoblement.EnnobledAt
}
h.lastEnnoblementAt[w] = lastEnnoblementAt
h.lastEnnoblementAt[server] = lastEnnoblementAt
}
return m
return m, nil
}
func (h *handler) loadLangVersions(servers []string) ([]*shared_models.LangVersion, error) {
@ -114,7 +126,11 @@ func (h *handler) checkEnnoblements() {
log.Print(err)
return
}
ennoblementsByServerKey := h.loadEnnoblements(servers)
ennoblementsByServerKey, err := h.loadEnnoblements(servers)
if err != nil {
log.Print(err)
return
}
for _, group := range groups {
if group.ConqueredVillagesChannelID == "" && group.LostVillagesChannelID == "" {
@ -145,10 +161,10 @@ func (h *handler) checkEnnoblements() {
}
if group.ConqueredVillagesChannelID != "" {
for _, ennoblement := range ennoblements.getConqueredVillagesByTribe(observation.TribeID, group.ShowSelfConquers) {
for _, ennoblement := range ennoblements.getConqueredVillagesByTribe(observation.TribeID, group.ShowInternals) {
isInTheSameGroup := !isPlayerTribeNil(ennoblement.OldOwner) &&
group.Observations.Contains(observation.Server, ennoblement.OldOwner.Tribe.ID)
if (!group.ShowSelfConquers && isInTheSameGroup) ||
if (!group.ShowInternals && isInTheSameGroup) ||
(!group.ShowEnnobledBarbarians && isBarbarian(ennoblement.OldOwner)) {
continue
}
@ -172,7 +188,7 @@ func (h *handler) checkEnnoblements() {
DefaultMessage: message.FallbackMsg("cron.conqueredVillages.title",
"Conquered villages"),
})
h.discord.SendEmbed(group.ConqueredVillagesChannelID,
go h.discord.SendEmbed(group.ConqueredVillagesChannelID,
discord.
NewEmbed().
SetTitle(title).
@ -188,7 +204,7 @@ func (h *handler) checkEnnoblements() {
DefaultMessage: message.FallbackMsg("cron.lostVillages.title",
"Lost villages"),
})
h.discord.SendEmbed(group.LostVillagesChannelID,
go h.discord.SendEmbed(group.LostVillagesChannelID,
discord.
NewEmbed().
SetTitle(title).

View File

@ -32,7 +32,7 @@ const (
ConqueredVillagesCommand Command = "conqueredvillages"
DisableConqueredVillagesCommand Command = "disableconqueredvillages"
ChangeLanguageCommand Command = "changelanguage"
ShowSelfConquersCommand Command = "showselfconquers"
ShowInternalsCommand Command = "showinternals"
)
func (s *Session) handleAddGroupCommand(ctx commandCtx, m *discordgo.MessageCreate) {
@ -964,7 +964,7 @@ func (s *Session) handleChangeLanguageCommand(ctx commandCtx, m *discordgo.Messa
}))
}
func (s *Session) handleShowSelfConquersCommand(ctx commandCtx, m *discordgo.MessageCreate, args ...string) {
func (s *Session) handleShowInternalsCommand(ctx commandCtx, m *discordgo.MessageCreate, args ...string) {
if has, err := s.memberHasPermission(m.GuildID, m.Author.ID, discordgo.PermissionAdministrator); err != nil || !has {
return
}
@ -976,11 +976,11 @@ func (s *Session) handleShowSelfConquersCommand(ctx commandCtx, m *discordgo.Mes
} else if argsLength < 1 {
s.SendMessage(m.ChannelID,
m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: "help.showselfconquers",
DefaultMessage: message.FallbackMsg("help.showselfconquers",
MessageID: "help.showinternals",
DefaultMessage: message.FallbackMsg("help.showinternals",
"**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about self-conquers between tribes in one group."),
TemplateData: map[string]interface{}{
"Command": ShowSelfConquersCommand.WithPrefix(s.cfg.CommandPrefix),
"Command": ShowInternalsCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
},
}))
@ -1013,8 +1013,8 @@ func (s *Session) handleShowSelfConquersCommand(ctx commandCtx, m *discordgo.Mes
return
}
oldValue := group.ShowSelfConquers
group.ShowSelfConquers = !oldValue
oldValue := group.ShowInternals
group.ShowInternals = !oldValue
if err := s.cfg.GroupRepository.Update(context.Background(), group); err != nil {
s.SendMessage(m.ChannelID,
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{

View File

@ -161,8 +161,8 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre
case ShowEnnobledBarbariansCommand.WithPrefix(s.cfg.CommandPrefix):
s.handleShowEnnobledBarbariansCommand(ctx, m, args...)
case ShowSelfConquersCommand.WithPrefix(s.cfg.CommandPrefix):
s.handleShowSelfConquersCommand(ctx, m, args...)
case ShowInternalsCommand.WithPrefix(s.cfg.CommandPrefix):
s.handleShowInternalsCommand(ctx, m, args...)
}
}

View File

@ -213,11 +213,11 @@ func (s *Session) handleHelpCommand(ctx commandCtx, m *discordgo.MessageCreate)
},
}),
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: "help.showselfconquers",
DefaultMessage: message.FallbackMsg("help.showselfconquers",
MessageID: "help.showinternals",
DefaultMessage: message.FallbackMsg("help.showinternals",
"**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about self-conquers between tribes in one group."),
TemplateData: map[string]interface{}{
"Command": ShowSelfConquersCommand.WithPrefix(s.cfg.CommandPrefix),
"Command": ShowInternalsCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
},
}),

2
go.mod
View File

@ -10,7 +10,7 @@ require (
github.com/pkg/errors v0.9.1
github.com/robfig/cron/v3 v3.0.1
github.com/segmentio/encoding v0.1.14 // indirect
github.com/tribalwarshelp/golang-sdk v0.0.0-20200721095058-9ee3513a54a9
github.com/tribalwarshelp/golang-sdk v0.0.0-20200727153039-1b7b21ad36a9
github.com/tribalwarshelp/shared v0.0.0-20200721124533-776cbb36074b
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 // indirect
golang.org/x/text v0.3.2

4
go.sum
View File

@ -107,6 +107,10 @@ github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYm
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs=
github.com/tribalwarshelp/golang-sdk v0.0.0-20200721095058-9ee3513a54a9 h1:y4fY0Ax8/OUMWvRFr9FkZ9QrKSi4MKsbovt31J3N+us=
github.com/tribalwarshelp/golang-sdk v0.0.0-20200721095058-9ee3513a54a9/go.mod h1:wRoVfjxu4FozpiJmDknv5Zw4AOx/0IC+VttDaSTpBg8=
github.com/tribalwarshelp/golang-sdk v0.0.0-20200727152443-be3c1217e00a h1:3INKmz4vQYFdIXOm1GPtfw+bZa30rFmCsUxTf5t2+Uc=
github.com/tribalwarshelp/golang-sdk v0.0.0-20200727152443-be3c1217e00a/go.mod h1:wRoVfjxu4FozpiJmDknv5Zw4AOx/0IC+VttDaSTpBg8=
github.com/tribalwarshelp/golang-sdk v0.0.0-20200727153039-1b7b21ad36a9 h1:xjCeZkqxGOC6hDirgHAIAeXianzRs5gN0pNgPlRQnNg=
github.com/tribalwarshelp/golang-sdk v0.0.0-20200727153039-1b7b21ad36a9/go.mod h1:wRoVfjxu4FozpiJmDknv5Zw4AOx/0IC+VttDaSTpBg8=
github.com/tribalwarshelp/shared v0.0.0-20200721094728-9ea33a732990 h1:PwMCKm5Wvqq+tP3KvdqxPtxKtKZTaEONCBT5DvpbVrc=
github.com/tribalwarshelp/shared v0.0.0-20200721094728-9ea33a732990/go.mod h1:tf+2yTHasV6jAF3V2deZ9slNoCyBzC0fMdTjI7clf6Y=
github.com/tribalwarshelp/shared v0.0.0-20200721124533-776cbb36074b h1:8bgZG6Zi3ROqtvpeUOj3a19mtES88VjeNwkUF0FI+Vs=

View File

@ -22,7 +22,7 @@
"help.lostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about lost village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications.",
"help.disablelostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disable notifications about lost villages.",
"help.changelanguage": "**{{.Command}}** [{{.Languages}}] - change language.",
"help.showselfconquers": "**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about self-conquers between tribes in one group.",
"help.showinternals": "**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about self-conquers between tribes in one group.",
"tribe.invalidPage": "{{.Mention}} The page must be a number greater than 0.",
"tribe.noTribeID": "{{.Mention}} You haven't entered the tribe ID.",
@ -86,10 +86,10 @@
"changeLanguage.languageNotSupported": "{{.Mention}} Language not supported.",
"changeLanguage.success": "{{.Mention}} The language has been changed.",
"showSelfConquers.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.",
"showSelfConquers.groupNotFound": "{{.Mention}} Group not found.",
"showSelfConquers.success_1": "{{.Mention}} Notifications about self-conquers will no longer show up.",
"showSelfConquers.success_2": "{{.Mention}} Enabled notifications about self-conquers.",
"showInternals.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.",
"showInternals.groupNotFound": "{{.Mention}} Group not found.",
"showInternals.success_1": "{{.Mention}} Notifications about self-conquers will no longer show up.",
"showInternals.success_2": "{{.Mention}} Enabled notifications about self-conquers.",
"cron.lostVillages.title": "Lost villages",
"cron.conqueredVillages.title": "Conquered villages",

View File

@ -22,7 +22,7 @@
"help.lostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - zmienia kanał na którym będą się pojawiać informację o straconych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.",
"help.disablelostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - wyłącza powiadomienia o straconych wioskach w danej grupie.",
"help.changelanguage": "**{{.Command}}** [{{.Languages}}] - zmień język.",
"help.showselfconquers": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - włącza/wyłącza notyfikacje o podbiciach plemion należących do jednej grupy.",
"help.showinternals": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - włącza/wyłącza notyfikacje o podbiciach plemion należących do jednej grupy.",
"tribe.invalidPage": "{{.Mention}} Strona musi być liczbą większą od 0.",
"tribe.noTribeID": "{{.Mention}} Nie wprowadziłeś ID plemienia.",
@ -83,10 +83,10 @@
"showEnnobledBarbs.success_1": "{{.Mention}} Powiadomienia o podbitych barbarkach nie będą się już dłużej pokazywały.",
"showEnnobledBarbs.success_2": "{{.Mention}} Włączono powiadomienia o podbitych barbarkach.",
"showSelfConquers.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"showSelfConquers.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
"showSelfConquers.success_1": "{{.Mention}} Powiadomieniach o podbiciach plemion w tej samej grupie nie będą się już pokazywały.",
"showSelfConquers.success_2": "{{.Mention}} Włączono powiadomienia o podbiciach plemion w tej samej grupie.",
"showInternals.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"showInternals.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
"showInternals.success_1": "{{.Mention}} Powiadomieniach o podbiciach plemion w tej samej grupie nie będą się już pokazywały.",
"showInternals.success_2": "{{.Mention}} Włączono powiadomienia o podbiciach plemion w tej samej grupie.",
"changeLanguage.languageNotSupported": "{{.Mention}} Język nie jest obsługiwany.",
"changeLanguage.success": "{{.Mention}} Język został zmieniony.",

View File

@ -5,7 +5,7 @@ type Group struct {
ConqueredVillagesChannelID string `pg:",use_zero" json:"conqueredVillagesChannelID" gqlgen:"conqueredVillagesChannelID"`
LostVillagesChannelID string `pg:",use_zero" json:"lostVillagesChannelID" gqlgen:"lostVillagesChannelID"`
ShowEnnobledBarbarians bool `pg:",use_zero"`
ShowSelfConquers bool `pg:",use_zero"`
ShowInternals bool `pg:",use_zero"`
ServerID string `pg:"on_delete:CASCADE,use_zero" json:"serverID" gqlgen:"serverID"`
Server *Server `json:"server,omitempty" gqlgen:"server"`
Observations Observations `json:"observation,omitempty" gqlgen:"observation"`