3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-05-10 12:25:02 +00:00

feat: timeout support

This commit is contained in:
Dragory 2023-04-01 18:33:09 +03:00 committed by Miikka
parent 06877e90cc
commit 39e0dfa27f
23 changed files with 532 additions and 92 deletions

View file

@ -15,10 +15,12 @@ import { ClearMutesWithoutRoleCmd } from "./commands/ClearMutesWithoutRoleCmd";
import { MutesCmd } from "./commands/MutesCmd";
import { ClearActiveMuteOnMemberBanEvt } from "./events/ClearActiveMuteOnMemberBanEvt";
import { ReapplyActiveMuteOnJoinEvt } from "./events/ReapplyActiveMuteOnJoinEvt";
import { RegisterManualTimeoutsEvt } from "./events/RegisterManualTimeoutsEvt";
import { clearMute } from "./functions/clearMute";
import { muteUser } from "./functions/muteUser";
import { offMutesEvent } from "./functions/offMutesEvent";
import { onMutesEvent } from "./functions/onMutesEvent";
import { renewTimeoutMute } from "./functions/renewTimeoutMute";
import { unmuteUser } from "./functions/unmuteUser";
import { ConfigSchema, MutesPluginType } from "./types";
@ -85,6 +87,7 @@ export const MutesPlugin = zeppelinGuildPlugin<MutesPluginType>()({
// ClearActiveMuteOnRoleRemovalEvt, // FIXME: Temporarily disabled for performance
ClearActiveMuteOnMemberBanEvt,
ReapplyActiveMuteOnJoinEvt,
RegisterManualTimeoutsEvt,
],
public: {
@ -118,13 +121,24 @@ export const MutesPlugin = zeppelinGuildPlugin<MutesPluginType>()({
afterLoad(pluginData) {
const { state, guild } = pluginData;
state.unregisterGuildEventListener = onGuildEvent(guild.id, "expiredMute", (mute) => clearMute(pluginData, mute));
state.unregisterExpiredRoleMuteListener = onGuildEvent(guild.id, "expiredMute", (mute) =>
clearMute(pluginData, mute),
);
state.unregisterTimeoutMuteToRenewListener = onGuildEvent(guild.id, "timeoutMuteToRenew", (mute) =>
renewTimeoutMute(pluginData, mute),
);
const muteRole = pluginData.config.get().mute_role;
if (muteRole) {
state.mutes.fillMissingMuteRole(muteRole);
}
},
beforeUnload(pluginData) {
const { state, guild } = pluginData;
state.unregisterGuildEventListener?.();
state.unregisterExpiredRoleMuteListener?.();
state.unregisterTimeoutMuteToRenewListener?.();
state.events.removeAllListeners();
},
});

View file

@ -1,4 +1,5 @@
import { Snowflake } from "discord.js";
import { MuteTypes } from "../../../data/MuteTypes";
import { memberRolesLock } from "../../../utils/lockNameHelpers";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { mutesEvt } from "../types";
@ -10,18 +11,25 @@ export const ReapplyActiveMuteOnJoinEvt = mutesEvt({
event: "guildMemberAdd",
async listener({ pluginData, args: { member } }) {
const mute = await pluginData.state.mutes.findExistingMuteForUserId(member.id);
if (mute) {
if (!mute) {
return;
}
if (mute.type === MuteTypes.Role) {
const muteRole = pluginData.config.get().mute_role;
if (muteRole) {
const memberRoleLock = await pluginData.locks.acquire(memberRolesLock(member));
await member.roles.add(muteRole as Snowflake);
memberRoleLock.unlock();
try {
await member.roles.add(muteRole as Snowflake);
} finally {
memberRoleLock.unlock();
}
}
pluginData.getPlugin(LogsPlugin).logMemberMuteRejoin({
member,
});
}
pluginData.getPlugin(LogsPlugin).logMemberMuteRejoin({
member,
});
},
});

View file

@ -0,0 +1,52 @@
import { AuditLogChange, AuditLogEvent } from "discord.js";
import moment from "moment-timezone";
import { MuteTypes } from "../../../data/MuteTypes";
import { resolveUser } from "../../../utils";
import { mutesEvt } from "../types";
export const RegisterManualTimeoutsEvt = mutesEvt({
event: "guildAuditLogEntryCreate",
async listener({ pluginData, args: { auditLogEntry } }) {
// Ignore the bot's own audit log events
if (auditLogEntry.executorId === pluginData.client.user?.id) {
return;
}
if (auditLogEntry.action !== AuditLogEvent.MemberUpdate) {
return;
}
const target = await resolveUser(pluginData.client, auditLogEntry.targetId!);
// Only act based on the last changes in this log
let lastTimeoutChange: AuditLogChange | null = null;
for (const change of auditLogEntry.changes) {
if (change.key === "communication_disabled_until") {
lastTimeoutChange = change;
}
}
if (!lastTimeoutChange) {
return;
}
const existingMute = await pluginData.state.mutes.findExistingMuteForUserId(target.id);
if (lastTimeoutChange.new == null && existingMute) {
await pluginData.state.mutes.clear(target.id);
return;
}
if (lastTimeoutChange.new != null) {
const expiresAtTimestamp = moment.utc(lastTimeoutChange.new as string).valueOf();
if (existingMute) {
await pluginData.state.mutes.updateExpiresAt(target.id, expiresAtTimestamp);
} else {
await pluginData.state.mutes.addMute({
userId: target.id,
type: MuteTypes.Timeout,
expiresAt: expiresAtTimestamp,
timeoutExpiresAt: expiresAtTimestamp,
});
}
}
},
});

View file

@ -2,6 +2,7 @@ import { GuildMember } from "discord.js";
import { GuildPluginData } from "knub";
import { Mute } from "../../../data/entities/Mute";
import { clearExpiringMute } from "../../../data/loops/expiringMutesLoop";
import { MuteTypes } from "../../../data/MuteTypes";
import { resolveMember, verboseUserMention } from "../../../utils";
import { memberRolesLock } from "../../../utils/lockNameHelpers";
import { LogsPlugin } from "../../Logs/LogsPlugin";
@ -24,22 +25,36 @@ export async function clearMute(
const lock = await pluginData.locks.acquire(memberRolesLock(member));
try {
const muteRole = pluginData.config.get().mute_role;
if (muteRole) {
await member.roles.remove(muteRole);
}
if (mute?.roles_to_restore) {
const guildRoles = pluginData.guild.roles.cache;
const newRoles = [...member.roles.cache.keys()].filter((roleId) => roleId !== muteRole);
for (const toRestore of mute?.roles_to_restore) {
if (guildRoles.has(toRestore) && toRestore !== muteRole && !newRoles.includes(toRestore)) {
newRoles.push(toRestore);
}
}
await member.roles.set(newRoles);
}
const defaultMuteRole = pluginData.config.get().mute_role;
if (mute) {
const muteRole = mute.mute_role || pluginData.config.get().mute_role;
lock.unlock();
if (mute.type === MuteTypes.Role) {
if (muteRole) {
await member.roles.remove(muteRole);
}
} else {
await member.timeout(null);
}
if (mute.roles_to_restore) {
const guildRoles = pluginData.guild.roles.cache;
const newRoles = [...member.roles.cache.keys()].filter((roleId) => roleId !== muteRole);
for (const toRestore of mute?.roles_to_restore) {
if (guildRoles.has(toRestore) && toRestore !== muteRole && !newRoles.includes(toRestore)) {
newRoles.push(toRestore);
}
}
await member.roles.set(newRoles);
}
} else {
// Unmuting someone without an active mute -> remove timeouts and/or mute role
const muteRole = pluginData.config.get().mute_role;
if (muteRole) {
await member.roles.remove(muteRole);
}
await member.timeout(null);
}
} catch {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Failed to remove mute role from ${verboseUserMention(member.user)}`,

View file

@ -0,0 +1,8 @@
import { GuildPluginData } from "knub";
import { MuteTypes } from "../../../data/MuteTypes";
import { MutesPluginType } from "../types";
export function getDefaultMuteType(pluginData: GuildPluginData<MutesPluginType>): MuteTypes {
const muteRole = pluginData.config.get().mute_role;
return muteRole ? MuteTypes.Role : MuteTypes.Timeout;
}

View file

@ -0,0 +1,15 @@
import { MAX_TIMEOUT_DURATION } from "../../../data/Mutes";
/**
* Since timeouts have a limited duration (max 28d) but we support mutes longer than that,
* the timeouts are applied for a certain duration at first and then renewed as necessary.
* This function returns the initial end time for a timeout.
* @param muteTime Time to mute for in ms
* @return - Timestamp of the
*/
export function getTimeoutExpiryTime(muteExpiresAt: number | null | undefined): number {
if (muteExpiresAt && muteExpiresAt <= MAX_TIMEOUT_DURATION) {
return muteExpiresAt;
}
return Date.now() + MAX_TIMEOUT_DURATION;
}

View file

@ -4,7 +4,9 @@ import { GuildPluginData } from "knub";
import { CaseTypes } from "../../../data/CaseTypes";
import { Case } from "../../../data/entities/Case";
import { Mute } from "../../../data/entities/Mute";
import { AddMuteParams } from "../../../data/GuildMutes";
import { registerExpiringMute } from "../../../data/loops/expiringMutesLoop";
import { MuteTypes } from "../../../data/MuteTypes";
import { LogsPlugin } from "../../../plugins/Logs/LogsPlugin";
import { ERRORS, RecoverablePluginError } from "../../../RecoverablePluginError";
import { renderTemplate, TemplateSafeValueContainer } from "../../../templateFormatter";
@ -20,6 +22,8 @@ import { muteLock } from "../../../utils/lockNameHelpers";
import { userToTemplateSafeUser } from "../../../utils/templateSafeObjects";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { MuteOptions, MutesPluginType } from "../types";
import { getDefaultMuteType } from "./getDefaultMuteType";
import { getTimeoutExpiryTime } from "./getTimeoutExpiryTime";
/**
* TODO: Clean up this function
@ -36,12 +40,9 @@ export async function muteUser(
const lock = await pluginData.locks.acquire(muteLock({ id: userId }));
const muteRole = pluginData.config.get().mute_role;
if (!muteRole) {
lock.unlock();
throw new RecoverablePluginError(ERRORS.NO_MUTE_ROLE_IN_CONFIG);
}
const timeUntilUnmute = muteTime ? humanizeDuration(muteTime) : "indefinite";
const muteType = getDefaultMuteType(pluginData);
const muteExpiresAt = muteTime ? Date.now() + muteTime : null;
const timeoutUntil = getTimeoutExpiryTime(muteExpiresAt);
// No mod specified -> mark Zeppelin as the mod
if (!muteOptions.caseArgs?.modId) {
@ -67,7 +68,7 @@ export async function muteUser(
const removeRoles = removeRolesOnMuteOverride ?? config.remove_roles_on_mute;
const restoreRoles = restoreRolesOnMuteOverride ?? config.restore_roles_on_mute;
// remove roles
// Remove roles
if (!Array.isArray(removeRoles)) {
if (removeRoles) {
// exclude managed roles from being removed
@ -80,7 +81,7 @@ export async function muteUser(
await member.roles.set(newRoles as Snowflake[]);
}
// set roles to be restored
// Set roles to be restored
if (!Array.isArray(restoreRoles)) {
if (restoreRoles) {
rolesToRestore = currentUserRoles;
@ -89,38 +90,42 @@ export async function muteUser(
rolesToRestore = currentUserRoles.filter((x) => (<string[]>restoreRoles).includes(x));
}
// Apply mute role if it's missing
if (!currentUserRoles.includes(muteRole as Snowflake)) {
try {
await member.roles.add(muteRole as Snowflake);
} catch (e) {
const actualMuteRole = pluginData.guild.roles.cache.get(muteRole as Snowflake);
if (!actualMuteRole) {
lock.unlock();
logs.logBotAlert({
body: `Cannot mute users, specified mute role Id is invalid`,
});
throw new RecoverablePluginError(ERRORS.INVALID_MUTE_ROLE_ID);
}
if (muteType === MuteTypes.Role) {
// Apply mute role if it's missing
if (!currentUserRoles.includes(muteRole!)) {
try {
await member.roles.add(muteRole!);
} catch (e) {
const actualMuteRole = pluginData.guild.roles.cache.get(muteRole!);
if (!actualMuteRole) {
lock.unlock();
logs.logBotAlert({
body: `Cannot mute users, specified mute role Id is invalid`,
});
throw new RecoverablePluginError(ERRORS.INVALID_MUTE_ROLE_ID);
}
const zep = await resolveMember(pluginData.client, pluginData.guild, pluginData.client.user!.id);
const zepRoles = pluginData.guild.roles.cache.filter((x) => zep!.roles.cache.has(x.id));
// If we have roles and one of them is above the muted role, throw generic error
if (zepRoles.size >= 0 && zepRoles.some((zepRole) => zepRole.position > actualMuteRole.position)) {
lock.unlock();
logs.logBotAlert({
body: `Cannot mute user ${member.id}: ${e}`,
});
throw e;
} else {
// Otherwise, throw error that mute role is above zeps roles
lock.unlock();
logs.logBotAlert({
body: `Cannot mute users, specified mute role is above Zeppelin in the role hierarchy`,
});
throw new RecoverablePluginError(ERRORS.MUTE_ROLE_ABOVE_ZEP, pluginData.guild);
const zep = await resolveMember(pluginData.client, pluginData.guild, pluginData.client.user!.id);
const zepRoles = pluginData.guild.roles.cache.filter((x) => zep!.roles.cache.has(x.id));
// If we have roles and one of them is above the muted role, throw generic error
if (zepRoles.size >= 0 && zepRoles.some((zepRole) => zepRole.position > actualMuteRole.position)) {
lock.unlock();
logs.logBotAlert({
body: `Cannot mute user ${member.id}: ${e}`,
});
throw e;
} else {
// Otherwise, throw error that mute role is above zeps roles
lock.unlock();
logs.logBotAlert({
body: `Cannot mute users, specified mute role is above Zeppelin in the role hierarchy`,
});
throw new RecoverablePluginError(ERRORS.MUTE_ROLE_ABOVE_ZEP, pluginData.guild);
}
}
}
} else {
await member.disableCommunicationUntil(timeoutUntil);
}
// If enabled, move the user to the mute voice channel (e.g. afk - just to apply the voice perms from the mute role)
@ -144,13 +149,28 @@ export async function muteUser(
rolesToRestore = Array.from(new Set([...existingMute.roles_to_restore, ...rolesToRestore]));
}
await pluginData.state.mutes.updateExpiryTime(user.id, muteTime, rolesToRestore);
if (muteType === MuteTypes.Timeout) {
await pluginData.state.mutes.updateTimeoutExpiresAt(user.id, timeoutUntil);
}
finalMute = (await pluginData.state.mutes.findExistingMuteForUserId(user.id))!;
} else {
finalMute = await pluginData.state.mutes.addMute(user.id, muteTime, rolesToRestore);
const muteParams: AddMuteParams = {
userId: user.id,
type: muteType,
expiresAt: muteExpiresAt,
rolesToRestore,
};
if (muteType === MuteTypes.Role) {
muteParams.muteRole = muteRole;
} else {
muteParams.timeoutExpiresAt = timeoutUntil;
}
finalMute = await pluginData.state.mutes.addMute(muteParams);
}
registerExpiringMute(finalMute);
const timeUntilUnmuteStr = muteTime ? humanizeDuration(muteTime) : "indefinite";
const template = existingMute
? config.update_mute_message
: muteTime
@ -164,7 +184,7 @@ export async function muteUser(
new TemplateSafeValueContainer({
guildName: pluginData.guild.name,
reason: reason || "None",
time: timeUntilUnmute,
time: timeUntilUnmuteStr,
moderator: muteOptions.caseArgs?.modId
? userToTemplateSafeUser(await resolveUser(pluginData.client, muteOptions.caseArgs.modId))
: null,
@ -201,7 +221,7 @@ export async function muteUser(
if (theCase) {
// Update old case
const noteDetails = [`Mute updated to ${muteTime ? timeUntilUnmute : "indefinite"}`];
const noteDetails = [`Mute updated to ${muteTime ? timeUntilUnmuteStr : "indefinite"}`];
const reasons = reason ? [reason] : [];
if (muteOptions.caseArgs?.extraNotes) {
reasons.push(...muteOptions.caseArgs.extraNotes);
@ -217,7 +237,7 @@ export async function muteUser(
}
} else {
// Create new case
const noteDetails = [`Muted ${muteTime ? `for ${timeUntilUnmute}` : "indefinitely"}`];
const noteDetails = [`Muted ${muteTime ? `for ${timeUntilUnmuteStr}` : "indefinitely"}`];
if (notifyResult.text) {
noteDetails.push(ucfirst(notifyResult.text));
}
@ -239,7 +259,7 @@ export async function muteUser(
pluginData.getPlugin(LogsPlugin).logMemberTimedMute({
mod,
user,
time: timeUntilUnmute,
time: timeUntilUnmuteStr,
caseNumber: theCase.case_number,
reason: reason ?? "",
});

View file

@ -0,0 +1,22 @@
import { GuildPluginData } from "knub";
import moment from "moment-timezone";
import { Mute } from "../../../data/entities/Mute";
import { MAX_TIMEOUT_DURATION } from "../../../data/Mutes";
import { DBDateFormat, resolveMember } from "../../../utils";
import { MutesPluginType } from "../types";
export async function renewTimeoutMute(pluginData: GuildPluginData<MutesPluginType>, mute: Mute) {
const member = await resolveMember(pluginData.client, pluginData.guild, mute.user_id, true);
if (!member) {
return;
}
let newExpiryTime = moment.utc().add(MAX_TIMEOUT_DURATION).format(DBDateFormat);
if (mute.expires_at && newExpiryTime > mute.expires_at) {
newExpiryTime = mute.expires_at;
}
const expiryTimestamp = moment.utc(newExpiryTime).valueOf();
await member.disableCommunicationUntil(expiryTimestamp);
await pluginData.state.mutes.updateTimeoutExpiresAt(mute.user_id, expiryTimestamp);
}

View file

@ -2,12 +2,17 @@ import { Snowflake } from "discord.js";
import humanizeDuration from "humanize-duration";
import { GuildPluginData } from "knub";
import { CaseTypes } from "../../../data/CaseTypes";
import { Mute } from "../../../data/entities/Mute";
import { AddMuteParams } from "../../../data/GuildMutes";
import { MuteTypes } from "../../../data/MuteTypes";
import { resolveMember, resolveUser } from "../../../utils";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { CaseArgs } from "../../Cases/types";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { MutesPluginType, UnmuteResult } from "../types";
import { clearMute } from "./clearMute";
import { getDefaultMuteType } from "./getDefaultMuteType";
import { getTimeoutExpiryTime } from "./getTimeoutExpiryTime";
import { memberHasMutedRole } from "./memberHasMutedRole";
export async function unmuteUser(
@ -21,15 +26,43 @@ export async function unmuteUser(
const member = await resolveMember(pluginData.client, pluginData.guild, userId, true); // Grab the fresh member so we don't have stale role info
const modId = caseArgs.modId || pluginData.client.user!.id;
if (!existingMute && member && !memberHasMutedRole(pluginData, member)) return null;
if (
!existingMute &&
member &&
!memberHasMutedRole(pluginData, member) &&
!member?.communicationDisabledUntilTimestamp
) {
return null;
}
if (unmuteTime) {
// Schedule timed unmute (= just set the mute's duration)
// Schedule timed unmute (= just update the mute's duration)
const muteExpiresAt = Date.now() + unmuteTime;
const timeoutExpiresAt = getTimeoutExpiryTime(muteExpiresAt);
let createdMute: Mute | null = null;
if (!existingMute) {
await pluginData.state.mutes.addMute(userId, unmuteTime);
const defaultMuteType = getDefaultMuteType(pluginData);
const muteParams: AddMuteParams = {
userId,
type: defaultMuteType,
expiresAt: muteExpiresAt,
};
if (defaultMuteType === MuteTypes.Role) {
muteParams.muteRole = pluginData.config.get().mute_role;
} else {
muteParams.timeoutExpiresAt = timeoutExpiresAt;
}
createdMute = await pluginData.state.mutes.addMute(muteParams);
} else {
await pluginData.state.mutes.updateExpiryTime(userId, unmuteTime);
}
// Update timeout
if (existingMute?.type === MuteTypes.Timeout || createdMute?.type === MuteTypes.Timeout) {
await member?.disableCommunicationUntil(timeoutExpiresAt);
await pluginData.state.mutes.updateTimeoutExpiresAt(userId, timeoutExpiresAt);
}
} else {
// Unmute immediately
clearMute(pluginData, existingMute);

View file

@ -50,7 +50,8 @@ export interface MutesPluginType extends BasePluginType {
serverLogs: GuildLogs;
archives: GuildArchives;
unregisterGuildEventListener: () => void;
unregisterExpiredRoleMuteListener: () => void;
unregisterTimeoutMuteToRenewListener: () => void;
events: MutesEventEmitter;
};