-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
304 lines (271 loc) · 8.46 KB
/
Copy pathmain.go
File metadata and controls
304 lines (271 loc) · 8.46 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"sync"
"time"
"github.com/bwmarrin/discordgo"
)
type SharedDurationMap struct {
mu sync.RWMutex
data map[string]int64
}
type SharedFlagMap struct {
mu sync.RWMutex
flags map[string]bool
}
var (
GuildID = flag.String("guild", "", "Test guild ID. If not passed - bot registers commands globally")
SkronkID = flag.String("skronk", "", "Skronk role ID. If not passed - bot searches for role by name")
BotToken = flag.String("token", "", "Bot access token")
RemoveCommands = flag.Bool("rmcmd", true, "Remove all commands after shutting down or not")
s *discordgo.Session
durationMinValue = 10.0
skronkTotalDuration = new(SharedDurationMap)
skronkInProgress = new(SharedFlagMap)
commands = []*discordgo.ApplicationCommand{
{
Name: "skronk",
Description: "skronk someone",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "target",
Description: "Who will you skronk?",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "duration",
Description: "How long will you skronk them for? (in seconds)",
MinValue: &durationMinValue,
MaxValue: 60.0 * 60.0 * 24.0 * 7.0,
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "reason",
Description: "What did they do to deserve this?",
Required: false,
},
},
},
}
commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
"skronk": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// pass command if skronk role not provided
if len(*SkronkID) == 0 {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Command unavailable: skronk role not provided",
},
})
return
}
// pass command if sender is skronk'd
for _, role := range i.Member.Roles {
if role == *SkronkID {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "The skronk'd cannot skronk others >:(",
},
})
return
}
}
// get command options
options := i.ApplicationCommandData().Options
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
margs := make([]interface{}, 0, len(options))
msgformat := ""
targetID := ""
if opt, ok := optionMap["target"]; ok {
targetID = opt.UserValue(nil).ID
if targetID == s.State.User.ID {
targetID = i.Member.User.ID
msgformat += "Skronk me? Skronk ME!? Skronk YOURSELF!!!\n"
}
margs = append(margs, targetID)
msgformat += "Get skronk'd <@%s>!\n"
} else {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Something went wrong; required target option was not provided",
},
})
return
}
duration := int64(durationMinValue)
if opt, ok := optionMap["duration"]; ok {
duration = opt.IntValue()
}
margs = append(margs, duration)
msgformat += "See you in %d seconds!\n"
reason := "None"
if opt, ok := optionMap["reason"]; ok {
if targetID != s.State.User.ID {
reason = opt.StringValue()
margs = append(margs, reason)
msgformat += "> %s\n"
}
}
// add skronk role to target
err := s.GuildMemberRoleAdd(*GuildID, targetID, *SkronkID)
if err != nil { // probably a permission or hierarchy issue
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Something went wrong while adding a role",
},
})
log.Println(err)
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf(
msgformat,
margs...,
),
},
})
// track total duration in shared resource
skronkTotalDuration.mu.Lock()
skronkTotalDuration.data[targetID] += duration
log.Printf(
"/skronk'd <@%s>\n\t Duration: %d seconds\n\t Reason: %s\n\t Total Duration this instance: %d seconds\n",
targetID,
duration,
reason,
skronkTotalDuration.data[targetID],
)
skronkTotalDuration.mu.Unlock()
// only one goroutine handles timing per user
skronkInProgress.mu.Lock()
if skronkInProgress.flags[targetID] {
skronkInProgress.mu.Unlock()
return
}
skronkInProgress.flags[targetID] = true
skronkInProgress.mu.Unlock()
for {
time.Sleep(time.Second * time.Duration(duration))
skronkTotalDuration.mu.Lock()
skronkTotalDuration.data[targetID] -= duration
duration = skronkTotalDuration.data[targetID]
if skronkTotalDuration.data[targetID] <= 0 {
skronkTotalDuration.mu.Unlock()
break
}
skronkTotalDuration.mu.Unlock()
}
skronkInProgress.mu.Lock()
skronkInProgress.flags[targetID] = false
skronkInProgress.mu.Unlock()
// remove skronk role from target
err = s.GuildMemberRoleRemove(*GuildID, targetID, *SkronkID)
if err != nil { // probably a permission or hierarchy issue
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Something went wrong while removing a role",
},
})
log.Println(err)
return
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf(
"Welcome back <@%s>!",
targetID,
),
},
})
log.Printf("/unskronk'd <@%s>\n", targetID)
},
}
)
func init() {
flag.Parse()
// create a bot session
var err error
s, err = discordgo.New("Bot " + *BotToken)
if err != nil {
log.Fatalf("Invalid bot parameters: %v", err)
}
// find skronk role by name if role ID not provided at start up
if len(*SkronkID) == 0 {
log.Println("Skronk role ID was not provided, searching for skronk role by name")
roles, err := s.GuildRoles(*GuildID)
if err != nil {
log.Fatalf("Invalid guild parameters: %v", err)
}
for _, role := range roles {
if role.Name == "SKRONK'd" {
*SkronkID = role.ID
}
}
if len(*SkronkID) == 0 {
log.Println("Skronk role was not found, skronk command will be unavailable")
} else {
log.Printf("Skronk role found. Skronk role ID is %s\nWRITE THAT DOWN!", *SkronkID)
}
}
skronkTotalDuration.data = make(map[string]int64)
skronkInProgress.flags = make(map[string]bool)
// create a handler for each command
s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})
}
func main() {
// open the session
s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
log.Printf("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator)
})
err := s.Open()
if err != nil {
log.Fatalf("Cannot open the session: %v", err)
}
// add commands to server
log.Println("Adding commands...")
registeredCommands := make([]*discordgo.ApplicationCommand, len(commands))
for i, v := range commands {
cmd, err := s.ApplicationCommandCreate(s.State.User.ID, *GuildID, v)
if err != nil {
log.Panicf("Cannot create '%v' command: %v", v.Name, err)
}
registeredCommands[i] = cmd
}
defer s.Close()
// wait until Ctrl+C signal is sent
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
log.Println("Press Ctrl+C to exit")
<-stop
// remove commands from server before shut down
if *RemoveCommands {
log.Println("Removing commands...")
for _, v := range registeredCommands {
err := s.ApplicationCommandDelete(s.State.User.ID, *GuildID, v.ID)
if err != nil {
log.Panicf("Cannot delete '%v' command: %v", v.Name, err)
}
}
}
log.Println("Gracefully shutting down.")
}