/
main.go
218 lines (183 loc) · 5.72 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
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
package main
import (
"context"
"database/sql"
"fmt"
"os"
"strings"
"time"
// Per the docs, this should be imported in the main package rather than a library.
// We use this for the profile timezone function
_ "time/tzdata"
"github.com/caarlos0/env/v7"
"github.com/diamondburned/arikawa/v3/api/webhook"
"github.com/diamondburned/arikawa/v3/discord"
"github.com/holedaemon/bot2/internal/bot"
"github.com/holedaemon/bot2/internal/db/dbx"
"github.com/holedaemon/bot2/internal/pkg/discordx"
"github.com/holedaemon/bot2/internal/web"
"github.com/zikaeroh/ctxlog"
"go.uber.org/zap"
"golang.org/x/oauth2"
)
type botOptions struct {
Debug bool `env:"BOT2_BOT_DEBUG" envDefault:"false"`
Admins []string `env:"BOT2_BOT_ADMINS"`
Token string `env:"BOT2_BOT_TOKEN"`
LoggingWebhookURL string `env:"BOT2_BOT_LOGGING_WEBHOOK_URL"`
FeedbackWebhookURL string `env:"BOT2_BOT_FEEDBACK_WEBHOOK_URL"`
DSN string `env:"BOT2_BOT_DSN"`
TopsterAddr string `env:"BOT2_BOT_TOPSTER_ADDR"`
SiteAddr string `env:"BOT2_BOT_SITE_ADDR"`
SteamAPIKey string `env:"BOT2_BOT_STEAM_API_KEY"`
DBMaxAttempts int `env:"BOT2_BOT_DB_MAX_ATTEMPTS" envDefault:"10"`
DBTimeoutDuration time.Duration `env:"BOT2_BOT_DB_TIMEOUT_DURATION" envDefault:"20s"`
}
type webOptions struct {
Debug bool `env:"BOT2_WEB_DEBUG" envDefault:"false"`
Addr string `env:"BOT2_WEB_ADDR" envDefault:":8080"`
Admins map[string]string `env:"BOT2_WEB_ADMINS"`
DSN string `env:"BOT2_WEB_DSN"`
DBMaxAttempts int `env:"BOT2_WEB_DB_MAX_ATTEMPTS" envDefault:"10"`
DBTimeoutDuration time.Duration `env:"BOT2_WEB_DB_TIMEOUT_DURATION" envDefault:"20s"`
OAuth2ClientID string `env:"BOT2_WEB_OAUTH2_CLIENT_ID"`
OAuth2ClientSecret string `env:"BOT2_WEB_OAUTH2_CLIENT_SECRET"`
OAuth2Scopes []string `env:"BOT2_WEB_OAUTH2_SCOPES"`
OAuth2RedirectURL string `env:"BOT2_WEB_OAUTH2_REDIRECT_URL"`
}
func main() {
if len(os.Args) == 1 {
fmt.Fprintf(os.Stderr, "missing required argument: bot, web")
return
}
cmd := strings.ToLower(os.Args[1])
switch cmd {
case "bot":
runBot()
case "web":
runWeb()
default:
fmt.Fprintf(os.Stderr, "invalid argument; accepted arguments: bot, web")
}
}
func runBot() {
opts := &botOptions{}
eo := env.Options{
RequiredIfNoDef: true,
}
if err := env.Parse(opts, eo); err != nil {
fmt.Fprintf(os.Stderr, "error parsing env variables into struct: %s\n", err.Error())
return
}
logger := ctxlog.New(opts.Debug)
ctx := ctxlog.WithLogger(context.Background(), logger)
admins := make([]discord.UserID, 0)
for _, a := range opts.Admins {
sf, err := discord.ParseSnowflake(a)
if err != nil {
logger.Fatal("error parsing admin snowflake", zap.Error(err))
}
admins = append(admins, discord.UserID(sf))
}
var (
db *sql.DB
err error
)
connected := false
for i := 0; i < opts.DBMaxAttempts && !connected; i++ {
db, err = sql.Open(dbx.Driver, opts.DSN)
if err != nil {
logger.Error("unable to connect to database", zap.Error(err), zap.Int("attempt", i))
time.Sleep(opts.DBTimeoutDuration)
continue
}
if err = db.PingContext(ctx); err != nil {
logger.Error("unable to ping database", zap.Error(err), zap.Int("attempt", i))
time.Sleep(opts.DBTimeoutDuration)
continue
}
connected = true
}
if !connected {
logger.Fatal("max database attempts reached", zap.Int("attempts", opts.DBMaxAttempts))
}
logHook, err := webhook.NewFromURL(opts.LoggingWebhookURL)
if err != nil {
logger.Fatal("error creating logging webhook", zap.Error(err))
}
feedHook, err := webhook.NewFromURL(opts.FeedbackWebhookURL)
if err != nil {
logger.Fatal("error creating feedback webhook", zap.Error(err))
}
b, err := bot.New(
opts.Token,
bot.WithDB(db),
bot.WithLoggingWebhook(logHook),
bot.WithFeedbackWebhook(feedHook),
bot.WithDebug(opts.Debug),
bot.WithTopsterAddr(opts.TopsterAddr),
bot.WithSiteAddr(opts.SiteAddr),
bot.WithSteamAPIKey(opts.SteamAPIKey),
bot.WithAdmins(admins...),
)
if err != nil {
logger.Fatal("error creating bot", zap.Error(err))
}
if err := b.Start(ctx); err != nil {
logger.Fatal("error starting bot", zap.Error(err))
}
}
func runWeb() {
opts := &webOptions{}
eo := env.Options{
RequiredIfNoDef: true,
}
if err := env.Parse(opts, eo); err != nil {
fmt.Fprintf(os.Stderr, "error parsing env variables into struct: %s\n", err.Error())
return
}
logger := ctxlog.New(opts.Debug)
ctx := ctxlog.WithLogger(context.Background(), logger)
oa := &oauth2.Config{
ClientID: opts.OAuth2ClientID,
ClientSecret: opts.OAuth2ClientSecret,
Endpoint: discordx.Endpoint,
RedirectURL: opts.OAuth2RedirectURL,
Scopes: opts.OAuth2Scopes,
}
var (
db *sql.DB
err error
)
connected := false
for i := 0; i < opts.DBMaxAttempts && !connected; i++ {
db, err = sql.Open(dbx.Driver, opts.DSN)
if err != nil {
logger.Error("unable to connect to database", zap.Error(err), zap.Int("attempt", i))
time.Sleep(opts.DBTimeoutDuration)
continue
}
if err = db.PingContext(ctx); err != nil {
logger.Error("unable to ping database", zap.Error(err), zap.Int("attempt", i))
time.Sleep(opts.DBTimeoutDuration)
continue
}
connected = true
}
if !connected {
logger.Fatal("max database attempts reached", zap.Int("attempts", opts.DBMaxAttempts))
}
s, err := web.New(
web.WithDebug(opts.Debug),
web.WithAddr(opts.Addr),
web.WithDB(db),
web.WithOAuth2(oa),
web.WithAdmins(opts.Admins),
)
if err != nil {
logger.Fatal("error creating bot", zap.Error(err))
}
if err := s.Run(ctx); err != nil {
logger.Fatal("error starting bot", zap.Error(err))
}
}