bump github.com/tribalwarshelp/shared and github.com/tribalwarshelp/golang-sdk

This commit is contained in:
Dawid Wysokiński 2021-05-06 14:42:37 +02:00
parent d2b06512fe
commit ab6bbfa9c2
19 changed files with 218 additions and 191 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

@ -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.deleteClosedTribalWarsServers,
"deleteClosedTribalWarsServers") "deleteClosedTribalWarsServers")
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/shared/tw/twmodel"
"github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/dcbot/utils"
shared_models "github.com/tribalwarshelp/shared/models"
) )
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

View File

@ -3,16 +3,17 @@ 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/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/golang-sdk/sdk"
"github.com/tribalwarshelp/dcbot/discord" "github.com/tribalwarshelp/dcbot/discord"
"github.com/tribalwarshelp/dcbot/group" "github.com/tribalwarshelp/dcbot/group"
@ -20,7 +21,6 @@ import (
"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/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,36 +83,36 @@ 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 {
@ -156,26 +156,26 @@ func (h *handler) checkEnnoblements() {
} }
log.Info("checkEnnoblements: loaded ennoblements") log.Info("checkEnnoblements: loaded ennoblements")
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 := utils.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 !utils.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 := !utils.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)
} }
} }
@ -282,9 +282,9 @@ func (h *handler) deleteClosedTribalWarsServers() {
WithField("servers", servers). WithField("servers", servers).
Info("deleteClosedTribalWarsServers: loaded servers") Info("deleteClosedTribalWarsServers: 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("deleteClosedTribalWarsServers: " + err.Error())
@ -294,9 +294,9 @@ func (h *handler) deleteClosedTribalWarsServers() {
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 {

View File

@ -1,10 +1,29 @@
package cron package cron
import ( import (
"github.com/sirupsen/logrus"
"github.com/tribalwarshelp/shared/tw/twmodel"
"time"
"github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/dcbot/utils"
shared_models "github.com/tribalwarshelp/shared/models"
) )
func isBarbarian(p *shared_models.Player) bool { func isBarbarian(p *twmodel.Player) bool {
return utils.IsPlayerNil(p) || p.ID == 0 return utils.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/utils"
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
} }
@ -55,23 +56,23 @@ func newMessage(cfg newMessageConfig) checkEnnoblementsMsg {
} }
if !utils.IsVillageNil(cfg.ennoblement.Village) { if !utils.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 !utils.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 !utils.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 !utils.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 !utils.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

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/golang-sdk/sdk"
"github.com/tribalwarshelp/dcbot/message" "github.com/tribalwarshelp/dcbot/message"
"github.com/tribalwarshelp/dcbot/utils" "github.com/tribalwarshelp/dcbot/utils"
"github.com/tribalwarshelp/golang-sdk/sdk"
"github.com/tribalwarshelp/shared/models"
"github.com/tribalwarshelp/shared/tw"
) )
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 !utils.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 !utils.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

@ -6,13 +6,15 @@ import (
"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"
) )
@ -231,18 +233,18 @@ func (s *Session) handleNewMessage(_ *discordgo.Session, m *discordgo.MessageCre
splitted := strings.Split(m.Content, " ") splitted := strings.Split(m.Content, " ")
args := splitted[1:] args := splitted[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(splitted[0])
@ -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/utils"
shared_models "github.com/tribalwarshelp/shared/models"
) )
const ( const (
@ -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 {
@ -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 := utils.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,

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"
@ -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,

6
go.mod
View File

@ -3,7 +3,9 @@ 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/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 +14,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 {

59
main.go
View File

@ -1,6 +1,8 @@
package main package main
import ( import (
"github.com/Kichiyaki/appmode"
"github.com/Kichiyaki/goutil/envutil"
"log" "log"
"os" "os"
"os/signal" "os/signal"
@ -16,13 +18,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 +37,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 +51,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 +72,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,14 +97,15 @@ 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.WithChain(
cron.SkipIfStillRunning(cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))), cron.SkipIfStillRunning(cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags))),
@ -122,24 +120,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,23 +1,23 @@
package models package models
import ( import (
"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

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

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

View File

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