all repos — stealth-developers @ 7630fcbf36d37076f1fd7e64a755a7d73fda56be

src/tasks/ticketWatcher.ts (view raw)

 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
import { db, ticketMessages, tickets } from "@/database";
import { getGuild } from "@/database/queries";
import { loggers } from "@/utils/logging";
import { type Client } from "discord.js";
import { and, desc, eq } from "drizzle-orm";

const logger = loggers.events.child({ name: "ticketWatcher" });

const WARN_MS = 15 * 60 * 1000;
const CLOSE_MS = 30 * 60 * 1000;
const UNCLAIM_MS = 5 * 60 * 1000;
const INTERVAL_MS = 60 * 1000;

export function startTicketWatcher(client: Client) {
	if (!client) throw new Error("client is required to start ticket watcher");

	logger.info("starting ticket watcher");

	let running = false;

	const run = async () => {
		if (running) {
			logger.warn(
				"previous ticket watcher run still in progress, skipping this tick",
			);
			return;
		}
    running = true;

		try {
			const openTickets = await db
				.select()
				.from(tickets)
				.where(eq(tickets.status, "open"))
				.execute();

      for (const ticket of openTickets) {
				try {
					if (ticket.claimedBy && ticket.claimedAt) {
            const claimedAt = new Date(ticket.claimedAt).getTime();
            if (Date.now() - claimedAt > UNCLAIM_MS) {
							const [lastModMsg] = await db
								.select()
								.from(ticketMessages)
								.where(
									and(
										eq(ticketMessages.ticketId, ticket.id),
										eq(ticketMessages.authorType, "staff"),
										eq(ticketMessages.authorId, ticket.claimedBy),
									),
								)
								.orderBy(desc(ticketMessages.createdAt))
								.limit(1)
								.execute();

							const lastModActivity = lastModMsg
								? new Date(lastModMsg.createdAt).getTime()
								: claimedAt;

              if (Date.now() - lastModActivity > UNCLAIM_MS) {
								const [lastUserMsg] = await db
									.select()
									.from(ticketMessages)
									.where(
										and(
											eq(ticketMessages.ticketId, ticket.id),
											eq(ticketMessages.authorType, "user"),
										),
									)
									.orderBy(desc(ticketMessages.createdAt))
									.limit(1)
									.execute();

								if (
									lastUserMsg &&
									new Date(lastUserMsg.createdAt).getTime() > lastModActivity
								) {
									await db
										.update(tickets)
										.set({
											claimedBy: null,
											claimedAt: null,
										})
										.where(eq(tickets.id, ticket.id))
										.execute();

									continue;
								}
              }
						}
					}

					const createdAt = ticket.createdAt
						? new Date(ticket.createdAt).getTime()
						: null;
					if (!createdAt) continue;

					const age = Date.now() - createdAt;

					const userMsgs = await db
						.select()
						.from(ticketMessages)
						.where(
							and(
								eq(ticketMessages.ticketId, ticket.id),
								eq(ticketMessages.authorType, "user"),
							),
						)
						.execute();

					const hasUserMessages = userMsgs && userMsgs.length > 0;
					if (hasUserMessages) continue;

					if (!ticket.warnedAt && age >= WARN_MS && age < CLOSE_MS) {
						if (ticket.channelId && ticket.guildId) {
							try {
								const channel = await client.channels
									.fetch(ticket.channelId)
									.catch(() => null);
								if (channel?.isSendable()) {
									await channel.send(
										`<@${ticket.authorId}>, this ticket will be automatically archived in 15 minutes due to inactivity. Please send a message in this channel to keep it open.`,
									);
								}
							} catch (err) {
								logger.error(err, `failed to warn for ticket ${ticket.id}`);
							}
						}

						await db
							.update(tickets)
							.set({ warnedAt: new Date() })
							.where(eq(tickets.id, ticket.id))
							.execute();

						logger.info(`warned ticket ${ticket.id}`);
						continue;
					}

					if (age >= CLOSE_MS) {
						await db
							.update(tickets)
							.set({
								status: "archived",
								closedAt: new Date(),
								closedBy: "system",
								closeReason: "Auto-archived due to inactivity",
							})
							.where(eq(tickets.id, ticket.id))
							.execute();

						if (ticket.channelId && ticket.guildId) {
							try {
								const channel = await client.channels
									.fetch(ticket.channelId)
									.catch(() => null);

								if (!channel) continue;

								await channel.delete(
									`Auto-archived due to inactivity for ticket ${ticket.id}`,
								);

								const authorId = ticket.authorId;
								if (authorId) {
									const user = await client.users
										.fetch(authorId)
										.catch(() => null);
									if (user) {
										await user
											.send(
												`Your ticket #${ticket.id} has been archived due to inactivity. You can open a new ticket at any time.`,
											)
											.catch(() => null);
									}
								}

								const { data: guildData, exists: guildExists } = await getGuild(
									ticket.guildId,
								);
								if (!guildExists) continue;

								const transcriptChannelId = guildData?.ticket_channel_id;
								if (!transcriptChannelId) continue;

								const transcriptChannel = await client.channels
									.fetch(transcriptChannelId)
									.catch(() => null);
								if (!transcriptChannel?.isTextBased()) continue;

								if (transcriptChannel.isSendable())
									await transcriptChannel.send({
										content: `Ticket #${ticket.id} has been archived due to inactivity.`,
									});
							} catch (err) {
								logger.error(
									err,
									`failed to delete channel for ticket ${ticket.id}`,
								);
							}
						}

						logger.info(
							`archived and deleted ticket ${ticket.id} due to inactivity`,
						);
					}
				} catch (errTicket) {
					logger.error(errTicket, `error processing ticket ${ticket.id}`);
				}
			}
		} catch (err) {
			logger.error(err, "ticket watcher run failed");
		} finally {
			running = false;
		}
	};

	void run();
	const id = setInterval(run, INTERVAL_MS);

	return {
		stop() {
			clearInterval(id);
			logger.info("stopped ticket watcher");
		},
	};
}