Merge pull request #14 from tribalwarshelp/bump-shared

Bump shared
This commit is contained in:
Dawid Wysokiński 2021-05-06 16:00:10 +02:00 committed by GitHub
commit 496ff5c9d2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 346 additions and 343 deletions

View File

@ -12,24 +12,24 @@ RUN go mod download
# Copy the source from the current directory to the Working Directory inside the container # Copy the source from the current directory to the Working Directory inside the container
COPY . . COPY . .
RUN go build -o dcbot . RUN go build -o twhelpdcbot .
######## Start a new stage from scratch ####### ######## Start a new stage from scratch #######
FROM alpine:latest FROM alpine:latest
RUN apk --no-cache add ca-certificates RUN apk --no-cache add ca-certificates
WORKDIR /root/ WORKDIR /root/
# Copy the Pre-built binary file from the previous stage # Copy the Pre-built binary file and translations from the previous stage
COPY --from=builder /app/message/translations ./message/translations COPY --from=builder /app/message/translations ./message/translations
COPY --from=builder /app/dcbot . COPY --from=builder /app/twhelpdcbot .
ENV MODE=production ENV APP_MODE=production
ENV GIN_MODE=release ENV GIN_MODE=release
EXPOSE 8080 EXPOSE 8080
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait ./wait ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait ./wait
RUN chmod +x ./wait RUN chmod +x ./wait
CMD ./wait && ./dcbot CMD ./wait && ./twhelpdcbot

View File

@ -18,7 +18,7 @@ Features:
## Development ## Development
**Required env variables to run this bot:** **Required ENV variables:**
``` ```
DB_USER=your_pgdb_user DB_USER=your_pgdb_user

View File

@ -1,13 +1,11 @@
package cron package cron
import ( import (
"github.com/Kichiyaki/appmode"
"time" "time"
sharedutils "github.com/tribalwarshelp/shared/utils"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/tribalwarshelp/golang-sdk/sdk" "github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/tribalwarshelp/shared/mode"
"github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/discord"
"github.com/tribalwarshelp/dcbot/group" "github.com/tribalwarshelp/dcbot/group"
@ -38,12 +36,12 @@ func Attach(c *cron.Cron, cfg Config) {
api: cfg.API, api: cfg.API,
status: cfg.Status, status: cfg.Status,
} }
checkEnnoblements := sharedutils.TrackExecutionTime(log, h.checkEnnoblements, "checkEnnoblements") checkEnnoblements := trackDuration(log, h.checkEnnoblements, "checkEnnoblements")
checkBotServers := sharedutils.TrackExecutionTime(log, h.checkBotServers, "checkBotServers") checkBotServers := trackDuration(log, h.checkBotServers, "checkBotServers")
deleteClosedTribalWarsServers := sharedutils.TrackExecutionTime(log, deleteClosedTribalWarsServers := trackDuration(log,
h.deleteClosedTribalWarsServers, h.deleteClosedTWServers,
"deleteClosedTribalWarsServers") "deleteClosedTWServers")
updateBotStatus := sharedutils.TrackExecutionTime(log, h.updateBotStatus, "updateBotStatus") updateBotStatus := trackDuration(log, h.updateBotStatus, "updateBotStatus")
c.AddFunc("@every 1m", checkEnnoblements) c.AddFunc("@every 1m", checkEnnoblements)
c.AddFunc("@every 30m", checkBotServers) c.AddFunc("@every 30m", checkBotServers)
c.AddFunc("@every 2h10m", deleteClosedTribalWarsServers) c.AddFunc("@every 2h10m", deleteClosedTribalWarsServers)
@ -52,7 +50,7 @@ func Attach(c *cron.Cron, cfg Config) {
checkBotServers() checkBotServers()
deleteClosedTribalWarsServers() deleteClosedTribalWarsServers()
updateBotStatus() updateBotStatus()
if mode.Get() == mode.DevelopmentMode { if appmode.Equals(appmode.DevelopmentMode) {
checkEnnoblements() checkEnnoblements()
} }
}() }()

View File

@ -1,13 +1,14 @@
package cron package cron
import ( import (
"github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/shared/tw/twmodel"
shared_models "github.com/tribalwarshelp/shared/models"
"github.com/tribalwarshelp/dcbot/tw/twutil"
) )
type ennoblements []*shared_models.Ennoblement type ennoblements []*twmodel.Ennoblement
func (e ennoblements) getLastEnnoblement() *shared_models.Ennoblement { func (e ennoblements) getLastEnnoblement() *twmodel.Ennoblement {
length := len(e) length := len(e)
if length <= 0 { if length <= 0 {
return nil return nil
@ -18,8 +19,8 @@ func (e ennoblements) getLastEnnoblement() *shared_models.Ennoblement {
func (e ennoblements) getLostVillagesByTribe(tribeID int) ennoblements { func (e ennoblements) getLostVillagesByTribe(tribeID int) ennoblements {
filtered := ennoblements{} filtered := ennoblements{}
for _, ennoblement := range e { for _, ennoblement := range e {
if (!utils.IsPlayerTribeNil(ennoblement.NewOwner) && ennoblement.NewOwner.Tribe.ID == tribeID) || if (!twutil.IsPlayerTribeNil(ennoblement.NewOwner) && ennoblement.NewOwner.Tribe.ID == tribeID) ||
utils.IsPlayerTribeNil(ennoblement.OldOwner) || twutil.IsPlayerTribeNil(ennoblement.OldOwner) ||
ennoblement.OldOwner.Tribe.ID != tribeID { ennoblement.OldOwner.Tribe.ID != tribeID {
continue continue
} }
@ -31,9 +32,9 @@ func (e ennoblements) getLostVillagesByTribe(tribeID int) ennoblements {
func (e ennoblements) getConqueredVillagesByTribe(tribeID int, showInternals bool) ennoblements { func (e ennoblements) getConqueredVillagesByTribe(tribeID int, showInternals bool) ennoblements {
filtered := ennoblements{} filtered := ennoblements{}
for _, ennoblement := range e { for _, ennoblement := range e {
if utils.IsPlayerTribeNil(ennoblement.NewOwner) || if twutil.IsPlayerTribeNil(ennoblement.NewOwner) ||
ennoblement.NewOwner.Tribe.ID != tribeID || ennoblement.NewOwner.Tribe.ID != tribeID ||
(!showInternals && !utils.IsPlayerTribeNil(ennoblement.OldOwner) && ennoblement.OldOwner.Tribe.ID == tribeID) { (!showInternals && !twutil.IsPlayerTribeNil(ennoblement.OldOwner) && ennoblement.OldOwner.Tribe.ID == tribeID) {
continue continue
} }
filtered = append(filtered, ennoblement) filtered = append(filtered, ennoblement)

View File

@ -3,24 +3,24 @@ package cron
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/Kichiyaki/appmode"
"github.com/tribalwarshelp/shared/tw/twmodel"
"time" "time"
"github.com/tribalwarshelp/shared/tw"
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/tribalwarshelp/dcbot/message"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/tribalwarshelp/shared/mode"
shared_models "github.com/tribalwarshelp/shared/models" "github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/dcbot/tw/twutil"
"github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/discord"
"github.com/tribalwarshelp/dcbot/group" "github.com/tribalwarshelp/dcbot/group"
"github.com/tribalwarshelp/dcbot/models" "github.com/tribalwarshelp/dcbot/models"
"github.com/tribalwarshelp/dcbot/observation" "github.com/tribalwarshelp/dcbot/observation"
"github.com/tribalwarshelp/dcbot/server" "github.com/tribalwarshelp/dcbot/server"
"github.com/tribalwarshelp/dcbot/utils"
"github.com/tribalwarshelp/golang-sdk/sdk"
) )
type handler struct { type handler struct {
@ -42,13 +42,13 @@ func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, e
query := "" query := ""
for _, server := range servers { for _, s := range servers {
lastEnnoblementAt, ok := h.lastEnnoblementAt[server] lastEnnoblementAt, ok := h.lastEnnoblementAt[s]
if !ok { if !ok {
lastEnnoblementAt = time.Now().Add(-1 * time.Minute) lastEnnoblementAt = time.Now().Add(-1 * time.Minute)
h.lastEnnoblementAt[server] = lastEnnoblementAt h.lastEnnoblementAt[s] = lastEnnoblementAt
} }
if mode.Get() == mode.DevelopmentMode { if appmode.Equals(appmode.DevelopmentMode) {
lastEnnoblementAt = time.Now().Add(-1 * time.Hour * 2) lastEnnoblementAt = time.Now().Add(-1 * time.Hour * 2)
} }
lastEnnoblementAtJSON, err := lastEnnoblementAt.MarshalJSON() lastEnnoblementAtJSON, err := lastEnnoblementAt.MarshalJSON()
@ -62,8 +62,8 @@ func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, e
ennobledAt ennobledAt
} }
} }
`, server, `, s,
server, s,
string(lastEnnoblementAtJSON), string(lastEnnoblementAtJSON),
sdk.EnnoblementInclude{ sdk.EnnoblementInclude{
NewOwner: true, NewOwner: true,
@ -83,40 +83,40 @@ func (h *handler) loadEnnoblements(servers []string) (map[string]ennoblements, e
return m, errors.Wrap(err, "loadEnnoblements") return m, errors.Wrap(err, "loadEnnoblements")
} }
for server, singleServerResp := range resp { for s, singleServerResp := range resp {
if singleServerResp == nil { if singleServerResp == nil {
continue continue
} }
m[server] = ennoblements(singleServerResp.Items) m[s] = singleServerResp.Items
lastEnnoblement := m[server].getLastEnnoblement() lastEnnoblement := m[s].getLastEnnoblement()
if lastEnnoblement != nil { if lastEnnoblement != nil {
h.lastEnnoblementAt[server] = lastEnnoblement.EnnobledAt h.lastEnnoblementAt[s] = lastEnnoblement.EnnobledAt
} }
} }
return m, nil return m, nil
} }
func (h *handler) loadVersions(servers []string) ([]*shared_models.Version, error) { func (h *handler) loadVersions(servers []string) ([]*twmodel.Version, error) {
versionCodes := []shared_models.VersionCode{} var versionCodes []twmodel.VersionCode
cache := make(map[shared_models.VersionCode]bool) cache := make(map[twmodel.VersionCode]bool)
for _, server := range servers { for _, s := range servers {
languageTag := tw.VersionCodeFromServerKey(server) versionCode := twmodel.VersionCodeFromServerKey(s)
if languageTag.IsValid() && !cache[languageTag] { if versionCode.IsValid() && !cache[versionCode] {
cache[languageTag] = true cache[versionCode] = true
versionCodes = append(versionCodes, languageTag) versionCodes = append(versionCodes, versionCode)
} }
} }
if len(versionCodes) == 0 { if len(versionCodes) == 0 {
return []*shared_models.Version{}, nil return []*twmodel.Version{}, nil
} }
versionList, err := h.api.Version.Browse(0, 0, []string{"code ASC"}, &shared_models.VersionFilter{ versionList, err := h.api.Version.Browse(0, 0, []string{"code ASC"}, &twmodel.VersionFilter{
Code: versionCodes, Code: versionCodes,
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "cannot load versions") return nil, errors.Wrap(err, "couldn't load versions")
} }
return versionList.Items, nil return versionList.Items, nil
@ -130,7 +130,7 @@ func (h *handler) checkEnnoblements() {
} }
log. log.
WithField("servers", servers). WithField("servers", servers).
Info("checkEnnoblements: loaded servers") Info("checkEnnoblements: servers have been loaded")
groups, total, err := h.groupRepo.Fetch(context.Background(), nil) groups, total, err := h.groupRepo.Fetch(context.Background(), nil)
if err != nil { if err != nil {
@ -139,7 +139,7 @@ func (h *handler) checkEnnoblements() {
} }
log. log.
WithField("numberOfGroups", total). WithField("numberOfGroups", total).
Info("checkEnnoblements: loaded groups") Info("checkEnnoblements: groups have been loaded")
versions, err := h.loadVersions(servers) versions, err := h.loadVersions(servers)
if err != nil { if err != nil {
@ -148,34 +148,34 @@ func (h *handler) checkEnnoblements() {
} }
log. log.
WithField("numberOfVersions", len(versions)). WithField("numberOfVersions", len(versions)).
Info("checkEnnoblements: loaded versions") Info("checkEnnoblements: versions have been loaded")
ennoblementsByServerKey, err := h.loadEnnoblements(servers) ennoblementsByServerKey, err := h.loadEnnoblements(servers)
if err != nil { if err != nil {
log.Errorln("checkEnnoblements:", err) log.Errorln("checkEnnoblements:", err)
} }
log.Info("checkEnnoblements: loaded ennoblements") log.Info("checkEnnoblements: ennoblements have been loaded")
for _, group := range groups { for _, g := range groups {
if group.ConqueredVillagesChannelID == "" && group.LostVillagesChannelID == "" { if g.ConqueredVillagesChannelID == "" && g.LostVillagesChannelID == "" {
continue continue
} }
localizer := message.NewLocalizer(group.Server.Lang) localizer := message.NewLocalizer(g.Server.Lang)
lostVillagesMsg := &discord.MessageEmbed{} lostVillagesMsg := &discord.MessageEmbed{}
conqueredVillagesMsg := &discord.MessageEmbed{} conqueredVillagesMsg := &discord.MessageEmbed{}
for _, observation := range group.Observations { for _, obs := range g.Observations {
ennoblements, ok := ennoblementsByServerKey[observation.Server] enblmnts, ok := ennoblementsByServerKey[obs.Server]
version := utils.FindVersionByCode(versions, tw.VersionCodeFromServerKey(observation.Server)) version := twutil.FindVersionByCode(versions, twmodel.VersionCodeFromServerKey(obs.Server))
if ok && version != nil && version.Host != "" { if ok && version != nil && version.Host != "" {
if group.LostVillagesChannelID != "" { if g.LostVillagesChannelID != "" {
for _, ennoblement := range ennoblements.getLostVillagesByTribe(observation.TribeID) { for _, ennoblement := range enblmnts.getLostVillagesByTribe(obs.TribeID) {
if !utils.IsPlayerTribeNil(ennoblement.NewOwner) && if !twutil.IsPlayerTribeNil(ennoblement.NewOwner) &&
group.Observations.Contains(observation.Server, ennoblement.NewOwner.Tribe.ID) { g.Observations.Contains(obs.Server, ennoblement.NewOwner.Tribe.ID) {
continue continue
} }
newMsgDataConfig := newMessageConfig{ newMsgDataConfig := newMessageConfig{
host: version.Host, host: version.Host,
server: observation.Server, server: obs.Server,
ennoblement: ennoblement, ennoblement: ennoblement,
t: messageTypeLost, t: messageTypeLost,
localizer: localizer, localizer: localizer,
@ -184,18 +184,18 @@ func (h *handler) checkEnnoblements() {
} }
} }
if group.ConqueredVillagesChannelID != "" { if g.ConqueredVillagesChannelID != "" {
for _, ennoblement := range ennoblements.getConqueredVillagesByTribe(observation.TribeID, group.ShowInternals) { for _, ennoblement := range enblmnts.getConqueredVillagesByTribe(obs.TribeID, g.ShowInternals) {
isInTheSameGroup := !utils.IsPlayerTribeNil(ennoblement.OldOwner) && isInTheSameGroup := !twutil.IsPlayerTribeNil(ennoblement.OldOwner) &&
group.Observations.Contains(observation.Server, ennoblement.OldOwner.Tribe.ID) g.Observations.Contains(obs.Server, ennoblement.OldOwner.Tribe.ID)
if (!group.ShowInternals && isInTheSameGroup) || if (!g.ShowInternals && isInTheSameGroup) ||
(!group.ShowEnnobledBarbarians && isBarbarian(ennoblement.OldOwner)) { (!g.ShowEnnobledBarbarians && isBarbarian(ennoblement.OldOwner)) {
continue continue
} }
newMsgDataConfig := newMessageConfig{ newMsgDataConfig := newMessageConfig{
host: version.Host, host: version.Host,
server: observation.Server, server: obs.Server,
ennoblement: ennoblement, ennoblement: ennoblement,
t: messageTypeConquer, t: messageTypeConquer,
localizer: localizer, localizer: localizer,
@ -207,13 +207,13 @@ func (h *handler) checkEnnoblements() {
} }
timestamp := time.Now().Format(time.RFC3339) timestamp := time.Now().Format(time.RFC3339)
if group.ConqueredVillagesChannelID != "" && !conqueredVillagesMsg.IsEmpty() { if g.ConqueredVillagesChannelID != "" && !conqueredVillagesMsg.IsEmpty() {
title := localizer.MustLocalize(&i18n.LocalizeConfig{ title := localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.CronConqueredVillagesTitle, MessageID: message.CronConqueredVillagesTitle,
DefaultMessage: message.FallbackMsg(message.CronConqueredVillagesTitle, DefaultMessage: message.FallbackMsg(message.CronConqueredVillagesTitle,
"Conquered villages"), "Conquered villages"),
}) })
go h.discord.SendEmbed(group.ConqueredVillagesChannelID, go h.discord.SendEmbed(g.ConqueredVillagesChannelID,
discord. discord.
NewEmbed(). NewEmbed().
SetTitle(title). SetTitle(title).
@ -223,13 +223,13 @@ func (h *handler) checkEnnoblements() {
MessageEmbed) MessageEmbed)
} }
if group.LostVillagesChannelID != "" && !lostVillagesMsg.IsEmpty() { if g.LostVillagesChannelID != "" && !lostVillagesMsg.IsEmpty() {
title := localizer.MustLocalize(&i18n.LocalizeConfig{ title := localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.CronLostVillagesTitle, MessageID: message.CronLostVillagesTitle,
DefaultMessage: message.FallbackMsg(message.CronLostVillagesTitle, DefaultMessage: message.FallbackMsg(message.CronLostVillagesTitle,
"Lost villages"), "Lost villages"),
}) })
go h.discord.SendEmbed(group.LostVillagesChannelID, go h.discord.SendEmbed(g.LostVillagesChannelID,
discord. discord.
NewEmbed(). NewEmbed().
SetTitle(title). SetTitle(title).
@ -251,10 +251,10 @@ func (h *handler) checkBotServers() {
WithField("numberOfServers", total). WithField("numberOfServers", total).
Info("checkBotServers: loaded servers") Info("checkBotServers: loaded servers")
idsToDelete := []string{} var idsToDelete []string
for _, server := range servers { for _, s := range servers {
if isGuildMember, _ := h.discord.IsGuildMember(server.ID); !isGuildMember { if isGuildMember, _ := h.discord.IsGuildMember(s.ID); !isGuildMember {
idsToDelete = append(idsToDelete, server.ID) idsToDelete = append(idsToDelete, s.ID)
} }
} }
@ -267,36 +267,36 @@ func (h *handler) checkBotServers() {
} else { } else {
log. log.
WithField("numberOfDeletedServers", len(deleted)). WithField("numberOfDeletedServers", len(deleted)).
Info("checkBotServers: deleted servers") Info("checkBotServers: some of the servers have been deleted")
} }
} }
} }
func (h *handler) deleteClosedTribalWarsServers() { func (h *handler) deleteClosedTWServers() {
servers, err := h.observationRepo.FetchServers(context.Background()) servers, err := h.observationRepo.FetchServers(context.Background())
if err != nil { if err != nil {
log.Error("deleteClosedTribalWarsServers: " + err.Error()) log.Error("deleteClosedTWServers: " + err.Error())
return return
} }
log. log.
WithField("servers", servers). WithField("servers", servers).
Info("deleteClosedTribalWarsServers: loaded servers") Info("deleteClosedTWServers: loaded servers")
list, err := h.api.Server.Browse(0, 0, []string{"key ASC"}, &shared_models.ServerFilter{ list, err := h.api.Server.Browse(0, 0, []string{"key ASC"}, &twmodel.ServerFilter{
Key: servers, Key: servers,
Status: []shared_models.ServerStatus{shared_models.ServerStatusClosed}, Status: []twmodel.ServerStatus{twmodel.ServerStatusClosed},
}, nil) }, nil)
if err != nil { if err != nil {
log.Errorln("deleteClosedTribalWarsServers: " + err.Error()) log.Errorln("deleteClosedTWServers: " + err.Error())
return return
} }
if list == nil || list.Items == nil { if list == nil || list.Items == nil {
return return
} }
keys := []string{} var keys []string
for _, server := range list.Items { for _, s := range list.Items {
keys = append(keys, server.Key) keys = append(keys, s.Key)
} }
if len(keys) > 0 { if len(keys) > 0 {
@ -304,11 +304,11 @@ func (h *handler) deleteClosedTribalWarsServers() {
Server: keys, Server: keys,
}) })
if err != nil { if err != nil {
log.Errorln("deleteClosedTribalWarsServers: " + err.Error()) log.Errorln("deleteClosedTWServers: " + err.Error())
} else { } else {
log. log.
WithField("numberOfDeletedObservations", len(deleted)). WithField("numberOfDeletedObservations", len(deleted)).
Infof("deleteClosedTribalWarsServers: deleted observations") Infof("deleteClosedTWServers: some of the observations have been deleted")
} }
} }
} }

View File

@ -1,10 +1,29 @@
package cron package cron
import ( import (
"github.com/tribalwarshelp/dcbot/utils" "github.com/sirupsen/logrus"
shared_models "github.com/tribalwarshelp/shared/models" "github.com/tribalwarshelp/shared/tw/twmodel"
"time"
"github.com/tribalwarshelp/dcbot/tw/twutil"
) )
func isBarbarian(p *shared_models.Player) bool { func isBarbarian(p *twmodel.Player) bool {
return utils.IsPlayerNil(p) || p.ID == 0 return twutil.IsPlayerNil(p) || p.ID == 0
}
func trackDuration(log *logrus.Entry, fn func(), fnName string) func() {
return func() {
now := time.Now()
log := log.WithField("fnName", fnName)
log.Infof("'%s' has been called", fnName)
fn()
duration := time.Since(now)
log.
WithField("duration", duration.Nanoseconds()).
WithField("durationPretty", duration.String()).
Infof("'%s' finished executing", fnName)
}
} }

View File

@ -2,11 +2,12 @@ package cron
import ( import (
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/tribalwarshelp/shared/tw/twmodel"
"github.com/tribalwarshelp/shared/tw/twurlbuilder"
"github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/discord"
"github.com/tribalwarshelp/dcbot/message" "github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/dcbot/tw/twutil"
shared_models "github.com/tribalwarshelp/shared/models"
"github.com/tribalwarshelp/shared/tw"
) )
type messageType string type messageType string
@ -38,7 +39,7 @@ type newMessageConfig struct {
t messageType t messageType
host string host string
server string server string
ennoblement *shared_models.Ennoblement ennoblement *twmodel.Ennoblement
localizer *i18n.Localizer localizer *i18n.Localizer
} }
@ -53,25 +54,25 @@ func newMessage(cfg newMessageConfig) checkEnnoblementsMsg {
newOwnerTribeTag: "-", newOwnerTribeTag: "-",
localizer: cfg.localizer, localizer: cfg.localizer,
} }
if !utils.IsVillageNil(cfg.ennoblement.Village) { if !twutil.IsVillageNil(cfg.ennoblement.Village) {
data.village = cfg.ennoblement.Village.FullName() data.village = cfg.ennoblement.Village.FullName()
data.villageURL = tw.BuildVillageURL(cfg.server, cfg.host, cfg.ennoblement.Village.ID) data.villageURL = twurlbuilder.BuildVillageURL(cfg.server, cfg.host, cfg.ennoblement.Village.ID)
} }
if !utils.IsPlayerNil(cfg.ennoblement.OldOwner) { if !twutil.IsPlayerNil(cfg.ennoblement.OldOwner) {
data.oldOwnerName = cfg.ennoblement.OldOwner.Name data.oldOwnerName = cfg.ennoblement.OldOwner.Name
data.oldOwnerURL = tw.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.ID) data.oldOwnerURL = twurlbuilder.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.ID)
} }
if !utils.IsPlayerTribeNil(cfg.ennoblement.OldOwner) { if !twutil.IsPlayerTribeNil(cfg.ennoblement.OldOwner) {
data.oldOwnerTribeTag = cfg.ennoblement.OldOwner.Tribe.Tag data.oldOwnerTribeTag = cfg.ennoblement.OldOwner.Tribe.Tag
data.oldOwnerTribeURL = tw.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.Tribe.ID) data.oldOwnerTribeURL = twurlbuilder.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.OldOwner.Tribe.ID)
} }
if !utils.IsPlayerNil(cfg.ennoblement.NewOwner) { if !twutil.IsPlayerNil(cfg.ennoblement.NewOwner) {
data.newOwnerName = cfg.ennoblement.NewOwner.Name data.newOwnerName = cfg.ennoblement.NewOwner.Name
data.newOwnerURL = tw.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.ID) data.newOwnerURL = twurlbuilder.BuildPlayerURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.ID)
} }
if !utils.IsPlayerTribeNil(cfg.ennoblement.NewOwner) { if !twutil.IsPlayerTribeNil(cfg.ennoblement.NewOwner) {
data.newOwnerTribeTag = cfg.ennoblement.NewOwner.Tribe.Tag data.newOwnerTribeTag = cfg.ennoblement.NewOwner.Tribe.Tag
data.newOwnerTribeURL = tw.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.Tribe.ID) data.newOwnerTribeURL = twurlbuilder.BuildTribeURL(cfg.server, cfg.host, cfg.ennoblement.NewOwner.Tribe.ID)
} }
return data return data

3
dev.sh
View File

@ -1,3 +0,0 @@
#!/bin/sh
export MODE=development
go run main.go

View File

@ -2,15 +2,16 @@ package discord
import ( import (
"context" "context"
"github.com/tribalwarshelp/shared/tw/twmodel"
"github.com/tribalwarshelp/shared/tw/twurlbuilder"
"regexp" "regexp"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/dcbot/utils"
"github.com/tribalwarshelp/golang-sdk/sdk" "github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/tribalwarshelp/shared/models"
"github.com/tribalwarshelp/shared/tw" "github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/dcbot/tw/twutil"
) )
const ( const (
@ -86,7 +87,7 @@ func (s *Session) translateCoords(ctx *commandCtx, m *discordgo.MessageCreate) {
coords := coordsRegex.FindAllString(m.Content, -1) coords := coordsRegex.FindAllString(m.Content, -1)
coordsLen := len(coords) coordsLen := len(coords)
if coordsLen > 0 { if coordsLen > 0 {
version, err := s.cfg.API.Version.Read(tw.VersionCodeFromServerKey(ctx.server.CoordsTranslation)) version, err := s.cfg.API.Version.Read(twmodel.VersionCodeFromServerKey(ctx.server.CoordsTranslation))
if err != nil || version == nil { if err != nil || version == nil {
return return
} }
@ -97,7 +98,7 @@ func (s *Session) translateCoords(ctx *commandCtx, m *discordgo.MessageCreate) {
0, 0,
0, 0,
[]string{}, []string{},
&models.VillageFilter{ &twmodel.VillageFilter{
XY: coords, XY: coords,
}, },
&sdk.VillageInclude{ &sdk.VillageInclude{
@ -105,25 +106,26 @@ func (s *Session) translateCoords(ctx *commandCtx, m *discordgo.MessageCreate) {
PlayerInclude: sdk.PlayerInclude{ PlayerInclude: sdk.PlayerInclude{
Tribe: true, Tribe: true,
}, },
}) },
if err != nil || list == nil || list.Items == nil || len(list.Items) <= 0 { )
if err != nil || list == nil || list.Items == nil {
return return
} }
msg := &MessageEmbed{} msg := &MessageEmbed{}
for _, village := range list.Items { for _, village := range list.Items {
villageURL := tw.BuildVillageURL(ctx.server.CoordsTranslation, version.Host, village.ID) villageURL := twurlbuilder.BuildVillageURL(ctx.server.CoordsTranslation, version.Host, village.ID)
playerName := "-" playerName := "-"
playerURL := "" playerURL := ""
if !utils.IsPlayerNil(village.Player) { if !twutil.IsPlayerNil(village.Player) {
playerName = village.Player.Name playerName = village.Player.Name
playerURL = tw.BuildPlayerURL(ctx.server.CoordsTranslation, version.Host, village.Player.ID) playerURL = twurlbuilder.BuildPlayerURL(ctx.server.CoordsTranslation, version.Host, village.Player.ID)
} }
tribeName := "-" tribeName := "-"
tribeURL := "" tribeURL := ""
if !utils.IsPlayerTribeNil(village.Player) { if !twutil.IsPlayerTribeNil(village.Player) {
tribeName = village.Player.Tribe.Name tribeName = village.Player.Tribe.Name
tribeURL = tw.BuildTribeURL(ctx.server.CoordsTranslation, version.Host, village.Player.Tribe.ID) tribeURL = twurlbuilder.BuildTribeURL(ctx.server.CoordsTranslation, version.Host, village.Player.Tribe.ID)
} }
msg.Append(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ msg.Append(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{

View File

@ -2,17 +2,19 @@ package discord
import ( import (
"context" "context"
"fmt" "github.com/pkg/errors"
"strings" "strings"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/tribalwarshelp/dcbot/message" "github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/tribalwarshelp/dcbot/group" "github.com/tribalwarshelp/dcbot/group"
"github.com/tribalwarshelp/dcbot/models" "github.com/tribalwarshelp/dcbot/models"
"github.com/tribalwarshelp/dcbot/observation" "github.com/tribalwarshelp/dcbot/observation"
"github.com/tribalwarshelp/dcbot/server" "github.com/tribalwarshelp/dcbot/server"
"github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
) )
@ -145,7 +147,7 @@ func (s *Session) init() error {
err := s.dg.Open() err := s.dg.Open()
if err != nil { if err != nil {
return fmt.Errorf("error opening ws connection: %s", err.Error()) return errors.Wrap(err, "error opening ws connection")
} }
if err := s.UpdateStatus(s.cfg.Status); err != nil { if err := s.UpdateStatus(s.cfg.Status); err != nil {
@ -174,7 +176,7 @@ func (s *Session) SendEmbed(channelID string, message *discordgo.MessageEmbed) e
baseNumberOfCharacters += len(message.Footer.Text) baseNumberOfCharacters += len(message.Footer.Text)
} }
splittedFields := [][]*discordgo.MessageEmbedField{} var splittedFields [][]*discordgo.MessageEmbedField
characters := baseNumberOfCharacters characters := baseNumberOfCharacters
fromIndex := 0 fromIndex := 0
fieldsLen := len(fields) fieldsLen := len(fields)
@ -229,23 +231,23 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre
return return
} }
splitted := strings.Split(m.Content, " ") parts := strings.Split(m.Content, " ")
args := splitted[1:] args := parts[1:]
server := &models.Server{ svr := &models.Server{
ID: m.GuildID, ID: m.GuildID,
Lang: message.GetDefaultLanguage().String(), Lang: message.GetDefaultLanguage().String(),
} }
if server.ID != "" { if svr.ID != "" {
if err := s.cfg.ServerRepository.Store(context.Background(), server); err != nil { if err := s.cfg.ServerRepository.Store(context.Background(), svr); err != nil {
return return
} }
} }
ctx := &commandCtx{ ctx := &commandCtx{
server: server, server: svr,
localizer: message.NewLocalizer(server.Lang), localizer: message.NewLocalizer(svr.Lang),
} }
cmd := Command(splitted[0]) cmd := Command(parts[0])
h := s.handlers.find(cmd) h := s.handlers.find(cmd)
if h != nil { if h != nil {
if h.requireAdmPermissions { if h.requireAdmPermissions {
@ -259,14 +261,14 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre
} }
log. log.
WithFields(logrus.Fields{ WithFields(logrus.Fields{
"serverID": server.ID, "serverID": svr.ID,
"lang": server.Lang, "lang": svr.Lang,
"command": cmd, "command": cmd,
"args": args, "args": args,
"authorID": m.Author.ID, "authorID": m.Author.ID,
"authorUsername": m.Author.Username, "authorUsername": m.Author.Username,
}). }).
Info("handleNewMessage: Executing command") Info("handleNewMessage: Executing command...")
h.fn(ctx, m, args...) h.fn(ctx, m, args...)
return return
} }

View File

@ -3,18 +3,19 @@ package discord
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/tribalwarshelp/shared/tw/twmodel"
"github.com/tribalwarshelp/shared/tw/twurlbuilder"
"strconv" "strconv"
"strings" "strings"
"github.com/tribalwarshelp/golang-sdk/sdk" "github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/tribalwarshelp/shared/tw"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/tribalwarshelp/dcbot/message" "github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/dcbot/models" "github.com/tribalwarshelp/dcbot/models"
"github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/dcbot/tw/twutil"
shared_models "github.com/tribalwarshelp/shared/models"
) )
const ( const (
@ -180,7 +181,7 @@ func (s *Session) handleConqueredVillagesCommand(ctx *commandCtx, m *discordgo.M
m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpConqueredVillages, MessageID: message.HelpConqueredVillages,
DefaultMessage: message.FallbackMsg(message.HelpConqueredVillages, DefaultMessage: message.FallbackMsg(message.HelpConqueredVillages,
"**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about conquered village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications."), "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about conquered village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Command": ConqueredVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "Command": ConqueredVillagesCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
@ -226,7 +227,7 @@ func (s *Session) handleConqueredVillagesCommand(ctx *commandCtx, m *discordgo.M
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.ConqueredVillagesSuccess, MessageID: message.ConqueredVillagesSuccess,
DefaultMessage: message.FallbackMsg(message.ConqueredVillagesSuccess, DefaultMessage: message.FallbackMsg(message.ConqueredVillagesSuccess,
"{{.Mention}} Channel changed successfully."), "{{.Mention}} The channel has been successfully set."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Mention": m.Author.Mention(), "Mention": m.Author.Mention(),
}, },
@ -302,7 +303,7 @@ func (s *Session) handleLostVillagesCommand(ctx *commandCtx, m *discordgo.Messag
m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ m.Author.Mention()+" "+ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpLostVillages, MessageID: message.HelpLostVillages,
DefaultMessage: message.FallbackMsg(message.HelpLostVillages, DefaultMessage: message.FallbackMsg(message.HelpLostVillages,
"**{{.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."), "**{{.Command}}** [group id from {{.GroupsCommand}}] sets the channel on which notifications about lost village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Command": LostVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "Command": LostVillagesCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
@ -349,7 +350,7 @@ func (s *Session) handleLostVillagesCommand(ctx *commandCtx, m *discordgo.Messag
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.LostVillagesSuccess, MessageID: message.LostVillagesSuccess,
DefaultMessage: message.FallbackMsg(message.LostVillagesSuccess, DefaultMessage: message.FallbackMsg(message.LostVillagesSuccess,
"{{.Mention}} Channel changed successfully."), "{{.Mention}} The channel has been successfully set."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Mention": m.Author.Mention(), "Mention": m.Author.Mention(),
}, },
@ -476,7 +477,7 @@ func (s *Session) handleObserveCommand(ctx *commandCtx, m *discordgo.MessageCrea
})) }))
return return
} }
if server.Status == shared_models.ServerStatusClosed { if server.Status == twmodel.ServerStatusClosed {
s.SendMessage(m.ChannelID, s.SendMessage(m.ChannelID,
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.ObserveServerIsClosed, MessageID: message.ObserveServerIsClosed,
@ -488,12 +489,12 @@ func (s *Session) handleObserveCommand(ctx *commandCtx, m *discordgo.MessageCrea
return return
} }
var tribe *shared_models.Tribe var tribe *twmodel.Tribe
if tribeID > 0 { if tribeID > 0 {
tribe, err = s.cfg.API.Tribe.Read(server.Key, tribeID) tribe, err = s.cfg.API.Tribe.Read(server.Key, tribeID)
} else { } else {
list := &sdk.TribeList{} list := &sdk.TribeList{}
list, err = s.cfg.API.Tribe.Browse(server.Key, 1, 0, []string{}, &shared_models.TribeFilter{ list, err = s.cfg.API.Tribe.Browse(server.Key, 1, 0, []string{}, &twmodel.TribeFilter{
Tag: []string{tribeTag}, Tag: []string{tribeTag},
}) })
if list != nil && list.Items != nil && len(list.Items) > 0 { if list != nil && list.Items != nil && len(list.Items) > 0 {
@ -548,7 +549,7 @@ func (s *Session) handleObserveCommand(ctx *commandCtx, m *discordgo.MessageCrea
s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.ObserveSuccess, MessageID: message.ObserveSuccess,
DefaultMessage: message.FallbackMsg(message.ObserveSuccess, "{{.Mention}} Added."), DefaultMessage: message.FallbackMsg(message.ObserveSuccess, "{{.Mention}} The tribe has been added to the group."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Mention": m.Author.Mention(), "Mention": m.Author.Mention(),
}, },
@ -619,7 +620,7 @@ func (s *Session) handleDeleteObservationCommand(ctx *commandCtx, m *discordgo.M
s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.DeleteObservationSuccess, MessageID: message.DeleteObservationSuccess,
DefaultMessage: message.FallbackMsg(message.DeleteObservationSuccess, "{{.Mention}} Deleted."), DefaultMessage: message.FallbackMsg(message.DeleteObservationSuccess, "{{.Mention}} The tribe has been removed from the group."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Mention": m.Author.Mention(), "Mention": m.Author.Mention(),
}, },
@ -687,10 +688,10 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag
} }
tribeIDsByServer := make(map[string][]int) tribeIDsByServer := make(map[string][]int)
versionCodes := []shared_models.VersionCode{} versionCodes := []twmodel.VersionCode{}
for _, observation := range observations { for _, observation := range observations {
tribeIDsByServer[observation.Server] = append(tribeIDsByServer[observation.Server], observation.TribeID) tribeIDsByServer[observation.Server] = append(tribeIDsByServer[observation.Server], observation.TribeID)
currentCode := tw.VersionCodeFromServerKey(observation.Server) currentCode := twmodel.VersionCodeFromServerKey(observation.Server)
unique := true unique := true
for _, code := range versionCodes { for _, code := range versionCodes {
if code == currentCode { if code == currentCode {
@ -703,7 +704,7 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag
} }
} }
for server, tribeIDs := range tribeIDsByServer { for server, tribeIDs := range tribeIDsByServer {
list, err := s.cfg.API.Tribe.Browse(server, 0, 0, []string{}, &shared_models.TribeFilter{ list, err := s.cfg.API.Tribe.Browse(server, 0, 0, []string{}, &twmodel.TribeFilter{
ID: tribeIDs, ID: tribeIDs,
}) })
if err != nil { if err != nil {
@ -727,7 +728,7 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag
} }
} }
} }
versionList, err := s.cfg.API.Version.Browse(0, 0, []string{}, &shared_models.VersionFilter{ versionList, err := s.cfg.API.Version.Browse(0, 0, []string{}, &twmodel.VersionFilter{
Code: versionCodes, Code: versionCodes,
}) })
@ -740,10 +741,10 @@ func (s *Session) handleObservationsCommand(ctx *commandCtx, m *discordgo.Messag
if observation.Tribe != nil { if observation.Tribe != nil {
tag = observation.Tribe.Tag tag = observation.Tribe.Tag
} }
version := utils.FindVersionByCode(versionList.Items, tw.VersionCodeFromServerKey(observation.Server)) version := twutil.FindVersionByCode(versionList.Items, twmodel.VersionCodeFromServerKey(observation.Server))
tribeURL := "" tribeURL := ""
if version != nil { if version != nil {
tribeURL = tw.BuildTribeURL(observation.Server, version.Host, observation.TribeID) tribeURL = twurlbuilder.BuildTribeURL(observation.Server, version.Host, observation.TribeID)
} }
msg.Append(fmt.Sprintf("**%d** | %d - %s - %s\n", i+1, observation.ID, msg.Append(fmt.Sprintf("**%d** | %d - %s - %s\n", i+1, observation.ID,
observation.Server, observation.Server,
@ -969,7 +970,7 @@ func (s *Session) handleShowInternalsCommand(ctx *commandCtx, m *discordgo.Messa
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.ShowInternalsSuccess2, MessageID: message.ShowInternalsSuccess2,
DefaultMessage: message.FallbackMsg(message.ShowInternalsSuccess2, DefaultMessage: message.FallbackMsg(message.ShowInternalsSuccess2,
"{{.Mention}} Enabled notifications about internals."), "{{.Mention}} Notifications about internals have been enabled."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Mention": m.Author.Mention(), "Mention": m.Author.Mention(),
}, },

View File

@ -2,6 +2,8 @@ package discord
import ( import (
"fmt" "fmt"
"github.com/tribalwarshelp/shared/tw/twmodel"
"github.com/tribalwarshelp/shared/tw/twurlbuilder"
"math" "math"
"strconv" "strconv"
"strings" "strings"
@ -9,8 +11,6 @@ import (
"github.com/tribalwarshelp/dcbot/message" "github.com/tribalwarshelp/dcbot/message"
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
shared_models "github.com/tribalwarshelp/shared/models"
"github.com/tribalwarshelp/shared/tw"
"github.com/bwmarrin/discordgo" "github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize" "github.com/dustin/go-humanize"
@ -163,7 +163,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate,
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpConqueredVillages, MessageID: message.HelpConqueredVillages,
DefaultMessage: message.FallbackMsg(message.HelpConqueredVillages, DefaultMessage: message.FallbackMsg(message.HelpConqueredVillages,
"**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about conquered village will show. IMPORTANT! Call this command on the channel you want to display these notifications."), "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about conquered village will be displayed. IMPORTANT! Call this command on the channel you want to display these notifications."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Command": ConqueredVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "Command": ConqueredVillagesCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
@ -191,7 +191,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate,
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpLostVillages, MessageID: message.HelpLostVillages,
DefaultMessage: message.FallbackMsg(message.HelpLostVillages, DefaultMessage: message.FallbackMsg(message.HelpLostVillages,
"**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about lost village will show. IMPORTANT! Call this command on the channel you want to display these notifications."), "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about lost village will be displayed. IMPORTANT! Call this command on the channel you want to display these notifications."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Command": LostVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "Command": LostVillagesCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
@ -200,7 +200,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate,
ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpDisableLostVillages, MessageID: message.HelpDisableLostVillages,
DefaultMessage: message.FallbackMsg(message.HelpDisableLostVillages, DefaultMessage: message.FallbackMsg(message.HelpDisableLostVillages,
"**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about lost village will show. IMPORTANT! Call this command on the channel you want to display these notifications."), "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about lost village will be displayed. IMPORTANT! Call this command on the channel you want to display these notifications."),
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Command": DisableLostVillagesCommand.WithPrefix(s.cfg.CommandPrefix), "Command": DisableLostVillagesCommand.WithPrefix(s.cfg.CommandPrefix),
"GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix), "GroupsCommand": GroupsCommand.WithPrefix(s.cfg.CommandPrefix),
@ -255,7 +255,7 @@ func (s *Session) handleHelpCommand(ctx *commandCtx, m *discordgo.MessageCreate,
SetURL("https://dcbot.tribalwarshelp.com/"). SetURL("https://dcbot.tribalwarshelp.com/").
SetDescription(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ SetDescription(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpDescription, MessageID: message.HelpDescription,
DefaultMessage: message.FallbackMsg(message.HelpDescription, "Commands offered by bot"), DefaultMessage: message.FallbackMsg(message.HelpDescription, "Command list"),
})). })).
AddField(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ AddField(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: message.HelpForAllUsers, MessageID: message.HelpForAllUsers,
@ -291,8 +291,8 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate
})) }))
return return
} }
ids := []int{} var ids []int
tags := []string{} var tags []string
for _, arg := range args[3:argsLength] { for _, arg := range args[3:argsLength] {
trimmed := strings.TrimSpace(arg) trimmed := strings.TrimSpace(arg)
if trimmed == "" { if trimmed == "" {
@ -319,10 +319,10 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate
exists := true exists := true
limit := 10 limit := 10
offset := (page - 1) * limit offset := (page - 1) * limit
filter := &shared_models.PlayerFilter{ filter := &twmodel.PlayerFilter{
Exists: &exists, Exists: &exists,
TribeFilter: &shared_models.TribeFilter{ TribeFilter: &twmodel.TribeFilter{
Or: &shared_models.TribeFilterOr{ Or: &twmodel.TribeFilterOr{
ID: ids, ID: ids,
Tag: tags, Tag: tags,
}, },
@ -414,7 +414,7 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate
return return
} }
code := tw.VersionCodeFromServerKey(server) code := twmodel.VersionCodeFromServerKey(server)
version, err := s.cfg.API.Version.Read(code) version, err := s.cfg.API.Version.Read(code)
if err != nil || version == nil { if err != nil || version == nil {
s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ s.SendMessage(m.ChannelID, ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
@ -458,7 +458,7 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate
tribeURL := "-" tribeURL := "-"
if player.Tribe != nil { if player.Tribe != nil {
tribeTag = player.Tribe.Tag tribeTag = player.Tribe.Tag
tribeURL = tw.BuildTribeURL(server, version.Host, player.Tribe.ID) tribeURL = twurlbuilder.BuildTribeURL(server, version.Host, player.Tribe.ID)
} }
msg.Append(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{ msg.Append(ctx.localizer.MustLocalize(&i18n.LocalizeConfig{
@ -468,7 +468,7 @@ func (s *Session) handleTribeCommand(ctx *commandCtx, m *discordgo.MessageCreate
TemplateData: map[string]interface{}{ TemplateData: map[string]interface{}{
"Index": offset + i + 1, "Index": offset + i + 1,
"PlayerName": player.Name, "PlayerName": player.Name,
"PlayerURL": tw.BuildPlayerURL(server, version.Host, player.ID), "PlayerURL": twurlbuilder.BuildPlayerURL(server, version.Host, player.ID),
"TribeTag": tribeTag, "TribeTag": tribeTag,
"TribeURL": tribeURL, "TribeURL": tribeURL,
"Rank": rank, "Rank": rank,

7
go.mod
View File

@ -3,7 +3,10 @@ module github.com/tribalwarshelp/dcbot
go 1.16 go 1.16
require ( require (
github.com/Kichiyaki/appmode v0.0.0-20210502105643-0a26207c548d
github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9 github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9
github.com/Kichiyaki/gopgutil/v10 v10.0.0-20210505093434-655fa2df248f
github.com/Kichiyaki/goutil v0.0.0-20210504132659-3d843a787db7
github.com/bwmarrin/discordgo v0.22.0 github.com/bwmarrin/discordgo v0.22.0
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/go-pg/pg/v10 v10.9.1 github.com/go-pg/pg/v10 v10.9.1
@ -12,7 +15,7 @@ require (
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
github.com/robfig/cron/v3 v3.0.1 github.com/robfig/cron/v3 v3.0.1
github.com/sirupsen/logrus v1.8.1 github.com/sirupsen/logrus v1.8.1
github.com/tribalwarshelp/golang-sdk v0.0.0-20210423190639-622eeb3ee870 github.com/tribalwarshelp/golang-sdk v0.0.0-20210505172651-7dc458534a8c
github.com/tribalwarshelp/shared v0.0.0-20210423190057-03d8445d35dc github.com/tribalwarshelp/shared v0.0.0-20210505172413-bf85190fd66d
golang.org/x/text v0.3.3 golang.org/x/text v0.3.3
) )

19
go.sum
View File

@ -2,10 +2,16 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT
github.com/BurntSushi/toml v0.3.0/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.0/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210423175217-c83fa01c60d7 h1:7IdSzhdupqm4AC3UDH9b5gdCDE2SlX6qkVC0zwqAuLA= github.com/Kichiyaki/appmode v0.0.0-20210502105643-0a26207c548d h1:ApX13STtfJc2YPH5D2JnBa6+4AM2vt7a81so/MPr/bA=
github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210423175217-c83fa01c60d7/go.mod h1:ADHVWnGlWcRn1aGthuh7I1Lrn6zzsjkVJju151dXyDw= github.com/Kichiyaki/appmode v0.0.0-20210502105643-0a26207c548d/go.mod h1:41p1KTy/fiVocPnJR2h/iXh2NvWWVBdNoZrN8TWVXUI=
github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9 h1:S/08K0AD4bXYeSPJKei8ZbumDy1JNARZsgYbNZgr9Tk= github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9 h1:S/08K0AD4bXYeSPJKei8ZbumDy1JNARZsgYbNZgr9Tk=
github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9/go.mod h1:ADHVWnGlWcRn1aGthuh7I1Lrn6zzsjkVJju151dXyDw= github.com/Kichiyaki/go-pg-logrus-query-logger/v10 v10.0.0-20210428180109-fb97298564d9/go.mod h1:ADHVWnGlWcRn1aGthuh7I1Lrn6zzsjkVJju151dXyDw=
github.com/Kichiyaki/go-php-serialize v0.0.0-20200601110855-47b6982acf83/go.mod h1:+iGkf5HfOVeRVd9K7qQDucIl+/Kt3MyenMa90b/O/c4=
github.com/Kichiyaki/gopgutil/v10 v10.0.0-20210505093434-655fa2df248f h1:/kJmv8B59cMHdTmsko0RyAOeRC9WpsQPDmLtRXOAU6c=
github.com/Kichiyaki/gopgutil/v10 v10.0.0-20210505093434-655fa2df248f/go.mod h1:MSAEhr8oeK+Rhjhqyl31/8/AI88thYky80OyD8mheDA=
github.com/Kichiyaki/goutil v0.0.0-20210502095630-318d17091eab/go.mod h1:+HhI932Xb0xrCodNcCv5GPiCjLYhDxWhCtlEqMIJhB4=
github.com/Kichiyaki/goutil v0.0.0-20210504132659-3d843a787db7 h1:OU3ZA5H8fHTzaYIw9UBfH3gtWRL0XmnczlhH3E2PjV4=
github.com/Kichiyaki/goutil v0.0.0-20210504132659-3d843a787db7/go.mod h1:+HhI932Xb0xrCodNcCv5GPiCjLYhDxWhCtlEqMIJhB4=
github.com/Kichiyaki/gqlgen-client v0.0.0-20200604145848-274796c104f4 h1:QiOarkkKHdFYI+0m6F1H3rRzP6DqJsKJVLirGXEHGSU= github.com/Kichiyaki/gqlgen-client v0.0.0-20200604145848-274796c104f4 h1:QiOarkkKHdFYI+0m6F1H3rRzP6DqJsKJVLirGXEHGSU=
github.com/Kichiyaki/gqlgen-client v0.0.0-20200604145848-274796c104f4/go.mod h1:weCVl47ZANyeX60sdsSl0bWHf8HWXyVFmlGHHCR/i5M= github.com/Kichiyaki/gqlgen-client v0.0.0-20200604145848-274796c104f4/go.mod h1:weCVl47ZANyeX60sdsSl0bWHf8HWXyVFmlGHHCR/i5M=
github.com/bwmarrin/discordgo v0.22.0 h1:uBxY1HmlVCsW1IuaPjpCGT6A2DBwRn0nvOguQIxDdFM= github.com/bwmarrin/discordgo v0.22.0 h1:uBxY1HmlVCsW1IuaPjpCGT6A2DBwRn0nvOguQIxDdFM=
@ -78,7 +84,6 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@ -90,10 +95,10 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo=
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs= github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs=
github.com/tribalwarshelp/golang-sdk v0.0.0-20210423190639-622eeb3ee870 h1:OHkmBk+KoVL/GEJqi9qpxuga6C0NOC8faam1wE74YWA= github.com/tribalwarshelp/golang-sdk v0.0.0-20210505172651-7dc458534a8c h1:Ip4C8G6zjdHnsHeyuajb5BZeRrls/Ym14Vww8e9jGLM=
github.com/tribalwarshelp/golang-sdk v0.0.0-20210423190639-622eeb3ee870/go.mod h1:OJSOBFIytm2cxZZh4B0x2ucJWQ0vlVu9T61hDrnwJaw= github.com/tribalwarshelp/golang-sdk v0.0.0-20210505172651-7dc458534a8c/go.mod h1:0VNYCWHFE5Szvd/b5RpnhtHdvYwR/6XfB/iFjgPTAtY=
github.com/tribalwarshelp/shared v0.0.0-20210423190057-03d8445d35dc h1:giWPsD/6WTOrQl9KT5AXrrf3KLkHSGuNpWa2CyyaM6w= github.com/tribalwarshelp/shared v0.0.0-20210505172413-bf85190fd66d h1:aMlYOsJbYwKqHx7wAt526eIutV1Q5EnYK6b7lOzvPmk=
github.com/tribalwarshelp/shared v0.0.0-20210423190057-03d8445d35dc/go.mod h1:CDQvesBYmSyGDl5X37xfa+ub55ZbikrHDuIZ4AcfM8I= github.com/tribalwarshelp/shared v0.0.0-20210505172413-bf85190fd66d/go.mod h1:GBnSKQrxL8Nmi3MViIzZVbyP9+ugd28gWArsSvw1iVU=
github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94=
github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ= github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ=
github.com/vmihailenco/msgpack/v5 v5.3.0/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= github.com/vmihailenco/msgpack/v5 v5.3.0/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc=

View File

@ -20,7 +20,7 @@ func NewPgRepo(db *pg.DB) (group.Repository, error) {
IfNotExists: true, IfNotExists: true,
FKConstraints: true, FKConstraints: true,
}); err != nil { }); err != nil {
return nil, errors.Wrap(err, "cannot create 'groups' table") return nil, errors.Wrap(err, "couldn't create the 'groups' table")
} }
return &pgRepo{db}, nil return &pgRepo{db}, nil
} }
@ -52,11 +52,11 @@ func (repo *pgRepo) Update(ctx context.Context, group *models.Group) error {
} }
func (repo *pgRepo) GetByID(ctx context.Context, id int) (*models.Group, error) { func (repo *pgRepo) GetByID(ctx context.Context, id int) (*models.Group, error) {
group := &models.Group{ g := &models.Group{
ID: id, ID: id,
} }
if err := repo. if err := repo.
Model(group). Model(g).
WherePK(). WherePK().
Returning("*"). Returning("*").
Relation("Observations"). Relation("Observations").
@ -64,12 +64,12 @@ func (repo *pgRepo) GetByID(ctx context.Context, id int) (*models.Group, error)
Select(); err != nil { Select(); err != nil {
return nil, err return nil, err
} }
return group, nil return g, nil
} }
func (repo *pgRepo) Fetch(ctx context.Context, f *models.GroupFilter) ([]*models.Group, int, error) { func (repo *pgRepo) Fetch(ctx context.Context, f *models.GroupFilter) ([]*models.Group, int, error) {
var err error var err error
data := []*models.Group{} var data []*models.Group
query := repo.Model(&data).Relation("Server").Relation("Observations").Context(ctx) query := repo.Model(&data).Relation("Server").Relation("Observations").Context(ctx)
if f != nil { if f != nil {
@ -88,7 +88,7 @@ func (repo *pgRepo) Fetch(ctx context.Context, f *models.GroupFilter) ([]*models
} }
func (repo *pgRepo) Delete(ctx context.Context, f *models.GroupFilter) ([]*models.Group, error) { func (repo *pgRepo) Delete(ctx context.Context, f *models.GroupFilter) ([]*models.Group, error) {
data := []*models.Group{} var data []*models.Group
query := repo.Model(&data).Context(ctx) query := repo.Model(&data).Context(ctx)
if f != nil { if f != nil {

70
main.go
View File

@ -1,7 +1,8 @@
package main package main
import ( import (
"log" "github.com/Kichiyaki/appmode"
"github.com/Kichiyaki/goutil/envutil"
"os" "os"
"os/signal" "os/signal"
"path" "path"
@ -16,13 +17,11 @@ import (
_cron "github.com/tribalwarshelp/dcbot/cron" _cron "github.com/tribalwarshelp/dcbot/cron"
"github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/discord"
group_repository "github.com/tribalwarshelp/dcbot/group/repository" grouprepository "github.com/tribalwarshelp/dcbot/group/repository"
observation_repository "github.com/tribalwarshelp/dcbot/observation/repository" observationrepository "github.com/tribalwarshelp/dcbot/observation/repository"
server_repository "github.com/tribalwarshelp/dcbot/server/repository" serverepository "github.com/tribalwarshelp/dcbot/server/repository"
"github.com/tribalwarshelp/shared/mode" "github.com/Kichiyaki/go-pg-logrus-query-logger/v10"
gopglogrusquerylogger "github.com/Kichiyaki/go-pg-logrus-query-logger/v10"
"github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10"
"github.com/joho/godotenv" "github.com/joho/godotenv"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
@ -37,7 +36,7 @@ var status = "tribalwarshelp.com | " + discord.HelpCommand.WithPrefix(commandPre
func init() { func init() {
os.Setenv("TZ", "UTC") os.Setenv("TZ", "UTC")
if mode.Get() == mode.DevelopmentMode { if appmode.Equals(appmode.DevelopmentMode) {
godotenv.Load(".env.local") godotenv.Load(".env.local")
} }
@ -51,17 +50,14 @@ func main() {
} }
dirWithMessages := path.Join(dir, "message", "translations") dirWithMessages := path.Join(dir, "message", "translations")
if err := message.LoadMessages(dirWithMessages); err != nil { if err := message.LoadMessages(dirWithMessages); err != nil {
logrus.Fatal(err) logrus.WithField("dir", dirWithMessages).Fatal(err)
} }
logrus.WithField("dir", dirWithMessages).
WithField("languages", message.LanguageTags()).
Info("Loaded messages")
db := pg.Connect(&pg.Options{ db := pg.Connect(&pg.Options{
User: os.Getenv("DB_USER"), User: envutil.GetenvString("DB_USER"),
Password: os.Getenv("DB_PASSWORD"), Password: envutil.GetenvString("DB_PASSWORD"),
Database: os.Getenv("DB_NAME"), Database: envutil.GetenvString("DB_NAME"),
Addr: os.Getenv("DB_HOST") + ":" + os.Getenv("DB_PORT"), Addr: envutil.GetenvString("DB_HOST") + ":" + os.Getenv("DB_PORT"),
}) })
defer func() { defer func() {
if err := db.Close(); err != nil { if err := db.Close(); err != nil {
@ -75,23 +71,23 @@ func main() {
}) })
} }
serverRepo, err := server_repository.NewPgRepo(db) serverRepo, err := serverepository.NewPgRepo(db)
if err != nil { if err != nil {
logrus.Fatal(err) logrus.Fatal(err)
} }
groupRepo, err := group_repository.NewPgRepo(db) groupRepo, err := grouprepository.NewPgRepo(db)
if err != nil { if err != nil {
logrus.Fatal(err) logrus.Fatal(err)
} }
observationRepo, err := observation_repository.NewPgRepo(db) observationRepo, err := observationrepository.NewPgRepo(db)
if err != nil { if err != nil {
logrus.Fatal(err) logrus.Fatal(err)
} }
api := sdk.New(os.Getenv("API_URL")) api := sdk.New(envutil.GetenvString("API_URL"))
sess, err := discord.New(discord.SessionConfig{ sess, err := discord.New(discord.SessionConfig{
Token: os.Getenv("BOT_TOKEN"), Token: envutil.GetenvString("BOT_TOKEN"),
CommandPrefix: commandPrefix, CommandPrefix: commandPrefix,
Status: status, Status: status,
ObservationRepository: observationRepo, ObservationRepository: observationRepo,
@ -100,18 +96,23 @@ func main() {
API: api, API: api,
}) })
if err != nil { if err != nil {
logrus.Fatal(err) logrus.
WithFields(logrus.Fields{
"api": envutil.GetenvString("API_URL"),
"commandPrefix": commandPrefix,
"status": status,
}).
Fatal(err)
} }
defer sess.Close() defer sess.Close()
logrus.WithFields(logrus.Fields{
"api": os.Getenv("API_URL"),
"commandPrefix": commandPrefix,
"status": status,
}).Info("The Discord session has been initialized")
c := cron.New(cron.WithChain( c := cron.New(
cron.SkipIfStillRunning(cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))), cron.WithChain(
)) cron.SkipIfStillRunning(
cron.PrintfLogger(logrus.StandardLogger()),
),
),
)
_cron.Attach(c, _cron.Config{ _cron.Attach(c, _cron.Config{
ServerRepo: serverRepo, ServerRepo: serverRepo,
ObservationRepo: observationRepo, ObservationRepo: observationRepo,
@ -122,24 +123,23 @@ func main() {
}) })
c.Start() c.Start()
defer c.Stop() defer c.Stop()
logrus.Info("Started the cron scheduler")
logrus.Info("Bot is running!") logrus.Info("The bot is up and running!")
channel := make(chan os.Signal, 1) channel := make(chan os.Signal, 1)
signal.Notify(channel, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGINT) signal.Notify(channel, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGINT)
<-channel <-channel
logrus.Info("shutting down") logrus.Info("shutting down...")
} }
func setupLogger() { func setupLogger() {
if mode.Get() == mode.DevelopmentMode { if appmode.Equals(appmode.DevelopmentMode) {
logrus.SetLevel(logrus.DebugLevel) logrus.SetLevel(logrus.DebugLevel)
} }
timestampFormat := "2006-01-02 15:04:05" timestampFormat := "2006-01-02 15:04:05"
if mode.Get() == mode.ProductionMode { if appmode.Equals(appmode.ProductionMode) {
customFormatter := new(logrus.JSONFormatter) customFormatter := new(logrus.JSONFormatter)
customFormatter.TimestampFormat = timestampFormat customFormatter.TimestampFormat = timestampFormat
logrus.SetFormatter(customFormatter) logrus.SetFormatter(customFormatter)

View File

@ -1,6 +1,6 @@
{ {
"help.title": "Help", "help.title": "Help",
"help.description": "Commands offered by the bot.", "help.description": "Command list",
"help.footer": "", "help.footer": "",
"help.forAllUsers": "For everyone", "help.forAllUsers": "For everyone",
"help.forAdmins": "For admins", "help.forAdmins": "For admins",
@ -17,9 +17,9 @@
"help.observe": "**{{.Command}}** [group id from {{.GroupsCommand}}] [server] [tribe id or tribe tag] - adds a tribe to the observation group.", "help.observe": "**{{.Command}}** [group id from {{.GroupsCommand}}] [server] [tribe id or tribe tag] - adds a tribe to the observation group.",
"help.observations": "**{{.Command}}** [group id from {{.GroupsCommand}}] - shows a list of monitored tribes added to this group.", "help.observations": "**{{.Command}}** [group id from {{.GroupsCommand}}] - shows a list of monitored tribes added to this group.",
"help.deleteobservation": "**{{.Command}}** [group id from {{.GroupsCommand}}] [id from {{.ObservationsCommand}}] - removes a tribe from the observation group.", "help.deleteobservation": "**{{.Command}}** [group id from {{.GroupsCommand}}] [id from {{.ObservationsCommand}}] - removes a tribe from the observation group.",
"help.conqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - changes the channel on which notifications about conquered village will show. **IMPORTANT!** Run this command on the channel you want to display these notifications.", "help.conqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about conquered village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications.",
"help.disableconqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disables notifications about conquered villages.", "help.disableconqueredvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disables notifications about conquered villages.",
"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.lostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - sets the channel on which notifications about lost village will be displayed. **IMPORTANT!** Run this command on the channel you want to display these notifications.",
"help.disablelostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disables notifications about lost villages.", "help.disablelostvillages": "**{{.Command}}** [group id from {{.GroupsCommand}}] - disables notifications about lost villages.",
"help.changelanguage": "**{{.Command}}** [{{.Languages}}] - changes language.", "help.changelanguage": "**{{.Command}}** [{{.Languages}}] - changes language.",
"help.showinternals": "**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about in-group/in-tribe conquering.", "help.showinternals": "**{{.Command}}** [group id from {{.GroupsCommand}}] - enables/disables notifications about in-group/in-tribe conquering.",
@ -49,7 +49,7 @@
"conqueredVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "conqueredVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.",
"conqueredVillages.groupNotFound": "{{.Mention}} Group not found.", "conqueredVillages.groupNotFound": "{{.Mention}} Group not found.",
"conqueredVillages.success": "{{.Mention}} Channel changed successfully.", "conqueredVillages.success": "{{.Mention}} The channel has been successfully set.",
"disableConqueredVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "disableConqueredVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.",
"disableConqueredVillages.groupNotFound": "{{.Mention}} Group not found.", "disableConqueredVillages.groupNotFound": "{{.Mention}} Group not found.",
@ -57,7 +57,7 @@
"lostVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "lostVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.",
"lostVillages.groupNotFound": "{{.Mention}} Group not found.", "lostVillages.groupNotFound": "{{.Mention}} Group not found.",
"lostVillages.success": "{{.Mention}} Channel changed successfully.", "lostVillages.success": "{{.Mention}} The channel has been successfully set.",
"disableLostVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.", "disableLostVillages.invalidID": "{{.Mention}} The group ID must be a number greater than 0.",
"disableLostVillages.groupNotFound": "{{.Mention}} Group not found.", "disableLostVillages.groupNotFound": "{{.Mention}} Group not found.",
@ -70,12 +70,12 @@
"observe.groupNotFound": "{{.Mention}} Group not found.", "observe.groupNotFound": "{{.Mention}} Group not found.",
"observe.tribeNotFound": "{{.Mention}} Tribe not found.", "observe.tribeNotFound": "{{.Mention}} Tribe not found.",
"observe.observationLimitHasBeenReached": "{{.Mention}} The observation limit for this group has been reached ({{.Total}}/{{.Limit}}).", "observe.observationLimitHasBeenReached": "{{.Mention}} The observation limit for this group has been reached ({{.Total}}/{{.Limit}}).",
"observe.success": "{{.Mention}} Added.", "observe.success": "{{.Mention}} The tribe has been added to the group.",
"deleteObservation.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.", "deleteObservation.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.",
"deleteObservation.invalidObservationID": "{{.Mention}} The observation ID must be a number greater than 0.", "deleteObservation.invalidObservationID": "{{.Mention}} The observation ID must be a number greater than 0.",
"deleteObservation.groupNotFound": "{{.Mention}} Group not found.", "deleteObservation.groupNotFound": "{{.Mention}} Group not found.",
"deleteObservation.success": "{{.Mention}} Deleted.", "deleteObservation.success": "{{.Mention}} The tribe has been removed from the group.",
"observations.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.", "observations.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.",
"observations.groupNotFound": "{{.Mention}} Group not found.", "observations.groupNotFound": "{{.Mention}} Group not found.",
@ -92,7 +92,7 @@
"showInternals.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.", "showInternals.invalidGroupID": "{{.Mention}} The group ID must be a number greater than 0.",
"showInternals.groupNotFound": "{{.Mention}} Group not found.", "showInternals.groupNotFound": "{{.Mention}} Group not found.",
"showInternals.success_1": "{{.Mention}} Notifications about internals will no longer show up.", "showInternals.success_1": "{{.Mention}} Notifications about internals will no longer show up.",
"showInternals.success_2": "{{.Mention}} Enabled notifications about internals.", "showInternals.success_2": "{{.Mention}} Notifications about internals have been enabled.",
"coordsTranslation.title": "Villages", "coordsTranslation.title": "Villages",
"coordsTranslation.message": "{{.Village}} owned by {{.Player}} (Tribe: {{.Tribe}}).", "coordsTranslation.message": "{{.Village}} owned by {{.Player}} (Tribe: {{.Tribe}}).",

View File

@ -1,6 +1,6 @@
{ {
"help.title": "Pomoc", "help.title": "Pomoc",
"help.description": "Komendy oferowane przez bota.", "help.description": "Lista komend",
"help.footer": "", "help.footer": "",
"help.forAllUsers": "Dla wszystkich", "help.forAllUsers": "Dla wszystkich",
"help.forAdmins": "Dla adminów", "help.forAdmins": "Dla adminów",
@ -17,9 +17,9 @@
"help.observe": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] [serwer] [id lub skrót plemienia] - dodaje plemię do grupy.", "help.observe": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] [serwer] [id lub skrót plemienia] - dodaje plemię do grupy.",
"help.observations": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - pokazuje plemiona należące do wybranej grupy.", "help.observations": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - pokazuje plemiona należące do wybranej grupy.",
"help.deleteobservation": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] [id from {{.ObservationsCommand}}] - usuwa plemię z grupy.", "help.deleteobservation": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] [id from {{.ObservationsCommand}}] - usuwa plemię z grupy.",
"help.conqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - zmienia kanał na którym będą się pojawiać informację o podbitych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.", "help.conqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - ustawia kanał na którym będą się pojawiać informację o podbitych wioskach w danej grupie. **WAŻNE!** Wywołaj tę komendę na kanale na którym chcesz dostawać te powiadomienia.",
"help.disableconqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - wyłącza powiadomienia o podbitych wioskach w danej grupie.", "help.disableconqueredvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - wyłącza powiadomienia o podbitych wioskach w danej grupie.",
"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.lostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - ustawia 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.disablelostvillages": "**{{.Command}}** [id grupy z {{.GroupsCommand}}] - wyłącza powiadomienia o straconych wioskach w danej grupie.",
"help.changelanguage": "**{{.Command}}** [{{.Languages}}] - zmień język bota.", "help.changelanguage": "**{{.Command}}** [{{.Languages}}] - zmień język bota.",
"help.showinternals": "**{{.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.",
@ -49,7 +49,7 @@
"conqueredVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "conqueredVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"conqueredVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "conqueredVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
"conqueredVillages.success": "{{.Mention}} Kanał został pomyślnie zmieniony.", "conqueredVillages.success": "{{.Mention}} Kanał został pomyślnie ustawiony.",
"disableConqueredVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "disableConqueredVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"disableConqueredVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "disableConqueredVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
@ -57,7 +57,7 @@
"lostVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "lostVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"lostVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "lostVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
"lostVillages.success": "{{.Mention}} Kanał został pomyślnie zmieniony.", "lostVillages.success": "{{.Mention}} Kanał został pomyślnie ustawiony.",
"disableLostVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "disableLostVillages.invalidID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"disableLostVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "disableLostVillages.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
@ -70,12 +70,12 @@
"observe.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "observe.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
"observe.tribeNotFound": "{{.Mention}} Plemię nie zostało znalezione.", "observe.tribeNotFound": "{{.Mention}} Plemię nie zostało znalezione.",
"observe.observationLimitHasBeenReached": "{{.Mention}} Limit obserwacji dla grupy został osiągnięty ({{.Total}}/{{.Limit}}).", "observe.observationLimitHasBeenReached": "{{.Mention}} Limit obserwacji dla grupy został osiągnięty ({{.Total}}/{{.Limit}}).",
"observe.success": "{{.Mention}} Dodano.", "observe.success": "{{.Mention}} Dodano plemię do obserwowanych.",
"deleteObservation.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "deleteObservation.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"deleteObservation.invalidObservationID": "{{.Mention}} ID obserwacji musi być liczbą większą od 0.", "deleteObservation.invalidObservationID": "{{.Mention}} ID obserwacji musi być liczbą większą od 0.",
"deleteObservation.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "deleteObservation.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
"deleteObservation.success": "{{.Mention}} Usunięto.", "deleteObservation.success": "{{.Mention}} Usunięto plemię z grupy.",
"observations.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.", "observations.invalidGroupID": "{{.Mention}} ID grupy musi być liczbą większą od 0.",
"observations.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.", "observations.groupNotFound": "{{.Mention}} Grupa nie została znaleziona.",
@ -109,5 +109,5 @@
"pagination.labelDisplayedPage": "Strona: {{.Page}} z {{.MaxPage}}", "pagination.labelDisplayedPage": "Strona: {{.Page}} z {{.MaxPage}}",
"internalServerError": "{{.Mention}} Wewnętrzny błąd serwera, prosimy spróbować później." "internalServerError": "{{.Mention}} Wewnętrzny błąd serwera, prosimy spróbować później."
} }

View File

@ -1,6 +1,7 @@
package models package models
import ( import (
"github.com/Kichiyaki/gopgutil/v10"
"github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm" "github.com/go-pg/pg/v10/orm"
) )
@ -22,20 +23,16 @@ type GroupFilter struct {
DefaultFilter DefaultFilter
} }
func (f *GroupFilter) ApplyWithPrefix(prefix string) func(q *orm.Query) (*orm.Query, error) { func (f *GroupFilter) ApplyWithAlias(q *orm.Query, prefix string) (*orm.Query, error) {
return func(q *orm.Query) (*orm.Query, error) { if len(f.ID) > 0 {
if len(f.ID) > 0 { q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("id", prefix), pg.Array(f.ID))
column := addPrefixToColumnName("id", prefix)
q = q.Where(column+" = ANY(?)", pg.Array(f.ID))
}
if len(f.ServerID) > 0 {
column := addPrefixToColumnName("server_id", prefix)
q = q.Where(column+" = ANY(?)", pg.Array(f.ServerID))
}
return f.DefaultFilter.Apply(q)
} }
if len(f.ServerID) > 0 {
q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("server_id", prefix), pg.Array(f.ServerID))
}
return f.DefaultFilter.Apply(q)
} }
func (f *GroupFilter) Apply(q *orm.Query) (*orm.Query, error) { func (f *GroupFilter) Apply(q *orm.Query) (*orm.Query, error) {
return f.ApplyWithPrefix("group")(q) return f.ApplyWithAlias(q, "group")
} }

View File

@ -1,16 +0,0 @@
package models
import "strings"
func addPrefixToColumnName(column, prefix string) string {
if prefix != "" && !strings.HasPrefix(column, prefix+".") {
column = wrapStringInDoubleQuotes(prefix) + "." + wrapStringInDoubleQuotes(column)
} else {
column = wrapStringInDoubleQuotes(column)
}
return column
}
func wrapStringInDoubleQuotes(str string) string {
return `"` + str + `"`
}

View File

@ -1,23 +1,24 @@
package models package models
import ( import (
"github.com/Kichiyaki/gopgutil/v10"
"github.com/tribalwarshelp/shared/tw/twmodel"
"time" "time"
"github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm" "github.com/go-pg/pg/v10/orm"
shared_models "github.com/tribalwarshelp/shared/models"
) )
type Observation struct { type Observation struct {
tableName struct{} `pg:",alias:observation"` tableName struct{} `pg:",alias:observation"`
ID int `json:"id" gqlgen:"id"` ID int `json:"id" gqlgen:"id"`
Server string `pg:"unique:group_1,use_zero" json:"server" gqlgen:"server"` Server string `pg:"unique:group_1,use_zero" json:"server" gqlgen:"server"`
TribeID int `pg:"unique:group_1,use_zero" json:"tribeID" gqlgen:"tribeID"` TribeID int `pg:"unique:group_1,use_zero" json:"tribeID" gqlgen:"tribeID"`
Tribe *shared_models.Tribe `pg:"-"` Tribe *twmodel.Tribe `pg:"-"`
GroupID int `pg:"on_delete:CASCADE,unique:group_1,use_zero" json:"groupID" gqlgen:"groupID"` GroupID int `pg:"on_delete:CASCADE,unique:group_1,use_zero" json:"groupID" gqlgen:"groupID"`
Group *Group `json:"group,omitempty" gqlgen:"group" pg:"rel:has-one"` Group *Group `json:"group,omitempty" gqlgen:"group" pg:"rel:has-one"`
CreatedAt time.Time `pg:"default:now()" json:"createdAt" gqlgen:"createdAt" xml:"createdAt"` CreatedAt time.Time `pg:"default:now()" json:"createdAt" gqlgen:"createdAt" xml:"createdAt"`
} }
type Observations []*Observation type Observations []*Observation
@ -38,24 +39,19 @@ type ObservationFilter struct {
DefaultFilter DefaultFilter
} }
func (f *ObservationFilter) ApplyWithPrefix(prefix string) func(q *orm.Query) (*orm.Query, error) { func (f *ObservationFilter) ApplyWithAlias(q *orm.Query, alias string) (*orm.Query, error) {
return func(q *orm.Query) (*orm.Query, error) { if len(f.ID) > 0 {
if len(f.ID) > 0 { q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("id", alias), pg.Array(f.ID))
column := addPrefixToColumnName("id", prefix)
q = q.Where(column+" = ANY(?)", pg.Array(f.ID))
}
if len(f.Server) > 0 {
column := addPrefixToColumnName("server", prefix)
q = q.Where(column+" = ANY(?)", pg.Array(f.Server))
}
if len(f.GroupID) > 0 {
column := addPrefixToColumnName("group_id", prefix)
q = q.Where(column+" = ANY(?)", pg.Array(f.GroupID))
}
return f.DefaultFilter.Apply(q)
} }
if len(f.Server) > 0 {
q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("server", alias), pg.Array(f.Server))
}
if len(f.GroupID) > 0 {
q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("group_id", alias), pg.Array(f.GroupID))
}
return f.DefaultFilter.Apply(q)
} }
func (f *ObservationFilter) Apply(q *orm.Query) (*orm.Query, error) { func (f *ObservationFilter) Apply(q *orm.Query) (*orm.Query, error) {
return f.ApplyWithPrefix("observation")(q) return f.ApplyWithAlias(q, "observation")
} }

View File

@ -1,6 +1,7 @@
package models package models
import ( import (
"github.com/Kichiyaki/gopgutil/v10"
"github.com/go-pg/pg/v10" "github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm" "github.com/go-pg/pg/v10/orm"
) )
@ -19,16 +20,13 @@ type ServerFilter struct {
DefaultFilter DefaultFilter
} }
func (f *ServerFilter) ApplyWithPrefix(prefix string) func(q *orm.Query) (*orm.Query, error) { func (f *ServerFilter) ApplyWithAlias(q *orm.Query, alias string) (*orm.Query, error) {
return func(q *orm.Query) (*orm.Query, error) { if len(f.ID) > 0 {
if len(f.ID) > 0 { q = q.Where(gopgutil.BuildConditionArray("?"), gopgutil.AddAliasToColumnName("id", alias), pg.Array(f.ID))
column := addPrefixToColumnName("id", prefix)
q = q.Where(column+" = ANY(?)", pg.Array(f.ID))
}
return f.DefaultFilter.Apply(q)
} }
return f.DefaultFilter.Apply(q)
} }
func (f *ServerFilter) Apply(q *orm.Query) (*orm.Query, error) { func (f *ServerFilter) Apply(q *orm.Query) (*orm.Query, error) {
return f.ApplyWithPrefix("server")(q) return f.ApplyWithAlias(q, "server")
} }

View File

@ -20,7 +20,7 @@ func NewPgRepo(db *pg.DB) (observation.Repository, error) {
IfNotExists: true, IfNotExists: true,
FKConstraints: true, FKConstraints: true,
}); err != nil { }); err != nil {
return nil, errors.Wrap(err, "cannot create 'observations' table") return nil, errors.Wrap(err, "couldn't create the 'observations' table")
} }
return &pgRepo{db}, nil return &pgRepo{db}, nil
} }
@ -53,7 +53,7 @@ func (repo *pgRepo) Update(ctx context.Context, observation *models.Observation)
func (repo *pgRepo) Fetch(ctx context.Context, f *models.ObservationFilter) ([]*models.Observation, int, error) { func (repo *pgRepo) Fetch(ctx context.Context, f *models.ObservationFilter) ([]*models.Observation, int, error) {
var err error var err error
data := []*models.Observation{} var data []*models.Observation
query := repo.Model(&data).Context(ctx) query := repo.Model(&data).Context(ctx)
if f != nil { if f != nil {
@ -72,10 +72,9 @@ func (repo *pgRepo) Fetch(ctx context.Context, f *models.ObservationFilter) ([]*
} }
func (repo *pgRepo) FetchServers(ctx context.Context) ([]string, error) { func (repo *pgRepo) FetchServers(ctx context.Context) ([]string, error) {
data := []*models.Observation{} var res []string
res := []string{}
err := repo. err := repo.
Model(&data). Model(&models.Observation{}).
Column("server"). Column("server").
Context(ctx). Context(ctx).
Group("server"). Group("server").
@ -85,7 +84,7 @@ func (repo *pgRepo) FetchServers(ctx context.Context) ([]string, error) {
} }
func (repo *pgRepo) Delete(ctx context.Context, f *models.ObservationFilter) ([]*models.Observation, error) { func (repo *pgRepo) Delete(ctx context.Context, f *models.ObservationFilter) ([]*models.Observation, error) {
data := []*models.Observation{} var data []*models.Observation
query := repo.Model(&data).Context(ctx) query := repo.Model(&data).Context(ctx)
if f != nil { if f != nil {

View File

@ -19,7 +19,7 @@ func NewPgRepo(db *pg.DB) (server.Repository, error) {
if err := db.Model((*models.Server)(nil)).CreateTable(&orm.CreateTableOptions{ if err := db.Model((*models.Server)(nil)).CreateTable(&orm.CreateTableOptions{
IfNotExists: true, IfNotExists: true,
}); err != nil { }); err != nil {
return nil, errors.Wrap(err, "cannot create 'servers' table") return nil, errors.Wrap(err, "couldn't create the 'servers' table")
} }
return &pgRepo{db}, nil return &pgRepo{db}, nil
} }
@ -51,7 +51,7 @@ func (repo *pgRepo) Update(ctx context.Context, server *models.Server) error {
func (repo *pgRepo) Fetch(ctx context.Context, f *models.ServerFilter) ([]*models.Server, int, error) { func (repo *pgRepo) Fetch(ctx context.Context, f *models.ServerFilter) ([]*models.Server, int, error) {
var err error var err error
data := []*models.Server{} var data []*models.Server
query := repo.Model(&data).Context(ctx).Relation("Groups") query := repo.Model(&data).Context(ctx).Relation("Groups")
if f != nil { if f != nil {
@ -70,7 +70,7 @@ func (repo *pgRepo) Fetch(ctx context.Context, f *models.ServerFilter) ([]*model
} }
func (repo *pgRepo) Delete(ctx context.Context, f *models.ServerFilter) ([]*models.Server, error) { func (repo *pgRepo) Delete(ctx context.Context, f *models.ServerFilter) ([]*models.Server, error) {
data := []*models.Server{} var data []*models.Server
query := repo.Model(&data).Context(ctx) query := repo.Model(&data).Context(ctx)
if f != nil { if f != nil {

View File

@ -0,0 +1,14 @@
package twutil
import "github.com/tribalwarshelp/shared/tw/twmodel"
func FindVersionByCode(versions []*twmodel.Version, code twmodel.VersionCode) *twmodel.Version {
var v *twmodel.Version
for _, version := range versions {
if version.Code == code {
v = version
break
}
}
return v
}

17
tw/twutil/tribalwars.go Normal file
View File

@ -0,0 +1,17 @@
package twutil
import (
"github.com/tribalwarshelp/shared/tw/twmodel"
)
func IsPlayerNil(player *twmodel.Player) bool {
return player == nil
}
func IsPlayerTribeNil(player *twmodel.Player) bool {
return IsPlayerNil(player) || player.Tribe == nil
}
func IsVillageNil(village *twmodel.Village) bool {
return village == nil
}

View File

@ -1,14 +0,0 @@
package utils
import "github.com/tribalwarshelp/shared/models"
func FindVersionByCode(versions []*models.Version, code models.VersionCode) *models.Version {
v := &models.Version{}
for _, version := range versions {
if version.Code == code {
v = version
break
}
}
return v
}

View File

@ -1,17 +0,0 @@
package utils
import (
"github.com/tribalwarshelp/shared/models"
)
func IsPlayerNil(player *models.Player) bool {
return player == nil
}
func IsPlayerTribeNil(player *models.Player) bool {
return IsPlayerNil(player) || player.Tribe == nil
}
func IsVillageNil(village *models.Village) bool {
return village == nil
}