-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathbanUserId.ts
More file actions
205 lines (190 loc) · 7.01 KB
/
banUserId.ts
File metadata and controls
205 lines (190 loc) · 7.01 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
import { DiscordAPIError, Snowflake } from "discord.js";
import { GuildPluginData } from "vety";
import { CaseTypes } from "../../../data/CaseTypes.js";
import { LogType } from "../../../data/LogType.js";
import { registerExpiringTempban } from "../../../data/loops/expiringTempbansLoop.js";
import { humanizeDuration } from "../../../humanizeDuration.js";
import { logger } from "../../../logger.js";
import { TemplateParseError, TemplateSafeValueContainer, renderTemplate } from "../../../templateFormatter.js";
import {
DAYS,
SECONDS,
UserNotificationResult,
createUserNotificationError,
notifyUser,
resolveMember,
resolveUser,
ucfirst,
} from "../../../utils.js";
import { userToTemplateSafeUser } from "../../../utils/templateSafeObjects.js";
import { CasesPlugin } from "../../Cases/CasesPlugin.js";
import { LogsPlugin } from "../../Logs/LogsPlugin.js";
import { BanOptions, BanResult, IgnoredEventType, ModActionsPluginType } from "../types.js";
import { getDefaultContactMethods } from "./getDefaultContactMethods.js";
import { ignoreEvent } from "./ignoreEvent.js";
/**
* Ban the specified user id, whether or not they're actually on the server at the time. Generates a case.
*/
export async function banUserId(
pluginData: GuildPluginData<ModActionsPluginType>,
userId: string,
reason?: string,
reasonWithAttachments?: string,
banOptions: BanOptions = {},
banTime?: number,
): Promise<BanResult> {
const config = pluginData.config.get();
const user = await resolveUser(pluginData.client, userId, "ModActions:banUserId");
if (!user.id) {
return {
status: "failed",
error: "Invalid user",
};
}
// Attempt to message the user *before* banning them, as doing it after may not be possible
const member = await resolveMember(pluginData.client, pluginData.guild, userId);
let notifyResult: UserNotificationResult = { method: null, success: true };
if (reasonWithAttachments && member) {
const contactMethods = banOptions?.contactMethods
? banOptions.contactMethods
: getDefaultContactMethods(pluginData, "ban");
if (contactMethods.length) {
if (!banTime && config.ban_message) {
let banMessage: string;
try {
banMessage = await renderTemplate(
config.ban_message,
new TemplateSafeValueContainer({
guildName: pluginData.guild.name,
reason: reasonWithAttachments,
moderator: banOptions.caseArgs?.modId
? userToTemplateSafeUser(await resolveUser(pluginData.client, banOptions.caseArgs.modId, "ModActions:banUserId"))
: null,
}),
);
} catch (err) {
if (err instanceof TemplateParseError) {
return {
status: "failed",
error: `Invalid ban_message format: ${err.message}`,
};
}
throw err;
}
notifyResult = await notifyUser(member.user, banMessage, contactMethods);
} else if (banTime && config.tempban_message) {
let banMessage: string;
try {
banMessage = await renderTemplate(
config.tempban_message,
new TemplateSafeValueContainer({
guildName: pluginData.guild.name,
reason: reasonWithAttachments,
moderator: banOptions.caseArgs?.modId
? userToTemplateSafeUser(await resolveUser(pluginData.client, banOptions.caseArgs.modId, "ModActions:banUserId"))
: null,
banTime: humanizeDuration(banTime),
}),
);
} catch (err) {
if (err instanceof TemplateParseError) {
return {
status: "failed",
error: `Invalid tempban_message format: ${err.message}`,
};
}
throw err;
}
notifyResult = await notifyUser(member.user, banMessage, contactMethods);
} else {
notifyResult = createUserNotificationError("No ban/tempban message specified in config");
}
}
}
// (Try to) ban the user
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_BAN, userId);
ignoreEvent(pluginData, IgnoredEventType.Ban, userId);
try {
const deleteMessageDays = Math.min(7, Math.max(0, banOptions.deleteMessageDays ?? 1));
await pluginData.guild.bans.create(userId as Snowflake, {
deleteMessageSeconds: (deleteMessageDays * DAYS) / SECONDS,
reason: reason ?? undefined,
});
} catch (e) {
let errorMessage;
if (e instanceof DiscordAPIError) {
errorMessage = `API error ${e.code}: ${e.message}`;
} else {
logger.warn(`Error applying ban to ${userId}: ${e}`);
errorMessage = "Unknown error";
}
return {
status: "failed",
error: errorMessage,
};
}
const tempbanLock = await pluginData.locks.acquire(`tempban-${user.id}`);
const existingTempban = await pluginData.state.tempbans.findExistingTempbanForUserId(user.id);
const banExpiresAt = banTime && banTime > 0 ? Date.now() + banTime : null;
const banExpiryTimestamp = banExpiresAt ? Math.ceil(banExpiresAt / 1000) : null;
const banExpiryRelative = banExpiryTimestamp ? `<t:${banExpiryTimestamp}:R>` : null;
if (banTime && banTime > 0) {
const selfId = pluginData.client.user!.id;
if (existingTempban) {
await pluginData.state.tempbans.updateExpiryTime(user.id, banTime, banOptions.modId ?? selfId);
} else {
await pluginData.state.tempbans.addTempban(user.id, banTime, banOptions.modId ?? selfId);
}
const tempban = (await pluginData.state.tempbans.findExistingTempbanForUserId(user.id))!;
registerExpiringTempban(tempban);
}
tempbanLock.unlock();
// Create a case for this action
const modId = banOptions.caseArgs?.modId || pluginData.client.user!.id;
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const noteDetails: string[] = [];
const timeUntilUnban = banTime ? humanizeDuration(banTime) : "indefinite";
if (notifyResult.text) {
noteDetails.push(ucfirst(notifyResult.text));
}
if (banTime && banTime > 0) {
noteDetails.push(`Banned for ${timeUntilUnban}`);
if (banExpiryRelative) {
noteDetails.push(`Expires ${banExpiryRelative}`);
}
} else {
noteDetails.push("Banned indefinitely");
}
const createdCase = await casesPlugin.createCase({
...(banOptions.caseArgs || {}),
userId,
modId,
type: CaseTypes.Ban,
reason,
noteDetails,
});
// Log the action
const mod = await resolveUser(pluginData.client, modId, "ModActions:banUserId");
if (banTime) {
pluginData.getPlugin(LogsPlugin).logMemberTimedBan({
mod,
user,
caseNumber: createdCase.case_number,
reason: reason ?? "",
banTime: humanizeDuration(banTime),
});
} else {
pluginData.getPlugin(LogsPlugin).logMemberBan({
mod,
user,
caseNumber: createdCase.case_number,
reason: reason ?? "",
});
}
pluginData.state.events.emit("ban", user.id, reason, banOptions.isAutomodAction);
return {
status: "success",
case: createdCase,
notifyResult,
};
}