-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy paththreadLengthMonitor.ts
More file actions
291 lines (253 loc) · 6.85 KB
/
threadLengthMonitor.ts
File metadata and controls
291 lines (253 loc) · 6.85 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
import {
type Client,
Container,
GuildThreadChannel,
TextDisplay
} from "@buape/carbon"
import {
threadLengthClose200Message,
threadLengthWarning100Message,
threadLengthWarning150Message
} from "../config/threadLengthMessages.js"
import {
listTrackedThreads,
type TrackedThreadRecord,
upsertTrackedThread
} from "../utils/trackedThreads.js"
const FIRST_WARNING_THRESHOLD = 100
const SECOND_WARNING_THRESHOLD = 150
const AUTO_CLOSE_THRESHOLD = 200
const DEFAULT_FETCH_LIMIT = 500
let monitorStarted = false
let monitorInterval: ReturnType<typeof setInterval> | null = null
let monitorRunInFlight = false
const parseIntervalMs = () => {
const rawValue = process.env.THREAD_LENGTH_CHECK_INTERVAL_HOURS?.trim()
if (!rawValue) {
return null
}
const intervalHours = Number.parseFloat(rawValue)
if (!Number.isFinite(intervalHours) || intervalHours <= 0) {
console.warn(
`THREAD_LENGTH_CHECK_INTERVAL_HOURS must be a positive number. Got "${rawValue}".`
)
return null
}
return Math.round(intervalHours * 60 * 60 * 1000)
}
const getErrorStatus = (error: unknown) => {
if (!error || typeof error !== "object") {
return null
}
const status = Reflect.get(error, "status")
if (typeof status === "number") {
return status
}
const statusCode = Reflect.get(error, "statusCode")
if (typeof statusCode === "number") {
return statusCode
}
const response = Reflect.get(error, "response")
if (!response || typeof response !== "object") {
return null
}
const responseStatus = Reflect.get(response, "status")
if (typeof responseStatus === "number") {
return responseStatus
}
const responseStatusCode = Reflect.get(response, "statusCode")
if (typeof responseStatusCode === "number") {
return responseStatusCode
}
return null
}
const isThreadLikeChannel = (
channel: unknown
): channel is GuildThreadChannel<any, false> =>
Boolean(
channel &&
typeof channel === "object" &&
"archive" in channel &&
typeof channel.archive === "function" &&
"lock" in channel &&
typeof channel.lock === "function"
)
const getMessageCount = (thread: GuildThreadChannel<any, false>) =>
thread.totalMessageSent ?? thread.messageCount ?? 0
const sendThreadMessage = async (
thread: GuildThreadChannel<any, false>,
message: string
) => {
await thread.send({
components: [new Container([new TextDisplay(message)])]
})
}
const syncClosedThread = async (
trackedThread: TrackedThreadRecord,
lastMessageCount: number | null
) => {
await upsertTrackedThread({
threadId: trackedThread.thread_id,
createdAt: trackedThread.created_at,
lastChecked: new Date().toISOString(),
solved: trackedThread.solved === 1,
warningLevel: trackedThread.warning_level,
closed: true,
lastMessageCount
})
}
const checkTrackedThread = async (
client: Client,
trackedThread: TrackedThreadRecord
) => {
let channel: Awaited<ReturnType<Client["fetchChannel"]>>
try {
channel = await client.fetchChannel(trackedThread.thread_id)
} catch (error) {
const status = getErrorStatus(error)
if (status === 404) {
await syncClosedThread(trackedThread, trackedThread.last_message_count)
return
}
console.error(
`Failed to fetch tracked thread ${trackedThread.thread_id} from Discord:`,
error
)
await upsertTrackedThread({
threadId: trackedThread.thread_id,
createdAt: trackedThread.created_at,
lastChecked: new Date().toISOString(),
solved: trackedThread.solved === 1,
warningLevel: trackedThread.warning_level,
closed: trackedThread.closed === 1,
lastMessageCount: trackedThread.last_message_count
})
return
}
if (!isThreadLikeChannel(channel)) {
console.warn(
`Tracked thread ${trackedThread.thread_id} is missing or is no longer a Discord thread channel.`
)
await syncClosedThread(trackedThread, trackedThread.last_message_count)
return
}
const messageCount = getMessageCount(channel)
const threadIsClosed = Boolean(channel.archived || channel.locked)
if (threadIsClosed) {
await syncClosedThread(trackedThread, messageCount)
return
}
const checkedAt = new Date().toISOString()
let nextWarningLevel = trackedThread.warning_level
let nextClosed = trackedThread.closed === 1
if (messageCount > AUTO_CLOSE_THRESHOLD) {
try {
await sendThreadMessage(channel, threadLengthClose200Message)
} catch (error) {
console.error(
`Failed to send auto-close warning for thread ${trackedThread.thread_id}:`,
error
)
}
let archived = false
let locked = false
try {
await channel.archive()
archived = true
} catch (error) {
console.error(
`Failed to archive thread ${trackedThread.thread_id} during auto-close:`,
error
)
}
try {
await channel.lock()
locked = true
} catch (error) {
console.error(
`Failed to lock thread ${trackedThread.thread_id} during auto-close:`,
error
)
}
nextClosed = archived || locked
nextWarningLevel = Math.max(nextWarningLevel, 2)
} else if (
messageCount > SECOND_WARNING_THRESHOLD &&
trackedThread.warning_level < 2
) {
try {
await sendThreadMessage(channel, threadLengthWarning150Message)
nextWarningLevel = 2
} catch (error) {
console.error(
`Failed to send 150-message warning for thread ${trackedThread.thread_id}:`,
error
)
}
} else if (
messageCount > FIRST_WARNING_THRESHOLD &&
trackedThread.warning_level < 1
) {
try {
await sendThreadMessage(channel, threadLengthWarning100Message)
nextWarningLevel = 1
} catch (error) {
console.error(
`Failed to send 100-message warning for thread ${trackedThread.thread_id}:`,
error
)
}
}
await upsertTrackedThread({
threadId: trackedThread.thread_id,
createdAt: trackedThread.created_at,
lastChecked: checkedAt,
solved: trackedThread.solved === 1,
warningLevel: nextWarningLevel,
closed: nextClosed,
lastMessageCount: messageCount
})
}
const runMonitorPass = async (client: Client) => {
const trackedThreads = await listTrackedThreads({
solved: false,
closed: false,
limit: DEFAULT_FETCH_LIMIT
})
for (const trackedThread of trackedThreads) {
await checkTrackedThread(client, trackedThread)
}
}
export const startThreadLengthMonitor = (client: Client) => {
if (monitorStarted) {
return
}
monitorStarted = true
const intervalMs = parseIntervalMs()
if (!intervalMs) {
console.log("Thread length monitor disabled.")
return
}
const run = async () => {
if (monitorRunInFlight) {
console.log("Skipping thread length monitor pass because the previous pass is still running.")
return
}
monitorRunInFlight = true
try {
await runMonitorPass(client)
} catch (error) {
console.error("Thread length monitor pass failed:", error)
} finally {
monitorRunInFlight = false
}
}
console.log(`Thread length monitor enabled with interval ${intervalMs}ms.`)
void run()
monitorInterval = setInterval(() => {
void run()
}, intervalMs)
if (typeof monitorInterval.unref === "function") {
monitorInterval.unref()
}
}