forked from akena-engineering/discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread-lifecycle.js
More file actions
88 lines (77 loc) · 2.46 KB
/
thread-lifecycle.js
File metadata and controls
88 lines (77 loc) · 2.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
const GUILD = process.env.GUILD
const { MessageActionRow, MessageButton } = require("discord.js")
const moment = require("moment")
const { read } = require("../utils/storage")
function weekdaysBefore(theMoment, days) {
let newMoment = theMoment.clone()
while (days > 0) {
if (newMoment.isoWeekday() < 6) {
days -= 1
}
newMoment = newMoment.subtract(1, "days")
}
return newMoment
}
function archiveThreadPrompt(client, thread) {
if (thread.ownerId === client.user.id) {
thread.setArchived(true)
return
}
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("archive-thread")
.setLabel("Archive The Thread")
.setStyle("DANGER")
)
.addComponents(
new MessageButton()
.setCustomId("long-running-thread")
.setLabel("Long-Running Thread")
.setStyle("SECONDARY")
)
thread.send({
content: `<@${thread.ownerId}>, it's been a bit since this thread has seen activity. Ready to archive it?`,
components: [row],
})
}
module.exports = {
schedule: "*/15 * * * *",
timezone: "Europe/Warsaw",
execute(client) {
return async () => {
const guild = await client.guilds.fetch(GUILD)
const channels = await guild.channels.fetch()
const longRunningThreadIds = (await read("long-running-thread-ids")) || {}
const archiveThreshold = weekdaysBefore(moment(), 4)
channels
.filter((channel) => channel && channel.isText() && channel.viewable)
.forEach(async (channel) => {
const threads = await channel.threads.fetch()
threads.threads.forEach(async (thread) => {
let lastMessage = null
try {
lastMessage = await thread.messages.fetch(thread.lastMessageId)
} catch (error) {
console.error(`Failed to fetch last message for thread ${thread.id}`)
archiveThreadPrompt(client, thread)
return
}
const lastActivity = Math.max(
lastMessage?.createdTimestamp ?? 0,
thread.archiveTimestamp
)
if (moment(lastActivity).isAfter(archiveThreshold)) {
return
}
if (longRunningThreadIds[thread.id]) {
await thread.setArchived(true)
thread.setArchived(false)
} else {
archiveThreadPrompt(client, thread)
}
})
})
}
},
}