-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
114 lines (97 loc) · 2.82 KB
/
main.go
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"time"
"github.com/joho/godotenv"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/ethanthatonekid/trends/preprocess"
"github.com/ethanthatonekid/trends/preprocess/discord"
)
func main() {
godotenv.Load(".env")
app := NewApp()
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
type App struct {
*cli.App
}
func NewApp() *App {
app := &App{}
app.App = &cli.App{
Name: "trends",
HelpName: "discover trends in your Discord server",
Commands: []*cli.Command{
{
Name: "preprocess",
HelpName: "preprocesses messages for analysis",
Usage: "trends preprocess <channel ID> <start timestamp> <end timestamp>",
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "channels",
Aliases: []string{"c"},
Usage: "the channels to analyze",
},
&cli.PathFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "the output directory",
Value: "results",
},
&cli.TimestampFlag{
Name: "start",
Aliases: []string{"s"},
Usage: "start date of the range to analyze (see https://unixtimestamp.com/)",
Layout: time.RFC3339,
},
&cli.TimestampFlag{
Name: "end",
Aliases: []string{"e"},
Usage: "end date of the range to analyze (see https://unixtimestamp.com/)",
Layout: time.RFC3339,
},
},
Action: preprocessAction,
},
},
}
return app
}
func preprocessAction(ctx *cli.Context) error {
provider := discord.New("Bot " + os.Getenv("DISCORD_TOKEN"))
channelIDs := ctx.StringSlice("channels")
outputRoot := ctx.Path("output")
start := ctx.Timestamp("start").UTC()
end := ctx.Timestamp("end").UTC()
// timeFormat (generated from https://godate.diamondb.xyz/)
const timeFormat = "06-01-02_15-04-05"
timeRange := fmt.Sprintf("%s-%s", start.Format(timeFormat), end.Format(timeFormat))
// Fetch and convert messages from each channel.
channels, err := preprocess.RenderChannels(provider, channelIDs, start, end)
if err != nil {
return errors.Wrap(err, "failed to render messages")
}
// Write each channel to a file.
for _, ch := range channels {
b, err := json.MarshalIndent(ch, "", " ")
if err != nil {
return errors.Wrap(err, "failed to marshal channel")
}
filename := fmt.Sprintf("%s.json", ch.ChannelID)
pathname := filepath.Join(outputRoot, timeRange, filename)
if err = os.MkdirAll(filepath.Dir(pathname), 0755); err != nil {
return errors.Wrap(err, "failed to create directory")
}
if err = ioutil.WriteFile(pathname, b, 0644); err != nil {
return errors.Wrap(err, "failed to write messages to file")
}
}
return nil
}