1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
package commands
import (
"bytes"
"context"
"errors"
"fmt"
"image/color"
"io"
"math"
"slices"
"time"
"git.anhgelus.world/anhgelus/les-copaings-bot/common"
"git.anhgelus.world/anhgelus/les-copaings-bot/config"
"git.anhgelus.world/anhgelus/les-copaings-bot/exp"
"git.anhgelus.world/anhgelus/les-copaings-bot/user"
"github.com/jackc/pgx/v5/pgtype"
"github.com/nyttikord/gokord/bot"
"github.com/nyttikord/gokord/discord/request"
"github.com/nyttikord/gokord/interaction"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
"gorm.io/gorm"
)
type data struct {
CreatedAt time.Time
XP int
CopaingID int
}
type dbData struct {
CreatedAt *pgtype.Date
XP int
CopaingID int
}
var colors = []color.RGBA{
{38, 70, 83, 255},
{42, 157, 143, 255},
{244, 162, 97, 255},
{231, 111, 81, 255},
{193, 18, 31, 255},
}
func Stats(ctx context.Context, dg bot.Session, i *interaction.ApplicationCommand) {
cfg := config.GetGuildConfig(ctx, i.GuildID)
days := 15
if common.IsDebug(ctx) {
days = 90
}
resp := interaction.NewMessageResponse()
defer func() {
err := dg.InteractionAPI().Respond(i.Interaction, resp.Response()).Do(ctx)
if err != nil {
bot.Logger(ctx).Error("replying to interaction", "error", err)
}
}()
opts := i.OptionMap()
if v, ok := opts["jours"]; ok {
in := v.IntValue()
if in < 1 || uint(in) > cfg.DaysXPRemains {
msg := fmt.Sprintf("Nombre de jours invalide. Il doit être strictement positif et inférieur à %d", cfg.DaysXPRemains)
resp.Message(msg)
return
}
days = int(in)
}
err := dg.InteractionAPI().Respond(i.Interaction, interaction.NewDeferredResponse()).Do(ctx)
if err != nil {
bot.Logger(ctx).Error("sending deferred", "error", err)
}
var w io.WriterTo
if v, ok := opts["copaing"]; ok {
w, err = statsMember(ctx, dg, i, days, v.UserValue(ctx).ID)
} else {
w, err = statsAll(ctx, dg, i, days)
}
if err != nil {
bot.Logger(ctx).Error("generating stats", "error", err, "guild", i.GuildID)
resp.Message("Il y a eu une erreur...")
return
}
b := new(bytes.Buffer)
_, err = w.WriteTo(b)
if err != nil {
bot.Logger(ctx).Error("writing png", "error", err)
resp.Message("Il y a eu une erreur...")
return
}
resp.AddFile(&request.File{
Name: "plot.png",
ContentType: "image/png",
Reader: b,
})
}
func statsAll(ctx context.Context, dg bot.Session, i *interaction.ApplicationCommand, days int) (io.WriterTo, error) {
return stats(ctx, dg, i, days, func(before, after string) *gorm.DB {
return common.GetDB(ctx).Raw(
before+"WHERE guild_id = ? and created_at > ?"+after,
i.GuildID, exp.TimeStampNDaysBefore(ctx, uint(days)),
)
})
}
func statsMember(ctx context.Context, dg bot.Session, i *interaction.ApplicationCommand, days int, discordID string) (io.WriterTo, error) {
_, err := dg.GuildAPI().Member(i.GuildID, discordID).Do(ctx)
if err != nil {
return nil, err
}
return stats(ctx, dg, i, days, func(before, after string) *gorm.DB {
return common.GetDB(ctx).Raw(
before+"WHERE guild_id = ? and created_at > ? and copaing_id = ?"+after,
i.GuildID, exp.TimeStampNDaysBefore(ctx, uint(days)), user.GetCopaing(ctx, discordID, i.GuildID).ID,
)
})
}
func stats(ctx context.Context, dg bot.Session, i *interaction.ApplicationCommand, days int, execSql func(before, after string) *gorm.DB) (io.WriterTo, error) {
var rawData []*data
if common.IsDebug(ctx) {
var rawCopaingData []*user.CopaingXP
if err := execSql("SELECT * FROM copaing_xps ", "").Scan(&rawCopaingData).Error; err != nil {
bot.Logger(ctx).Error("fetching result", "error", err)
return nil, err
}
rawData = make([]*data, len(rawCopaingData))
for in, d := range rawCopaingData {
rawData[in] = &data{
CreatedAt: d.CreatedAt,
XP: int(d.XP),
CopaingID: int(d.CopaingID),
}
}
} else {
var rawDbData []dbData
if err := execSql(
`SELECT "created_at"::date::text, sum("xp") as xp, "copaing_id" FROM copaing_xps `, ` GROUP BY "created_at"::date, "copaing_id"`,
).Scan(&rawDbData).Error; err != nil {
bot.Logger(ctx).Error("fetching result", "error", err)
return nil, err
}
rawData = make([]*data, len(rawDbData))
for in, d := range rawDbData {
rawData[in] = &data{
CreatedAt: d.CreatedAt.Time,
XP: d.XP,
CopaingID: d.CopaingID,
}
}
}
copaings := map[int]*user.Copaing{}
stats := map[int][]plotter.XY{}
for _, raw := range rawData {
_, ok := copaings[raw.CopaingID]
if !ok {
var cp user.Copaing
if err := common.GetDB(ctx).First(&cp, raw.CopaingID).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
bot.Logger(ctx).Error("finding copaing", "error", err, "copaing", raw.CopaingID)
return nil, err
}
bot.Logger(ctx).Warn("copaing not found, skipping", "copaing", raw.CopaingID)
continue
}
copaings[raw.CopaingID] = &cp
}
pts, ok := stats[raw.CopaingID]
now := time.Now().Unix()
if !ok {
pts = make([]plotter.XY, days+1)
for i := 0; i < len(pts); i++ {
pts[i] = plotter.XY{
X: float64(i - days),
Y: 0,
}
}
stats[raw.CopaingID] = pts
}
t := raw.CreatedAt.Unix() - now
if !common.IsDebug(ctx) {
t = int64(math.Ceil(float64(t) / (24 * 60 * 60)))
} else {
t = int64(math.Ceil(float64(t) / exp.DebugFactor))
}
pts[int64(days)+t] = plotter.XY{ // because t <= 0
X: float64(t),
Y: float64(raw.XP),
}
}
return generatePlot(ctx, dg, i, copaings, stats)
}
func generatePlot(ctx context.Context, dg bot.Session, i *interaction.ApplicationCommand, copaings map[int]*user.Copaing, stats map[int][]plotter.XY) (io.WriterTo, error) {
p := plot.New()
fontSizeTitle := vg.Length(16)
fontSize := vg.Length(12)
// set font size
p.Title.TextStyle.Font.Size = fontSizeTitle
p.X.Label.TextStyle.Font.Size = fontSizeTitle
p.Y.Label.TextStyle.Font.Size = fontSizeTitle
p.Legend.TextStyle.Font.Size = fontSize
// set legend style
p.Legend.YPosition = draw.PosTop
p.Legend.Top = true
p.Legend.Padding = vg.Points(2)
// set scales
p.Title.Text = "XP gagnées"
p.X.Label.Text = "Jours"
if common.IsDebug(ctx) {
p.X.Label.Text = fmt.Sprintf("%d secondes", exp.DebugFactor)
}
p.Y.Label.Text = "XP"
p.Y.Scale = exp.LevelScale{}
p.Add(plotter.NewGrid())
cnt := 0
for in, c := range copaings {
m, err := dg.GuildAPI().Member(i.GuildID, c.DiscordID).Do(ctx)
if err != nil {
bot.Logger(ctx).Error("fetching guild member", "error", err)
return nil, err
}
slices.SortFunc(stats[in], func(a, b plotter.XY) int {
if a.X < b.X {
return -1
}
if a.X > b.X {
return 1
}
return 0
})
l, _, err := plotter.NewLinePoints(plotter.XYs(stats[in]))
if err != nil {
return nil, err
}
l.Color = colors[cnt%len(colors)]
if len(copaings) < 4 {
l.Width = vg.Points(2)
}
if cnt/len(colors) > 0 {
size := 7 / min(cnt/len(colors), 7)
l.Dashes = []vg.Length{vg.Points(float64(size)), vg.Points(float64(size))}
}
p.Add(l)
p.Legend.Add(m.DisplayName(), l)
cnt++
}
return p.WriterTo(12*vg.Inch, 8*vg.Inch, "png")
}
|