-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
392 lines (340 loc) · 11.2 KB
/
app.js
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
const { App, AwsLambdaReceiver } = require("@slack/bolt");
const dotenv = require("dotenv");
dotenv.config();
const fs = require("fs");
// Initialize your custom receiver
const awsLambdaReceiver = new AwsLambdaReceiver({
signingSecret: process.env.SLACK_SIGNING_SECRET,
});
// Initializes app with bot token and signing secret
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET,
appToken: process.env.SLACK_APP_TOKEN,
ignoreSelf: false,
receiver: awsLambdaReceiver,
});
// Handle the Lambda function event
module.exports.handler = async (event, context, callback) => {
const handler = await awsLambdaReceiver.start();
return handler(event, context, callback);
};
// given a filename, returns parsed JSON contents
async function readJSON(filename) {
try {
const data = await fs.promises.readFile(filename, "utf8");
const jsonData = JSON.parse(data);
return jsonData;
} catch (error) {
console.error("error reading/parsing json file:", error);
throw error;
}
}
// generate a schedule for a week of messages
// returns a list of numbers [0-6] that represents day offsets from the current day
function getWeeklySchedule(startDate, timesPerWeek) {
// this represents offsets of the current date
const weekDates = [0, 1, 2, 3, 4, 5, 6];
const chosenDates = new Set();
// get weekend date
const daysUntilSat = 6 - startDate.getDay();
const daysUntilSun = (daysUntilSat + 1) % 7;
chosenDates.add(Math.random() < 0.5 ? daysUntilSat : daysUntilSun);
// fill up the rest of our dates
while (chosenDates.size < timesPerWeek) {
chosenDates.add(weekDates[Math.floor(Math.random() * weekDates.length)]);
}
return Array.from(chosenDates).sort();
}
// get a random prompt from promptList, remove it if removePrompt is true
function getRandomPrompt(promptList, removePrompt) {
const index = Math.floor(Math.random() * promptList.length);
const prompt = promptList[index];
if (removePrompt) promptList.splice(index, 1);
return prompt;
}
// add days to a date
function addDays(startDate, days) {
const newDate = new Date(startDate.valueOf());
newDate.setDate(newDate.getDate() + days);
return newDate;
}
async function schedulePrompts(startDate, promptList = []) {
const { oneTimePrompts, repeatedPrompts, timesPerWeek, probabilityRepeat } =
await readJSON("prompt_config.json");
// if we didn't input a prompt list, use the one from config
const prompts = promptList.length === 0 ? oneTimePrompts : promptList;
while (prompts.length > 0) {
// generate timesPerWeek days in the next week
const nextTimes = getWeeklySchedule(startDate, timesPerWeek);
for (const time of nextTimes) {
if (prompts.length === 0) break;
// get a prompt randomly with probability
const isOneTime = Math.random() > probabilityRepeat;
const prompt = isOneTime
? getRandomPrompt(prompts, true)
: getRandomPrompt(repeatedPrompts, false);
// get the next time
const nextTime = addDays(startDate, time);
nextTime.setHours(
12 + Math.random() * 4,
Math.floor(Math.random() * 60),
0
);
// schedule message
await app.client.chat.scheduleMessage({
channel: "bereal",
text: `🦛 it's time to BeSiege! 🦛\n\ntoday's prompt is: *${prompt}*`,
post_at: Math.floor(nextTime.getTime() / 1000),
parse: "full",
});
}
// go to the next week
startDate = addDays(startDate, 7);
}
}
async function initialScheduling() {
// set start date to be next day 8am
let startDate = addDays(new Date(), 1);
startDate.setHours(12, 0, 0);
schedulePrompts(startDate);
}
// check if current user is admin
async function isAdmin(userId) {
const channels = (
await app.client.conversations.list({
types: "public_channel,private_channel",
})
)["channels"];
const adminChannelId = channels.filter(
(val) => val.name === "siegebot-admin"
)[0];
if (!adminChannelId) {
throw new Error("failed to find channel");
} else {
const members = await app.client.conversations.members({
channel: adminChannelId.id,
});
if (members["ok"]) {
return members["members"].includes(userId);
} else {
throw new Error("failed to get members");
}
}
}
// command, get the next scheduled bereal times
app.command("/schedule", async ({ command, say, ack }) => {
try {
let responseMessage;
if (await isAdmin(command.user_id)) {
const scheduled =
(await app.client.chat.scheduledMessages.list()).scheduled_messages ??
[];
const schedule = scheduled
.sort((a, b) => a.post_at - b.post_at)
.map((message) => {
const timeString = new Date(message.post_at * 1000).toLocaleString(
"en-US",
{ timeZone: "America/New_York" }
);
return `"${message.text.replace(
/[\r\n]+/gm,
" "
)}" at ${timeString} (id: ${message.id})`;
});
responseMessage =
"next scheduled times:\n" +
schedule.reduce((prev, next) => prev + "\n" + next, "");
} else {
responseMessage = "you do not have permissions to run this command!";
}
await say(responseMessage);
await ack();
} catch (error) {
console.error(error);
await say(`schedule failed with error ${error}`);
await ack();
}
});
// command, clear the prompt schedule
app.command("/clear-schedule", async ({ command, say, ack }) => {
try {
let responseMessage;
if (await isAdmin(command.user_id)) {
const scheduled =
(await app.client.chat.scheduledMessages.list()).scheduled_messages ??
[];
for (const message of scheduled) {
app.client.chat.deleteScheduledMessage({
channel: message.channel_id,
scheduled_message_id: message.id,
});
}
responseMessage = "cleared bereal schedule";
} else {
responseMessage = "you do not have permission to run this command!";
}
await say(responseMessage);
await ack();
} catch (error) {
console.error(error);
await say(`clear failed with error ${error}`);
await ack();
}
});
// command, initialize the prompt schedule
app.command("/initialize", async ({ command, say, ack }) => {
try {
let responseMessage;
if (await isAdmin(command.user_id)) {
initialScheduling();
responseMessage = "running initial scheduling...";
} else {
responseMessage = "you do not have permission to run this command!";
}
await say(responseMessage);
await ack();
} catch (error) {
console.error(error);
await say(`initialize failed with error ${error}`);
await ack();
}
});
// command, delete prompt(s) given a list of prompt ids
app.command("/delete", async ({ command, say, ack }) => {
try {
let responseMessage;
if (await isAdmin(command.user_id)) {
const messageIds = command.text.split(",").map((id) => id.trimStart());
const scheduled =
(await app.client.chat.scheduledMessages.list()).scheduled_messages ??
[];
// if there is anything in scheduled
if (scheduled && messageIds.length > 0) {
const channel_id = scheduled[0].channel_id;
responseMessage = "deleted:\n";
console.log("messageids", messageIds);
const responses = await Promise.all(
messageIds.map((messageId) =>
app.client.chat.deleteScheduledMessage({
channel: channel_id,
scheduled_message_id: messageId,
})
)
);
responseMessage =
"deleted:\n" +
responses
.map((val, i) =>
val["ok"]
? `successfully deleted ${messageIds[i]}`
: `failed to delete ${messageIds[i]}`
)
.join("\n");
} else {
responseMessage =
"failed to delete, no messages scheduled right now or no message IDs provided.";
}
} else {
responseMessage = "you do not have permissions to use this command!";
}
await say(responseMessage);
await ack();
} catch (error) {
console.error(error);
await say(
`delete failed — check to make sure that your message ID is correct!`
);
await ack();
}
});
// command, add a prompt to the schedule
app.command("/add", async ({ command, say, ack }) => {
try {
let responseMessage;
if (await isAdmin(command.user_id)) {
const prompts = command.text
.split(",")
.map((prompt) => prompt.trimStart());
const scheduled =
(await app.client.chat.scheduledMessages.list()).scheduled_messages ??
[];
const lastScheduled = scheduled
.sort((a, b) => a.post_at - b.post_at)
.pop();
const startDate = addDays(
lastScheduled === undefined
? new Date()
: new Date(lastScheduled.post_at * 1000),
1
); // default to current date
startDate.setHours(12, 0, 0);
schedulePrompts(startDate, prompts);
responseMessage = `inserting prompts:\n${prompts.join("\n")}`;
} else {
responseMessage = "you do not have permissions to use this command!";
}
await say(responseMessage);
await ack();
} catch (error) {
console.error(error);
await say(`add failed with error ${error}`);
await ack();
}
});
// command, add a prompt to the schedule
// takes input in the format "prompt", "yyyy-mm-dd"
app.command("/add-on-day", async ({ command, say, ack }) => {
try {
let responseMessage;
if (await isAdmin(command.user_id)) {
const inputs = command.text.split(",").map((val) => val.trimStart());
if (inputs.length !== 2) {
responseMessage = "command must be of the form '<prompt>, yyyy-mm-dd'";
} else {
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = inputs[1].match(regex);
if (!match) {
responseMessage =
"command must be of the form '<prompt>, yyyy-mm-dd'";
} else {
const { year, month, day } = match.groups;
// pick a random time on the given date to schedule the message
const schedDate = new Date(
parseInt(year),
parseInt(month) - 1,
parseInt(day),
12 + Math.random() * 4,
Math.floor(Math.random() * 60),
0
);
await app.client.chat.scheduleMessage({
channel: "bereal",
text: `🦛 it's time to BeSiege! 🦛\n\ntoday's prompt is: *${inputs[0]}*`,
post_at: Math.floor(schedDate.getTime() / 1000),
parse: "full",
});
responseMessage = `inserted prompt ${
inputs[0]
} at ${schedDate.toLocaleString("en-US", {
timeZone: "America/New_York",
})}`;
}
}
} else {
responseMessage = "you do not have permissions to use this command!";
}
await say(responseMessage);
await ack();
} catch (error) {
console.error(error);
await say(`add failed with error ${error}`);
await ack();
}
});
(async () => {
// Start the app
console.log("we are running");
await app.start(process.env.PORT || 3000);
console.log("⚡️ Bolt app is running!");
})();