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

Centralize periodic checks for mutes, tempbans, vcalerts, reminders, and scheduled posts

This should result in a significant performance improvement.
The new method is also more precise than the old one, allowing
the aforementioned checks to be performed with second-precision.
This commit is contained in:
Dragory 2021-09-25 21:33:59 +03:00
parent c84d1a0be1
commit c7751a9da1
No known key found for this signature in database
GPG key ID: 5F387BA66DF8AAC1
55 changed files with 883 additions and 366 deletions

View file

@ -9,8 +9,8 @@ import { GuildBanRemoveAlertsEvt } from "./events/BanRemoveAlertsEvt";
import { VoiceStateUpdateAlertEvt } from "./events/SendAlertsEvts";
import { ConfigSchema, LocateUserPluginType } from "./types";
import { fillActiveAlertsList } from "./utils/fillAlertsList";
import { outdatedAlertsLoop } from "./utils/outdatedLoop";
import Timeout = NodeJS.Timeout;
import { onGuildEvent } from "../../data/GuildEvents";
import { clearExpiredAlert } from "./utils/clearExpiredAlert";
const defaultOptions: PluginOptions<LocateUserPluginType> = {
config: {
@ -61,18 +61,17 @@ export const LocateUserPlugin = zeppelinGuildPlugin<LocateUserPluginType>()({
const { state, guild } = pluginData;
state.alerts = GuildVCAlerts.getGuildInstance(guild.id);
state.outdatedAlertsTimeout = null;
state.usersWithAlerts = [];
state.unloaded = false;
},
afterLoad(pluginData) {
outdatedAlertsLoop(pluginData);
pluginData.state.unregisterGuildEventListener = onGuildEvent(pluginData.guild.id, "expiredVCAlert", (alert) =>
clearExpiredAlert(pluginData, alert),
);
fillActiveAlertsList(pluginData);
},
beforeUnload(pluginData) {
clearTimeout(pluginData.state.outdatedAlertsTimeout as Timeout);
pluginData.state.unloaded = true;
pluginData.state.unregisterGuildEventListener();
},
});

View file

@ -4,6 +4,7 @@ import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { MINUTES, SECONDS } from "../../../utils";
import { locateUserCmd } from "../types";
import { registerExpiringVCAlert } from "../../../data/loops/expiringVCAlertsLoop";
export const FollowCmd = locateUserCmd({
trigger: ["follow", "f"],
@ -30,7 +31,7 @@ export const FollowCmd = locateUserCmd({
return;
}
await pluginData.state.alerts.add(
const alert = await pluginData.state.alerts.add(
msg.author.id,
args.member.id,
msg.channel.id,
@ -38,6 +39,8 @@ export const FollowCmd = locateUserCmd({
body,
active,
);
registerExpiringVCAlert(alert);
if (!pluginData.state.usersWithAlerts.includes(args.member.id)) {
pluginData.state.usersWithAlerts.push(args.member.id);
}

View file

@ -2,6 +2,7 @@ import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { createChunkedMessage, sorter } from "../../../utils";
import { locateUserCmd } from "../types";
import { clearExpiringVCAlert } from "../../../data/loops/expiringVCAlertsLoop";
export const ListFollowCmd = locateUserCmd({
trigger: ["follows", "fs"],
@ -50,6 +51,7 @@ export const DeleteFollowCmd = locateUserCmd({
}
const toDelete = alerts[args.num - 1];
clearExpiringVCAlert(toDelete);
await pluginData.state.alerts.delete(toDelete.id);
sendSuccessMessage(pluginData, msg.channel, "Alert deleted");

View file

@ -1,4 +1,5 @@
import { locateUserEvt } from "../types";
import { clearExpiringVCAlert } from "../../../data/loops/expiringVCAlertsLoop";
export const GuildBanRemoveAlertsEvt = locateUserEvt({
event: "guildBanAdd",
@ -6,6 +7,7 @@ export const GuildBanRemoveAlertsEvt = locateUserEvt({
async listener(meta) {
const alerts = await meta.pluginData.state.alerts.getAlertsByUserId(meta.args.ban.user.id);
alerts.forEach((alert) => {
clearExpiringVCAlert(alert);
meta.pluginData.state.alerts.delete(alert.id);
});
},

View file

@ -13,9 +13,8 @@ export interface LocateUserPluginType extends BasePluginType {
config: TConfigSchema;
state: {
alerts: GuildVCAlerts;
outdatedAlertsTimeout: Timeout | null;
usersWithAlerts: string[];
unloaded: boolean;
unregisterGuildEventListener: () => void;
};
}

View file

@ -0,0 +1,9 @@
import { GuildPluginData } from "knub";
import { LocateUserPluginType } from "../types";
import { removeUserIdFromActiveAlerts } from "./removeUserIdFromActiveAlerts";
import { VCAlert } from "../../../data/entities/VCAlert";
export async function clearExpiredAlert(pluginData: GuildPluginData<LocateUserPluginType>, alert: VCAlert) {
await pluginData.state.alerts.delete(alert.id);
await removeUserIdFromActiveAlerts(pluginData, alert.user_id);
}

View file

@ -1,19 +0,0 @@
import { GuildPluginData } from "knub";
import { SECONDS } from "../../../utils";
import { LocateUserPluginType } from "../types";
import { removeUserIdFromActiveAlerts } from "./removeUserIdFromActiveAlerts";
const ALERT_LOOP_TIME = 30 * SECONDS;
export async function outdatedAlertsLoop(pluginData: GuildPluginData<LocateUserPluginType>) {
const outdatedAlerts = await pluginData.state.alerts.getOutdatedAlerts();
for (const alert of outdatedAlerts) {
await pluginData.state.alerts.delete(alert.id);
await removeUserIdFromActiveAlerts(pluginData, alert.user_id);
}
if (!pluginData.state.unloaded) {
pluginData.state.outdatedAlertsTimeout = setTimeout(() => outdatedAlertsLoop(pluginData), ALERT_LOOP_TIME);
}
}

View file

@ -3,12 +3,12 @@ import { LogsPluginType } from "../types";
import { LogType } from "../../../data/LogType";
import { log } from "../util/log";
import { createTypedTemplateSafeValueContainer } from "../../../templateFormatter";
import { BaseGuildTextChannel, User } from "discord.js";
import { BaseGuildTextChannel, ThreadChannel, User } from "discord.js";
import { channelToTemplateSafeChannel, userToTemplateSafeUser } from "../../../utils/templateSafeObjects";
interface LogPostedScheduledMessageData {
author: User;
channel: BaseGuildTextChannel;
channel: BaseGuildTextChannel | ThreadChannel;
messageId: string;
}

View file

@ -34,7 +34,6 @@ import { UnmuteCmd } from "./commands/UnmuteCmd";
import { UpdateCmd } from "./commands/UpdateCmd";
import { WarnCmd } from "./commands/WarnCmd";
import { CreateBanCaseOnManualBanEvt } from "./events/CreateBanCaseOnManualBanEvt";
import { CreateKickCaseOnManualKickEvt } from "./events/CreateKickCaseOnManualKickEvt";
import { CreateUnbanCaseOnManualUnbanEvt } from "./events/CreateUnbanCaseOnManualUnbanEvt";
import { PostAlertOnMemberJoinEvt } from "./events/PostAlertOnMemberJoinEvt";
import { banUserId } from "./functions/banUserId";
@ -42,11 +41,12 @@ import { hasMutePermission } from "./functions/hasMutePerm";
import { kickMember } from "./functions/kickMember";
import { offModActionsEvent } from "./functions/offModActionsEvent";
import { onModActionsEvent } from "./functions/onModActionsEvent";
import { outdatedTempbansLoop } from "./functions/outdatedTempbansLoop";
import { updateCase } from "./functions/updateCase";
import { warnMember } from "./functions/warnMember";
import { BanOptions, ConfigSchema, KickOptions, ModActionsPluginType, WarnOptions } from "./types";
import { LogsPlugin } from "../Logs/LogsPlugin";
import { onGuildEvent } from "../../data/GuildEvents";
import { clearTempban } from "./functions/clearTempban";
const defaultOptions = {
config: {
@ -200,7 +200,6 @@ export const ModActionsPlugin = zeppelinGuildPlugin<ModActionsPluginType>()({
state.serverLogs = new GuildLogs(guild.id);
state.unloaded = false;
state.outdatedTempbansTimeout = null;
state.ignoredEvents = [];
// Massbans can take a while depending on rate limits,
// so we're giving each massban 15 minutes to complete before launching the next massban
@ -210,11 +209,14 @@ export const ModActionsPlugin = zeppelinGuildPlugin<ModActionsPluginType>()({
},
afterLoad(pluginData) {
outdatedTempbansLoop(pluginData);
pluginData.state.unregisterGuildEventListener = onGuildEvent(pluginData.guild.id, "expiredTempban", (tempban) =>
clearTempban(pluginData, tempban),
);
},
beforeUnload(pluginData) {
pluginData.state.unloaded = true;
pluginData.state.unregisterGuildEventListener();
pluginData.state.events.removeAllListeners();
},
});

View file

@ -10,6 +10,7 @@ import { formatReasonWithAttachments } from "../functions/formatReasonWithAttach
import { ignoreEvent } from "../functions/ignoreEvent";
import { IgnoredEventType, modActionsCmd } from "../types";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { clearExpiringTempban } from "../../../data/loops/expiringTempbansLoop";
const opts = {
mod: ct.member({ option: true }),
@ -68,7 +69,11 @@ export const UnbanCmd = modActionsCmd({
ppId: mod.id !== msg.author.id ? msg.author.id : undefined,
});
// Delete the tempban, if one exists
pluginData.state.tempbans.clear(user.id);
const tempban = await pluginData.state.tempbans.findExistingTempbanForUserId(user.id);
if (tempban) {
clearExpiringTempban(tempban);
await pluginData.state.tempbans.clear(user.id);
}
// Confirm the action
sendSuccessMessage(pluginData, msg.channel, `Member unbanned (Case #${createdCase.case_number})`);

View file

@ -19,6 +19,7 @@ import { BanOptions, BanResult, IgnoredEventType, ModActionsPluginType } from ".
import { getDefaultContactMethods } from "./getDefaultContactMethods";
import { ignoreEvent } from "./ignoreEvent";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { registerExpiringTempban } from "../../../data/loops/expiringTempbansLoop";
/**
* Ban the specified user id, whether or not they're actually on the server at the time. Generates a case.
@ -112,6 +113,8 @@ export async function banUserId(
} else {
pluginData.state.tempbans.addTempban(user.id, banTime, banOptions.modId ?? selfId);
}
const tempban = (await pluginData.state.tempbans.findExistingTempbanForUserId(user.id))!;
registerExpiringTempban(tempban);
}
// Create a case for this action

View file

@ -0,0 +1,60 @@
import { Snowflake } from "discord.js";
import humanizeDuration from "humanize-duration";
import { GuildPluginData } from "knub";
import moment from "moment-timezone";
import { LogType } from "src/data/LogType";
import { logger } from "src/logger";
import { CaseTypes } from "../../../data/CaseTypes";
import { resolveUser, SECONDS } from "../../../utils";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { IgnoredEventType, ModActionsPluginType } from "../types";
import { formatReasonWithAttachments } from "./formatReasonWithAttachments";
import { ignoreEvent } from "./ignoreEvent";
import { isBanned } from "./isBanned";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { Tempban } from "../../../data/entities/Tempban";
export async function clearTempban(pluginData: GuildPluginData<ModActionsPluginType>, tempban: Tempban) {
if (!(await isBanned(pluginData, tempban.user_id))) {
pluginData.state.tempbans.clear(tempban.user_id);
return;
}
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, tempban.user_id);
const reason = formatReasonWithAttachments(
`Tempban timed out.
Tempbanned at: \`${tempban.created_at} UTC\``,
[],
);
try {
ignoreEvent(pluginData, IgnoredEventType.Unban, tempban.user_id);
await pluginData.guild.bans.remove(tempban.user_id as Snowflake, reason ?? undefined);
} catch (e) {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Encountered an error trying to automatically unban ${tempban.user_id} after tempban timeout`,
});
logger.warn(`Error automatically unbanning ${tempban.user_id} (tempban timeout): ${e}`);
return;
}
// Create case and delete tempban
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const createdCase = await casesPlugin.createCase({
userId: tempban.user_id,
modId: tempban.mod_id,
type: CaseTypes.Unban,
reason,
ppId: undefined,
});
pluginData.state.tempbans.clear(tempban.user_id);
// Log the unban
const banTime = moment(tempban.created_at).diff(moment(tempban.expires_at));
pluginData.getPlugin(LogsPlugin).logMemberTimedUnban({
mod: await resolveUser(pluginData.client, tempban.mod_id),
userId: tempban.user_id,
caseNumber: createdCase.case_number,
reason,
banTime: humanizeDuration(banTime),
});
}

View file

@ -1,70 +0,0 @@
import { Snowflake } from "discord.js";
import humanizeDuration from "humanize-duration";
import { GuildPluginData } from "knub";
import moment from "moment-timezone";
import { LogType } from "src/data/LogType";
import { logger } from "src/logger";
import { userToTemplateSafeUser } from "../../../utils/templateSafeObjects";
import { CaseTypes } from "../../../data/CaseTypes";
import { resolveUser, SECONDS } from "../../../utils";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { IgnoredEventType, ModActionsPluginType } from "../types";
import { formatReasonWithAttachments } from "./formatReasonWithAttachments";
import { ignoreEvent } from "./ignoreEvent";
import { isBanned } from "./isBanned";
import { LogsPlugin } from "../../Logs/LogsPlugin";
const TEMPBAN_LOOP_TIME = 60 * SECONDS;
export async function outdatedTempbansLoop(pluginData: GuildPluginData<ModActionsPluginType>) {
const outdatedTempbans = await pluginData.state.tempbans.getExpiredTempbans();
for (const tempban of outdatedTempbans) {
if (!(await isBanned(pluginData, tempban.user_id))) {
pluginData.state.tempbans.clear(tempban.user_id);
continue;
}
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, tempban.user_id);
const reason = formatReasonWithAttachments(
`Tempban timed out.
Tempbanned at: \`${tempban.created_at} UTC\``,
[],
);
try {
ignoreEvent(pluginData, IgnoredEventType.Unban, tempban.user_id);
await pluginData.guild.bans.remove(tempban.user_id as Snowflake, reason ?? undefined);
} catch (e) {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Encountered an error trying to automatically unban ${tempban.user_id} after tempban timeout`,
});
logger.warn(`Error automatically unbanning ${tempban.user_id} (tempban timeout): ${e}`);
return;
}
// Create case and delete tempban
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const createdCase = await casesPlugin.createCase({
userId: tempban.user_id,
modId: tempban.mod_id,
type: CaseTypes.Unban,
reason,
ppId: undefined,
});
pluginData.state.tempbans.clear(tempban.user_id);
// Log the unban
const banTime = moment(tempban.created_at).diff(moment(tempban.expires_at));
pluginData.getPlugin(LogsPlugin).logMemberTimedUnban({
mod: await resolveUser(pluginData.client, tempban.mod_id),
userId: tempban.user_id,
caseNumber: createdCase.case_number,
reason,
banTime: humanizeDuration(banTime),
});
}
if (!pluginData.state.unloaded) {
pluginData.state.outdatedTempbansTimeout = setTimeout(() => outdatedTempbansLoop(pluginData), TEMPBAN_LOOP_TIME);
}
}

View file

@ -72,7 +72,7 @@ export interface ModActionsPluginType extends BasePluginType {
serverLogs: GuildLogs;
unloaded: boolean;
outdatedTempbansTimeout: Timeout | null;
unregisterGuildEventListener: () => void;
ignoredEvents: IIgnoredEvent[];
massbanQueue: Queue;

View file

@ -15,12 +15,13 @@ import { MutesCmd } from "./commands/MutesCmd";
import { ClearActiveMuteOnMemberBanEvt } from "./events/ClearActiveMuteOnMemberBanEvt";
import { ClearActiveMuteOnRoleRemovalEvt } from "./events/ClearActiveMuteOnRoleRemovalEvt";
import { ReapplyActiveMuteOnJoinEvt } from "./events/ReapplyActiveMuteOnJoinEvt";
import { clearExpiredMutes } from "./functions/clearExpiredMutes";
import { muteUser } from "./functions/muteUser";
import { offMutesEvent } from "./functions/offMutesEvent";
import { onMutesEvent } from "./functions/onMutesEvent";
import { unmuteUser } from "./functions/unmuteUser";
import { ConfigSchema, MutesPluginType } from "./types";
import { onGuildEvent } from "../../data/GuildEvents";
import { clearMute } from "./functions/clearMute";
const defaultOptions = {
config: {
@ -113,15 +114,13 @@ export const MutesPlugin = zeppelinGuildPlugin<MutesPluginType>()({
},
afterLoad(pluginData) {
clearExpiredMutes(pluginData);
pluginData.state.muteClearIntervalId = setInterval(
() => clearExpiredMutes(pluginData),
EXPIRED_MUTE_CHECK_INTERVAL,
pluginData.state.unregisterGuildEventListener = onGuildEvent(pluginData.guild.id, "expiredMute", (mute) =>
clearMute(pluginData, mute),
);
},
beforeUnload(pluginData) {
clearInterval(pluginData.state.muteClearIntervalId);
pluginData.state.unregisterGuildEventListener();
pluginData.state.events.removeAllListeners();
},
});

View file

@ -1,50 +0,0 @@
import { Snowflake } from "discord.js";
import { GuildPluginData } from "knub";
import { memberToTemplateSafeMember } from "../../../utils/templateSafeObjects";
import { LogType } from "../../../data/LogType";
import { resolveMember, UnknownUser, verboseUserMention } from "../../../utils";
import { memberRolesLock } from "../../../utils/lockNameHelpers";
import { MutesPluginType } from "../types";
import { LogsPlugin } from "../../Logs/LogsPlugin";
export async function clearExpiredMutes(pluginData: GuildPluginData<MutesPluginType>) {
const expiredMutes = await pluginData.state.mutes.getExpiredMutes();
for (const mute of expiredMutes) {
const member = await resolveMember(pluginData.client, pluginData.guild, mute.user_id, true);
if (member) {
try {
const lock = await pluginData.locks.acquire(memberRolesLock(member));
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);
}
lock.unlock();
} catch {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Failed to remove mute role from ${verboseUserMention(member.user)}`,
});
}
}
await pluginData.state.mutes.clear(mute.user_id);
pluginData.getPlugin(LogsPlugin).logMemberMuteExpired({
member: member || new UnknownUser({ id: mute.user_id }),
});
pluginData.state.events.emit("unmute", mute.user_id);
}
}

View file

@ -0,0 +1,55 @@
import { Mute } from "../../../data/entities/Mute";
import { resolveMember, verboseUserMention } from "../../../utils";
import { memberRolesLock } from "../../../utils/lockNameHelpers";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { GuildPluginData } from "knub";
import { MutesPluginType } from "../types";
import { clearExpiringMute } from "../../../data/loops/expiringMutesLoop";
import { GuildMember } from "discord.js";
export async function clearMute(
pluginData: GuildPluginData<MutesPluginType>,
mute: Mute | null = null,
member: GuildMember | null = null,
) {
if (mute) {
clearExpiringMute(mute);
}
if (!member && mute) {
member = await resolveMember(pluginData.client, pluginData.guild, mute.user_id, true);
}
if (member) {
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);
}
lock.unlock();
} catch {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Failed to remove mute role from ${verboseUserMention(member.user)}`,
});
} finally {
lock.unlock();
}
}
if (mute) {
await pluginData.state.mutes.clear(mute.user_id);
}
}

View file

@ -4,7 +4,6 @@ import { GuildPluginData } from "knub";
import { userToTemplateSafeUser } from "../../../utils/templateSafeObjects";
import { CaseTypes } from "../../../data/CaseTypes";
import { Case } from "../../../data/entities/Case";
import { LogType } from "../../../data/LogType";
import { LogsPlugin } from "../../../plugins/Logs/LogsPlugin";
import { ERRORS, RecoverablePluginError } from "../../../RecoverablePluginError";
import { renderTemplate, TemplateSafeValueContainer } from "../../../templateFormatter";
@ -19,7 +18,12 @@ import {
import { muteLock } from "../../../utils/lockNameHelpers";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { MuteOptions, MutesPluginType } from "../types";
import { Mute } from "../../../data/entities/Mute";
import { registerExpiringMute } from "../../../data/loops/expiringMutesLoop";
/**
* TODO: Clean up this function
*/
export async function muteUser(
pluginData: GuildPluginData<MutesPluginType>,
userId: string,
@ -132,6 +136,7 @@ export async function muteUser(
// If the user is already muted, update the duration of their existing mute
const existingMute = await pluginData.state.mutes.findExistingMuteForUserId(user.id);
let finalMute: Mute;
let notifyResult: UserNotificationResult = { method: null, success: true };
if (existingMute) {
@ -139,10 +144,13 @@ export async function muteUser(
rolesToRestore = Array.from(new Set([...existingMute.roles_to_restore, ...rolesToRestore]));
}
await pluginData.state.mutes.updateExpiryTime(user.id, muteTime, rolesToRestore);
finalMute = (await pluginData.state.mutes.findExistingMuteForUserId(user.id))!;
} else {
await pluginData.state.mutes.addMute(user.id, muteTime, rolesToRestore);
finalMute = await pluginData.state.mutes.addMute(user.id, muteTime, rolesToRestore);
}
registerExpiringMute(finalMute);
const template = existingMute
? config.update_mute_message
: muteTime

View file

@ -11,6 +11,7 @@ import { CaseArgs } from "../../Cases/types";
import { MutesPluginType, UnmuteResult } from "../types";
import { memberHasMutedRole } from "./memberHasMutedRole";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { clearMute } from "./clearMute";
export async function unmuteUser(
pluginData: GuildPluginData<MutesPluginType>,
@ -34,34 +35,7 @@ export async function unmuteUser(
}
} else {
// Unmute immediately
if (member) {
const lock = await pluginData.locks.acquire(memberRolesLock(member));
const muteRole = pluginData.config.get().mute_role;
if (muteRole && member.roles.cache.has(muteRole as Snowflake)) {
await member.roles.remove(muteRole as Snowflake);
}
if (existingMute?.roles_to_restore) {
const guildRoles = pluginData.guild.roles.cache;
const newRoles = [...member.roles.cache.keys()].filter((roleId) => roleId !== muteRole);
for (const toRestore of existingMute.roles_to_restore) {
if (guildRoles.has(toRestore) && toRestore !== muteRole && !newRoles.includes(toRestore)) {
newRoles.push(toRestore);
}
}
await member.roles.set(newRoles);
}
lock.unlock();
} else {
// tslint:disable-next-line:no-console
console.warn(
`Member ${userId} not found in guild ${pluginData.guild.name} (${pluginData.guild.id}) when attempting to unmute`,
);
}
if (existingMute) {
await pluginData.state.mutes.clear(userId);
}
clearMute(pluginData, existingMute);
}
const timeUntilUnmute = unmuteTime && humanizeDuration(unmuteTime);

View file

@ -52,7 +52,7 @@ export interface MutesPluginType extends BasePluginType {
serverLogs: GuildLogs;
archives: GuildArchives;
muteClearIntervalId: Timeout;
unregisterGuildEventListener: () => void;
events: MutesEventEmitter;
};

View file

@ -8,12 +8,13 @@ import { EditCmd } from "./commands/EditCmd";
import { EditEmbedCmd } from "./commands/EditEmbedCmd";
import { PostCmd } from "./commands/PostCmd";
import { PostEmbedCmd } from "./commands/PostEmbedCmd";
import { ScheduledPostsDeleteCmd } from "./commands/SchedluedPostsDeleteCmd";
import { ScheduledPostsDeleteCmd } from "./commands/ScheduledPostsDeleteCmd";
import { ScheduledPostsListCmd } from "./commands/ScheduledPostsListCmd";
import { ScheduledPostsShowCmd } from "./commands/ScheduledPostsShowCmd";
import { ConfigSchema, PostPluginType } from "./types";
import { scheduledPostLoop } from "./util/scheduledPostLoop";
import { LogsPlugin } from "../Logs/LogsPlugin";
import { onGuildEvent } from "../../data/GuildEvents";
import { postScheduledPost } from "./util/postScheduledPost";
const defaultOptions: PluginOptions<PostPluginType> = {
config: {
@ -60,10 +61,12 @@ export const PostPlugin = zeppelinGuildPlugin<PostPluginType>()({
},
afterLoad(pluginData) {
scheduledPostLoop(pluginData);
pluginData.state.unregisterGuildEventListener = onGuildEvent(pluginData.guild.id, "scheduledPost", (post) =>
postScheduledPost(pluginData, post),
);
},
beforeUnload(pluginData) {
clearTimeout(pluginData.state.scheduledPostLoopTimeout);
pluginData.state.unregisterGuildEventListener();
},
});

View file

@ -2,6 +2,7 @@ import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { sorter } from "../../../utils";
import { postCmd } from "../types";
import { clearUpcomingScheduledPost } from "../../../data/loops/upcomingScheduledPostsLoop";
export const ScheduledPostsDeleteCmd = postCmd({
trigger: ["scheduled_posts delete", "scheduled_posts d"],
@ -20,6 +21,7 @@ export const ScheduledPostsDeleteCmd = postCmd({
return;
}
clearUpcomingScheduledPost(post);
await pluginData.state.scheduledPosts.delete(post.id);
sendSuccessMessage(pluginData, msg.channel, "Scheduled post deleted!");
},

View file

@ -16,7 +16,7 @@ export interface PostPluginType extends BasePluginType {
scheduledPosts: GuildScheduledPosts;
logs: GuildLogs;
scheduledPostLoopTimeout: NodeJS.Timeout;
unregisterGuildEventListener: () => void;
};
}

View file

@ -11,6 +11,7 @@ import { PostPluginType } from "../types";
import { parseScheduleTime } from "./parseScheduleTime";
import { postMessage } from "./postMessage";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { registerUpcomingScheduledPost } from "../../../data/loops/upcomingScheduledPostsLoop";
const MIN_REPEAT_TIME = 5 * MINUTES;
const MAX_REPEAT_TIME = Math.pow(2, 32);
@ -141,7 +142,7 @@ export async function actualPostCmd(
return;
}
await pluginData.state.scheduledPosts.create({
const post = await pluginData.state.scheduledPosts.create({
author_id: msg.author.id,
author_name: msg.author.tag,
channel_id: targetChannel.id,
@ -153,6 +154,7 @@ export async function actualPostCmd(
repeat_until: repeatUntil ? repeatUntil.clone().tz("Etc/UTC").format(DBDateFormat) : null,
repeat_times: repeatTimes ?? null,
});
registerUpcomingScheduledPost(post);
if (opts.repeat) {
pluginData.getPlugin(LogsPlugin).logScheduledRepeatedMessage({

View file

@ -0,0 +1,78 @@
import { Snowflake, TextChannel, User } from "discord.js";
import { GuildPluginData } from "knub";
import moment from "moment-timezone";
import { logger } from "../../../logger";
import { DBDateFormat, verboseChannelMention, verboseUserMention } from "../../../utils";
import { PostPluginType } from "../types";
import { postMessage } from "./postMessage";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { ScheduledPost } from "../../../data/entities/ScheduledPost";
import { registerUpcomingScheduledPost } from "../../../data/loops/upcomingScheduledPostsLoop";
export async function postScheduledPost(pluginData: GuildPluginData<PostPluginType>, post: ScheduledPost) {
// First, update the scheduled post or delete it from the database *before* we try posting it.
// This ensures strange errors don't cause reposts.
let shouldClear = true;
if (post.repeat_interval) {
const nextPostAt = moment.utc().add(post.repeat_interval, "ms");
if (post.repeat_until) {
const repeatUntil = moment.utc(post.repeat_until, DBDateFormat);
if (nextPostAt.isSameOrBefore(repeatUntil)) {
await pluginData.state.scheduledPosts.update(post.id, {
post_at: nextPostAt.format(DBDateFormat),
});
shouldClear = false;
}
} else if (post.repeat_times) {
if (post.repeat_times > 1) {
await pluginData.state.scheduledPosts.update(post.id, {
post_at: nextPostAt.format(DBDateFormat),
repeat_times: post.repeat_times - 1,
});
shouldClear = false;
}
}
}
if (shouldClear) {
await pluginData.state.scheduledPosts.delete(post.id);
} else {
const upToDatePost = (await pluginData.state.scheduledPosts.find(post.id))!;
registerUpcomingScheduledPost(upToDatePost);
}
// Post the message
const channel = pluginData.guild.channels.cache.get(post.channel_id as Snowflake);
if (channel?.isText() || channel?.isThread()) {
const [username, discriminator] = post.author_name.split("#");
const author: User = (await pluginData.client.users.fetch(post.author_id as Snowflake)) || {
id: post.author_id,
username,
discriminator,
};
try {
const postedMessage = await postMessage(
pluginData,
channel,
post.content,
post.attachments,
post.enable_mentions,
);
pluginData.getPlugin(LogsPlugin).logPostedScheduledMessage({
author,
channel,
messageId: postedMessage.id,
});
} catch {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Failed to post scheduled message by ${verboseUserMention(author)} to ${verboseChannelMention(channel)}`,
});
logger.warn(
`Failed to post scheduled message to #${channel.name} (${channel.id}) on ${pluginData.guild.name} (${pluginData.guild.id})`,
);
}
}
}

View file

@ -1,84 +0,0 @@
import { Snowflake, TextChannel, User } from "discord.js";
import { GuildPluginData } from "knub";
import moment from "moment-timezone";
import { channelToTemplateSafeChannel, userToTemplateSafeUser } from "../../../utils/templateSafeObjects";
import { LogType } from "../../../data/LogType";
import { logger } from "../../../logger";
import { DBDateFormat, SECONDS, verboseChannelMention, verboseUserMention } from "../../../utils";
import { PostPluginType } from "../types";
import { postMessage } from "./postMessage";
import { LogsPlugin } from "../../Logs/LogsPlugin";
const SCHEDULED_POST_CHECK_INTERVAL = 5 * SECONDS;
export async function scheduledPostLoop(pluginData: GuildPluginData<PostPluginType>) {
const duePosts = await pluginData.state.scheduledPosts.getDueScheduledPosts();
for (const post of duePosts) {
const channel = pluginData.guild.channels.cache.get(post.channel_id as Snowflake);
if (channel instanceof TextChannel) {
const [username, discriminator] = post.author_name.split("#");
const author: User = (await pluginData.client.users.fetch(post.author_id as Snowflake)) || {
id: post.author_id,
username,
discriminator,
};
try {
const postedMessage = await postMessage(
pluginData,
channel,
post.content,
post.attachments,
post.enable_mentions,
);
pluginData.getPlugin(LogsPlugin).logPostedScheduledMessage({
author,
channel,
messageId: postedMessage.id,
});
} catch {
pluginData.getPlugin(LogsPlugin).logBotAlert({
body: `Failed to post scheduled message by ${verboseUserMention(author)} to ${verboseChannelMention(
channel,
)}`,
});
logger.warn(
`Failed to post scheduled message to #${channel.name} (${channel.id}) on ${pluginData.guild.name} (${pluginData.guild.id})`,
);
}
}
let shouldClear = true;
if (post.repeat_interval) {
const nextPostAt = moment.utc().add(post.repeat_interval, "ms");
if (post.repeat_until) {
const repeatUntil = moment.utc(post.repeat_until, DBDateFormat);
if (nextPostAt.isSameOrBefore(repeatUntil)) {
await pluginData.state.scheduledPosts.update(post.id, {
post_at: nextPostAt.format(DBDateFormat),
});
shouldClear = false;
}
} else if (post.repeat_times) {
if (post.repeat_times > 1) {
await pluginData.state.scheduledPosts.update(post.id, {
post_at: nextPostAt.format(DBDateFormat),
repeat_times: post.repeat_times - 1,
});
shouldClear = false;
}
}
}
if (shouldClear) {
await pluginData.state.scheduledPosts.delete(post.id);
}
}
pluginData.state.scheduledPostLoopTimeout = setTimeout(
() => scheduledPostLoop(pluginData),
SCHEDULED_POST_CHECK_INTERVAL,
);
}

View file

@ -6,7 +6,8 @@ import { RemindCmd } from "./commands/RemindCmd";
import { RemindersCmd } from "./commands/RemindersCmd";
import { RemindersDeleteCmd } from "./commands/RemindersDeleteCmd";
import { ConfigSchema, RemindersPluginType } from "./types";
import { postDueRemindersLoop } from "./utils/postDueRemindersLoop";
import { onGuildEvent } from "../../data/GuildEvents";
import { postReminder } from "./functions/postReminder";
const defaultOptions: PluginOptions<RemindersPluginType> = {
config: {
@ -46,16 +47,16 @@ export const RemindersPlugin = zeppelinGuildPlugin<RemindersPluginType>()({
state.reminders = GuildReminders.getGuildInstance(guild.id);
state.tries = new Map();
state.unloaded = false;
state.postRemindersTimeout = null;
},
afterLoad(pluginData) {
postDueRemindersLoop(pluginData);
pluginData.state.unregisterGuildEventListener = onGuildEvent(pluginData.guild.id, "reminder", (reminder) =>
postReminder(pluginData, reminder),
);
},
beforeUnload(pluginData) {
clearTimeout(pluginData.state.postRemindersTimeout);
pluginData.state.unregisterGuildEventListener();
pluginData.state.unloaded = true;
},
});

View file

@ -5,6 +5,7 @@ import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { convertDelayStringToMS, messageLink } from "../../../utils";
import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin";
import { remindersCmd } from "../types";
import { registerUpcomingReminder } from "../../../data/loops/upcomingRemindersLoop";
export const RemindCmd = remindersCmd({
trigger: ["remind", "remindme", "reminder"],
@ -50,7 +51,7 @@ export const RemindCmd = remindersCmd({
}
const reminderBody = args.reminder || messageLink(pluginData.guild.id, msg.channel.id, msg.id);
await pluginData.state.reminders.add(
const reminder = await pluginData.state.reminders.add(
msg.author.id,
msg.channel.id,
reminderTime.clone().tz("Etc/UTC").format("YYYY-MM-DD HH:mm:ss"),
@ -58,6 +59,8 @@ export const RemindCmd = remindersCmd({
moment.utc().format("YYYY-MM-DD HH:mm:ss"),
);
registerUpcomingReminder(reminder);
const msUntilReminder = reminderTime.diff(now);
const timeUntilReminder = humanizeDuration(msUntilReminder, { largest: 2, round: true });
const prettyReminderTime = (await timeAndDate.inMemberTz(msg.author.id, reminderTime)).format(

View file

@ -2,6 +2,7 @@ import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { sorter } from "../../../utils";
import { remindersCmd } from "../types";
import { clearUpcomingReminder } from "../../../data/loops/upcomingRemindersLoop";
export const RemindersDeleteCmd = remindersCmd({
trigger: ["reminders delete", "reminders d"],
@ -21,6 +22,7 @@ export const RemindersDeleteCmd = remindersCmd({
}
const toDelete = reminders[args.num - 1];
clearUpcomingReminder(toDelete);
await pluginData.state.reminders.delete(toDelete.id);
sendSuccessMessage(pluginData, msg.channel, "Reminder deleted");

View file

@ -0,0 +1,41 @@
import { GuildPluginData } from "knub";
import { RemindersPluginType } from "../types";
import { Reminder } from "../../../data/entities/Reminder";
import { Snowflake, TextChannel } from "discord.js";
import moment from "moment-timezone";
import { disableLinkPreviews } from "knub/dist/helpers";
import { DBDateFormat, SECONDS } from "../../../utils";
import humanizeDuration from "humanize-duration";
export async function postReminder(pluginData: GuildPluginData<RemindersPluginType>, reminder: Reminder) {
const channel = pluginData.guild.channels.cache.get(reminder.channel_id as Snowflake);
if (channel && (channel.isText() || channel.isThread())) {
try {
// Only show created at date if one exists
if (moment.utc(reminder.created_at).isValid()) {
const createdAtTS = Math.floor(moment.utc(reminder.created_at, DBDateFormat).valueOf() / 1000);
await channel.send({
content: disableLinkPreviews(
`Reminder for <@!${reminder.user_id}>: ${reminder.body} \nSet <t:${createdAtTS}:R>`,
),
allowedMentions: {
users: [reminder.user_id as Snowflake],
},
});
} else {
await channel.send({
content: disableLinkPreviews(`Reminder for <@!${reminder.user_id}>: ${reminder.body}`),
allowedMentions: {
users: [reminder.user_id as Snowflake],
},
});
}
} catch (err) {
// If we were unable to post the reminder, we'll try again later
console.warn(`Error when posting reminder for ${reminder.user_id} in guild ${reminder.guild_id}: ${String(err)}`);
return;
}
}
await pluginData.state.reminders.delete(reminder.id);
}

View file

@ -14,7 +14,8 @@ export interface RemindersPluginType extends BasePluginType {
reminders: GuildReminders;
tries: Map<number, number>;
postRemindersTimeout;
unregisterGuildEventListener: () => void;
unloaded: boolean;
};
}

View file

@ -1,56 +0,0 @@
import { Snowflake, TextChannel } from "discord.js";
import humanizeDuration from "humanize-duration";
import { GuildPluginData } from "knub";
import { disableLinkPreviews } from "knub/dist/helpers";
import moment from "moment-timezone";
import { SECONDS } from "../../../utils";
import { RemindersPluginType } from "../types";
const REMINDER_LOOP_TIME = 10 * SECONDS;
const MAX_TRIES = 3;
export async function postDueRemindersLoop(pluginData: GuildPluginData<RemindersPluginType>) {
const pendingReminders = await pluginData.state.reminders.getDueReminders();
for (const reminder of pendingReminders) {
const channel = pluginData.guild.channels.cache.get(reminder.channel_id as Snowflake);
if (channel && channel instanceof TextChannel) {
try {
// Only show created at date if one exists
if (moment.utc(reminder.created_at).isValid()) {
const target = moment.utc();
const diff = target.diff(moment.utc(reminder.created_at, "YYYY-MM-DD HH:mm:ss"));
const result = humanizeDuration(diff, { largest: 2, round: true });
await channel.send({
content: disableLinkPreviews(
`Reminder for <@!${reminder.user_id}>: ${reminder.body} \n\`Set at ${reminder.created_at} (${result} ago)\``,
),
allowedMentions: {
users: [reminder.user_id as Snowflake],
},
});
} else {
await channel.send({
content: disableLinkPreviews(`Reminder for <@!${reminder.user_id}>: ${reminder.body}`),
allowedMentions: {
users: [reminder.user_id as Snowflake],
},
});
}
} catch {
// Probably random Discord internal server error or missing permissions or somesuch
// Try again next round unless we've already tried to post this a bunch of times
const tries = pluginData.state.tries.get(reminder.id) || 0;
if (tries < MAX_TRIES) {
pluginData.state.tries.set(reminder.id, tries + 1);
continue;
}
}
}
await pluginData.state.reminders.delete(reminder.id);
}
if (!pluginData.state.unloaded) {
pluginData.state.postRemindersTimeout = setTimeout(() => postDueRemindersLoop(pluginData), REMINDER_LOOP_TIME);
}
}