3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-03-15 05:41:51 +00:00

Fixes, refactoring and PR feedback

This commit is contained in:
Lily Bergonzat 2024-04-15 15:51:45 +02:00
parent 0be54912c4
commit 893a77d562
202 changed files with 1037 additions and 1069 deletions

View file

@ -28,10 +28,10 @@ app.use(multer().none());
const rootRouter = express.Router();
initAuth(app);
initGuildsAPI(app);
initArchives(app);
initDocs(app);
initAuth(rootRouter);
initGuildsAPI(rootRouter);
initArchives(rootRouter);
initDocs(rootRouter);
// Default route
rootRouter.get("/", (req, res) => {

View file

@ -6,6 +6,7 @@ import { DisableAutoReactionsCmd } from "./commands/DisableAutoReactionsCmd";
import { NewAutoReactionsCmd } from "./commands/NewAutoReactionsCmd";
import { AddReactionsEvt } from "./events/AddReactionsEvt";
import { AutoReactionsPluginType, zAutoReactionsConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions: PluginOptions<AutoReactionsPluginType> = {
config: {
@ -50,4 +51,8 @@ export const AutoReactionsPlugin = guildPlugin<AutoReactionsPluginType>()({
state.autoReactions = GuildAutoReactions.getGuildInstance(guild.id);
state.cache = new Map();
},
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
}
});

View file

@ -14,12 +14,12 @@ export const DisableAutoReactionsCmd = autoReactionsCmd({
async run({ message: msg, args, pluginData }) {
const autoReaction = await pluginData.state.autoReactions.getForChannel(args.channelId);
if (!autoReaction) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `Auto-reactions aren't enabled in <#${args.channelId}>`);
void pluginData.state.common.sendErrorMessage(msg, `Auto-reactions aren't enabled in <#${args.channelId}>`);
return;
}
await pluginData.state.autoReactions.removeFromChannel(args.channelId);
pluginData.state.cache.delete(args.channelId);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Auto-reactions disabled in <#${args.channelId}>`);
void pluginData.state.common.sendSuccessMessage(msg, `Auto-reactions disabled in <#${args.channelId}>`);
},
});

View file

@ -25,20 +25,16 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
const me = pluginData.guild.members.cache.get(pluginData.client.user!.id)!;
const missingPermissions = getMissingChannelPermissions(me, args.channel, requiredPermissions);
if (missingPermissions) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(
msg,
`Cannot set auto-reactions for that channel. ${missingPermissionError(missingPermissions)}`,
);
pluginData.state.common.sendErrorMessage(
msg,
`Cannot set auto-reactions for that channel. ${missingPermissionError(missingPermissions)}`,
);
return;
}
for (const reaction of args.reactions) {
if (!isEmoji(reaction)) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, "One or more of the specified reactions were invalid!");
void pluginData.state.common.sendErrorMessage(msg, "One or more of the specified reactions were invalid!");
return;
}
@ -48,9 +44,7 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
if (customEmojiMatch) {
// Custom emoji
if (!canUseEmoji(pluginData.client, customEmojiMatch[2])) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, "I can only use regular emojis and custom emojis from this server");
pluginData.state.common.sendErrorMessage(msg, "I can only use regular emojis and custom emojis from this server");
return;
}
@ -65,6 +59,6 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
await pluginData.state.autoReactions.set(args.channel.id, finalReactions);
pluginData.state.cache.delete(args.channel.id);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Auto-reactions set for <#${args.channel.id}>`);
void pluginData.state.common.sendSuccessMessage(msg, `Auto-reactions set for <#${args.channel.id}>`);
},
});

View file

@ -1,9 +1,10 @@
import { BasePluginType, guildPluginEventListener, guildPluginMessageCommand } from "knub";
import { BasePluginType, guildPluginEventListener, guildPluginMessageCommand, pluginUtils } from "knub";
import z from "zod";
import { GuildAutoReactions } from "../../data/GuildAutoReactions";
import { GuildLogs } from "../../data/GuildLogs";
import { GuildSavedMessages } from "../../data/GuildSavedMessages";
import { AutoReaction } from "../../data/entities/AutoReaction";
import { CommonPlugin } from "../Common/CommonPlugin";
export const zAutoReactionsConfig = z.strictObject({
can_manage: z.boolean(),
@ -16,6 +17,7 @@ export interface AutoReactionsPluginType extends BasePluginType {
savedMessages: GuildSavedMessages;
autoReactions: GuildAutoReactions;
cache: Map<string, AutoReaction | null>;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
};
}

View file

@ -32,6 +32,7 @@ import { clearOldRecentNicknameChanges } from "./functions/clearOldNicknameChang
import { clearOldRecentActions } from "./functions/clearOldRecentActions";
import { clearOldRecentSpam } from "./functions/clearOldRecentSpam";
import { AutomodPluginType, zAutomodConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions = {
config: {
@ -117,6 +118,10 @@ export const AutomodPlugin = guildPlugin<AutomodPluginType>()({
state.cachedAntiraidLevel = await state.antiraidLevels.get();
},
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
async afterLoad(pluginData) {
const { state } = pluginData;

View file

@ -1,5 +1,4 @@
import { guildPluginMessageCommand } from "knub";
import { CommonPlugin } from "../../Common/CommonPlugin";
import { setAntiraidLevel } from "../functions/setAntiraidLevel";
import { AutomodPluginType } from "../types";
@ -9,6 +8,6 @@ export const AntiraidClearCmd = guildPluginMessageCommand<AutomodPluginType>()({
async run({ pluginData, message }) {
await setAntiraidLevel(pluginData, null, message.author);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(message, "Anti-raid turned **off**");
void pluginData.state.common.sendSuccessMessage(message, "Anti-raid turned **off**");
},
});

View file

@ -1,6 +1,5 @@
import { guildPluginMessageCommand } from "knub";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { CommonPlugin } from "../../Common/CommonPlugin";
import { setAntiraidLevel } from "../functions/setAntiraidLevel";
import { AutomodPluginType } from "../types";
@ -15,11 +14,11 @@ export const SetAntiraidCmd = guildPluginMessageCommand<AutomodPluginType>()({
async run({ pluginData, message, args }) {
const config = pluginData.config.get();
if (!config.antiraid_levels.includes(args.level)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Unknown anti-raid level");
pluginData.state.common.sendErrorMessage(message, "Unknown anti-raid level");
return;
}
await setAntiraidLevel(pluginData, args.level, message.author);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(message, `Anti-raid level set to **${args.level}**`);
pluginData.state.common.sendSuccessMessage(message, `Anti-raid level set to **${args.level}**`);
},
});

View file

@ -1,5 +1,5 @@
import { GuildMember, GuildTextBasedChannel, PartialGuildMember, ThreadChannel, User } from "discord.js";
import { BasePluginType, CooldownManager } from "knub";
import { BasePluginType, CooldownManager, pluginUtils } from "knub";
import z from "zod";
import { Queue } from "../../Queue";
import { RegExpRunner } from "../../RegExpRunner";
@ -17,6 +17,7 @@ import { RecentActionType } from "./constants";
import { availableTriggers } from "./triggers/availableTriggers";
import Timeout = NodeJS.Timeout;
import { CommonPlugin } from "../Common/CommonPlugin";
export type ZTriggersMapHelper = {
[TriggerName in keyof typeof availableTriggers]: (typeof availableTriggers)[TriggerName]["configSchema"];
@ -139,6 +140,8 @@ export interface AutomodPluginType extends BasePluginType {
modActionsListeners: Map<keyof ModActionsEvents, any>;
mutesListeners: Map<keyof MutesEvents, any>;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
};
}

View file

@ -4,7 +4,6 @@ import { AllowedGuilds } from "../../data/AllowedGuilds";
import { ApiPermissionAssignments } from "../../data/ApiPermissionAssignments";
import { Configs } from "../../data/Configs";
import { GuildArchives } from "../../data/GuildArchives";
import { CommonPlugin } from "../Common/CommonPlugin";
import { getActiveReload, resetActiveReload } from "./activeReload";
import { AddDashboardUserCmd } from "./commands/AddDashboardUserCmd";
import { AddServerFromInviteCmd } from "./commands/AddServerFromInviteCmd";
@ -77,7 +76,7 @@ export const BotControlPlugin = globalPlugin<BotControlPluginType>()({
if (guild) {
const channel = guild.channels.cache.get(channelId as Snowflake);
if (channel instanceof TextChannel) {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(channel, "Global plugins reloaded!");
void channel.send("Global plugins reloaded!");
}
}
}

View file

@ -20,7 +20,7 @@ export const AddDashboardUserCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin");
void msg.channel.send("Server is not using Zeppelin");
return;
}
@ -38,11 +38,6 @@ export const AddDashboardUserCmd = botControlCmd({
const userNameList = args.users.map((user) => `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`)`);
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg,
`The following users were given dashboard access for **${guild.name}**:\n\n${userNameList}`,
);
msg.channel.send(`The following users were given dashboard access for **${guild.name}**:\n\n${userNameList}`);
},
});

View file

@ -18,21 +18,19 @@ export const AddServerFromInviteCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const invite = await resolveInvite(pluginData.client, args.inviteCode, true);
if (!invite || !isGuildInvite(invite)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Could not resolve invite"); // :D
void msg.channel.send("Could not resolve invite"); // :D
return;
}
const existing = await pluginData.state.allowedGuilds.find(invite.guild.id);
if (existing) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is already allowed!");
void msg.channel.send("Server is already allowed!");
return;
}
const { result, explanation } = await isEligible(pluginData, args.user, invite);
if (!result) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `Could not add server because it's not eligible: ${explanation}`);
msg.channel.send(`Could not add server because it's not eligible: ${explanation}`);
return;
}
@ -53,8 +51,6 @@ export const AddServerFromInviteCmd = botControlCmd({
);
}
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(msg, "Server was eligible and is now allowed to use Zeppelin!");
msg.channel.send("Server was eligible and is now allowed to use Zeppelin!");
},
});

View file

@ -21,17 +21,17 @@ export const AllowServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const existing = await pluginData.state.allowedGuilds.find(args.guildId);
if (existing) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is already allowed!");
void msg.channel.send("Server is already allowed!");
return;
}
if (!isSnowflake(args.guildId)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Invalid server ID!");
void msg.channel.send("Invalid server ID!");
return;
}
if (args.userId && !isSnowflake(args.userId)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Invalid user ID!");
void msg.channel.send("Invalid user ID!");
return;
}
@ -52,6 +52,6 @@ export const AllowServerCmd = botControlCmd({
);
}
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, "Server is now allowed to use Zeppelin!");
void msg.channel.send("Server is now allowed to use Zeppelin!");
},
});

View file

@ -17,7 +17,7 @@ export const ChannelToServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const channel = pluginData.client.channels.cache.get(args.channelId);
if (!channel) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Channel not found in cache!");
void msg.channel.send("Channel not found in cache!");
return;
}

View file

@ -19,7 +19,7 @@ export const DisallowServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const existing = await pluginData.state.allowedGuilds.find(args.guildId);
if (!existing) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "That server is not allowed in the first place!");
void msg.channel.send("That server is not allowed in the first place!");
return;
}
@ -28,6 +28,6 @@ export const DisallowServerCmd = botControlCmd({
.get(args.guildId as Snowflake)
?.leave()
.catch(noop);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, "Server removed!");
void msg.channel.send("Server removed!");
},
});

View file

@ -16,17 +16,17 @@ export const EligibleCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const invite = await resolveInvite(pluginData.client, args.inviteCode, true);
if (!invite || !isGuildInvite(invite)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Could not resolve invite");
void msg.channel.send("Could not resolve invite");
return;
}
const { result, explanation } = await isEligible(pluginData, args.user, invite);
if (result) {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Server is eligible: ${explanation}`);
void msg.channel.send(`Server is eligible: ${explanation}`);
return;
}
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `Server is **NOT** eligible: ${explanation}`);
void msg.channel.send(`Server is **NOT** eligible: ${explanation}`);
},
});

View file

@ -17,7 +17,7 @@ export const LeaveServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
if (!pluginData.client.guilds.cache.has(args.guildId as Snowflake)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "I am not in that guild");
void msg.channel.send("I am not in that guild");
return;
}
@ -27,10 +27,10 @@ export const LeaveServerCmd = botControlCmd({
try {
await pluginData.client.guilds.cache.get(args.guildId as Snowflake)?.leave();
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `Failed to leave guild: ${e.message}`);
void msg.channel.send(`Failed to leave guild: ${e.message}`);
return;
}
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Left guild **${guildName}**`);
void msg.channel.send(`Left guild **${guildName}**`);
},
});

View file

@ -16,7 +16,7 @@ export const ListDashboardPermsCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
if (!args.user && !args.guildId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Must specify at least guildId, user, or both.");
void msg.channel.send("Must specify at least guildId, user, or both.");
return;
}
@ -24,7 +24,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (args.guildId) {
guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin");
void msg.channel.send("Server is not using Zeppelin");
return;
}
}
@ -33,7 +33,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (args.user) {
existingUserAssignment = await pluginData.state.apiPermissionAssignments.getByUserId(args.user.id);
if (existingUserAssignment.length === 0) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "The user has no assigned permissions.");
void msg.channel.send("The user has no assigned permissions.");
return;
}
}
@ -54,9 +54,7 @@ export const ListDashboardPermsCmd = botControlCmd({
}
if (finalMessage === "") {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `The user ${userInfo} has no assigned permissions on the specified server.`);
msg.channel.send(`The user ${userInfo} has no assigned permissions on the specified server.`);
return;
}
// Else display all users that have permissions on the specified guild
@ -65,9 +63,7 @@ export const ListDashboardPermsCmd = botControlCmd({
const existingGuildAssignment = await pluginData.state.apiPermissionAssignments.getByGuildId(guild.id);
if (existingGuildAssignment.length === 0) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `The server ${guildInfo} has no assigned permissions.`);
msg.channel.send(`The server ${guildInfo} has no assigned permissions.`);
return;
}
@ -80,6 +76,9 @@ export const ListDashboardPermsCmd = botControlCmd({
}
}
await pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, finalMessage.trim(), {});
await msg.channel.send({
content: finalMessage.trim(),
allowedMentions: {},
});
},
});

View file

@ -14,7 +14,7 @@ export const ListDashboardUsersCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin");
void msg.channel.send("Server is not using Zeppelin");
return;
}
@ -30,12 +30,9 @@ export const ListDashboardUsersCmd = botControlCmd({
`<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`): ${permission.permissions.join(", ")}`,
);
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg,
`The following users have dashboard access for **${guild.name}**:\n\n${userNameList.join("\n")}`,
{},
);
msg.channel.send({
content: `The following users have dashboard access for **${guild.name}**:\n\n${userNameList.join("\n")}`,
allowedMentions: {},
});
},
});

View file

@ -14,7 +14,7 @@ export const RateLimitPerformanceCmd = botControlCmd({
async run({ pluginData, message: msg }) {
const logItems = getRateLimitStats();
if (logItems.length === 0) {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `No rate limits hit`);
void msg.channel.send(`No rate limits hit`);
return;
}

View file

@ -15,7 +15,7 @@ export const ReloadGlobalPluginsCmd = botControlCmd({
const guildId = "guild" in message.channel ? message.channel.guild.id : null;
if (!guildId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "This command can only be used in a server");
void message.channel.send("This command can only be used in a server");
return;
}

View file

@ -17,18 +17,18 @@ export const ReloadServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
if (!pluginData.client.guilds.cache.has(args.guildId as Snowflake)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "I am not in that guild");
void msg.channel.send("I am not in that guild");
return;
}
try {
await pluginData.getKnubInstance().reloadGuild(args.guildId);
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `Failed to reload guild: ${e.message}`);
void msg.channel.send(`Failed to reload guild: ${e.message}`);
return;
}
const guild = await pluginData.client.guilds.fetch(args.guildId as Snowflake);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Reloaded guild **${guild?.name || "???"}**`);
void msg.channel.send(`Reloaded guild **${guild?.name || "???"}**`);
},
});

View file

@ -19,7 +19,7 @@ export const RemoveDashboardUserCmd = botControlCmd({
async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin");
void msg.channel.send("Server is not using Zeppelin");
return;
}
@ -37,11 +37,8 @@ export const RemoveDashboardUserCmd = botControlCmd({
const userNameList = args.users.map((user) => `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`)`);
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg,
`The following users were removed from the dashboard for **${guild.name}**:\n\n${userNameList}`,
);
msg.channel.send(
`The following users were removed from the dashboard for **${guild.name}**:\n\n${userNameList}`,
);
},
});

View file

@ -1,4 +1,4 @@
import { BasePluginType, globalPluginEventListener, globalPluginMessageCommand } from "knub";
import { BasePluginType, globalPluginEventListener, globalPluginMessageCommand, pluginUtils } from "knub";
import z from "zod";
import { AllowedGuilds } from "../../data/AllowedGuilds";
import { ApiPermissionAssignments } from "../../data/ApiPermissionAssignments";

View file

@ -3,6 +3,7 @@ import z from "zod";
import { TimeAndDatePlugin } from "../TimeAndDate/TimeAndDatePlugin";
import { ArchiveChannelCmd } from "./commands/ArchiveChannelCmd";
import { ChannelArchiverPluginType } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
export const ChannelArchiverPlugin = guildPlugin<ChannelArchiverPluginType>()({
name: "channel_archiver",
@ -14,4 +15,8 @@ export const ChannelArchiverPlugin = guildPlugin<ChannelArchiverPluginType>()({
messageCommands: [
ArchiveChannelCmd,
],
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
}
});

View file

@ -38,7 +38,7 @@ export const ArchiveChannelCmd = channelArchiverCmd({
"No `-attachment-channel` specified. Continue? Attachments will not be available in the log if their message is deleted.",
});
if (!confirmed) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Canceled");
void pluginData.state.common.sendErrorMessage(msg, "Canceled");
return;
}
}

View file

@ -1,5 +1,10 @@
import { BasePluginType, guildPluginMessageCommand } from "knub";
import { BasePluginType, guildPluginMessageCommand, pluginUtils } from "knub";
import { CommonPlugin } from "../Common/CommonPlugin";
export interface ChannelArchiverPluginType extends BasePluginType {}
export interface ChannelArchiverPluginType extends BasePluginType {
state: {
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
}
}
export const channelArchiverCmd = guildPluginMessageCommand<ChannelArchiverPluginType>();

View file

@ -1,4 +1,5 @@
import {
Attachment,
ChatInputCommandInteraction,
Message,
MessageCreateOptions,
@ -7,11 +8,10 @@ import {
TextBasedChannel,
User,
} from "discord.js";
import { PluginOptions } from "knub";
import { PluginOptions, guildPlugin } from "knub";
import { logger } from "../../logger";
import { isContextInteraction, sendContextResponse } from "../../pluginUtils";
import { errorMessage, successMessage } from "../../utils";
import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint";
import { getErrorEmoji, getSuccessEmoji } from "./functions/getEmoji";
import { CommonPluginType, zCommonConfig } from "./types";
@ -19,30 +19,21 @@ const defaultOptions: PluginOptions<CommonPluginType> = {
config: {
success_emoji: "✅",
error_emoji: "❌",
attachment_storing_channel: null,
},
};
export const CommonPlugin = zeppelinGuildPlugin<CommonPluginType>()({
export const CommonPlugin = guildPlugin<CommonPluginType>()({
name: "common",
showInDocs: false,
info: {
prettyName: "Common",
},
dependencies: () => [],
configParser: (input) => zCommonConfig.parse(input),
defaultOptions,
public: {
getSuccessEmoji(pluginData) {
return () => getSuccessEmoji(pluginData);
},
public(pluginData) {
return {
getSuccessEmoji,
getErrorEmoji,
getErrorEmoji(pluginData) {
return () => getErrorEmoji(pluginData);
},
sendSuccessMessage(pluginData) {
return async (
sendSuccessMessage: async (
context: TextBasedChannel | Message | User | ChatInputCommandInteraction,
body: string,
allowedMentions?: MessageMentionOptions,
@ -89,11 +80,9 @@ export const CommonPlugin = zeppelinGuildPlugin<CommonPluginType>()({
return undefined;
}) as Promise<Message>;
};
},
},
sendErrorMessage(pluginData) {
return async (
sendErrorMessage: async (
context: TextBasedChannel | Message | User | ChatInputCommandInteraction,
body: string,
allowedMentions?: MessageMentionOptions,
@ -140,7 +129,25 @@ export const CommonPlugin = zeppelinGuildPlugin<CommonPluginType>()({
return undefined;
}) as Promise<Message>;
};
},
},
storeAttachmentsAsMessage: async (attachments: Attachment[], backupChannel?: TextBasedChannel | null) => {
const attachmentChannelId = pluginData.config.get().attachment_storing_channel;
const channel = attachmentChannelId
? (pluginData.guild.channels.cache.get(attachmentChannelId) as TextBasedChannel) ?? backupChannel
: backupChannel;
if (!channel) {
throw new Error(
'Cannot store attachments: no attachment storing channel configured, and no backup channel passed'
);
}
return channel!.send({
content: `Storing ${attachments.length} attachment${attachments.length === 1 ? "" : "s"}`,
files: attachments.map((a) => a.url),
});
},
}
},
});

View file

@ -0,0 +1,8 @@
import { ZeppelinPluginInfo } from "../../types";
import { zCommonConfig } from "./types";
export const contextMenuPluginInfo: ZeppelinPluginInfo = {
showInDocs: false,
prettyName: "Common",
configSchema: zCommonConfig,
};

View file

@ -4,6 +4,7 @@ import z from "zod";
export const zCommonConfig = z.strictObject({
success_emoji: z.string(),
error_emoji: z.string(),
attachment_storing_channel: z.nullable(z.string()),
});
export interface CommonPluginType extends BasePluginType {

View file

@ -9,8 +9,8 @@ import {
} from "discord.js";
import humanizeDuration from "humanize-duration";
import { GuildPluginData } from "knub";
import { canActOn } from "src/pluginUtils";
import { ModActionsPlugin } from "src/plugins/ModActions/ModActionsPlugin";
import { canActOn } from "../../../pluginUtils";
import { ModActionsPlugin } from "../../ModActions/ModActionsPlugin";
import { logger } from "../../../logger";
import { convertDelayStringToMS, renderUserUsername } from "../../../utils";
import { CaseArgs } from "../../Cases/types";
@ -36,17 +36,13 @@ async function banAction(
const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasBanPermission(executingMember, interaction.channelId))) {
await interactionToReply
.editReply({ content: "Cannot ban: insufficient permissions", embeds: [], components: [] })
.catch((err) => logger.error(`Ban interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: "Cannot ban: insufficient permissions", embeds: [], components: [] });
return;
}
const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply
.editReply({ content: "Cannot ban: insufficient permissions", embeds: [], components: [] })
.catch((err) => logger.error(`Ban interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: "Cannot ban: insufficient permissions", embeds: [], components: [] });
return;
}
@ -57,9 +53,7 @@ async function banAction(
const durationMs = duration ? convertDelayStringToMS(duration)! : undefined;
const result = await modactions.banUserId(target, reason, reason, { caseArgs }, durationMs);
if (result.status === "failed") {
await interactionToReply
.editReply({ content: "Error: Failed to ban user", embeds: [], components: [] })
.catch((err) => logger.error(`Ban interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: "Error: Failed to ban user", embeds: [], components: [] });
return;
}
@ -73,9 +67,7 @@ async function banAction(
await updateAction(pluginData, executingMember, result.case, evidence);
}
await interactionToReply
.editReply({ content: banMessage, embeds: [], components: [] })
.catch((err) => logger.error(`Ban interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: banMessage, embeds: [], components: [] });
}
export async function launchBanActionModal(
@ -112,9 +104,7 @@ export async function launchBanActionModal(
if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Ban interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) {
await submitted
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Ban interaction defer failed: ${err}`));
await submitted.deferReply({ ephemeral: true });
}
const duration = submitted.fields.getTextInputValue("duration");
@ -122,6 +112,5 @@ export async function launchBanActionModal(
const evidence = submitted.fields.getTextInputValue("evidence");
await banAction(pluginData, duration, reason, evidence, target, interaction, submitted);
})
.catch((err) => logger.error(`Ban modal interaction failed: ${err}`));
});
}

View file

@ -61,15 +61,11 @@ export async function launchCleanActionModal(
await interaction
.awaitModalSubmit({ time: MODAL_TIMEOUT, filter: (i) => i.customId == modalId })
.then(async (submitted) => {
await submitted
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Clean interaction defer failed: ${err}`));
await submitted.deferReply({ ephemeral: true });
const amount = submitted.fields.getTextInputValue("amount");
if (isNaN(Number(amount))) {
interaction
.editReply({ content: `Error: Amount '${amount}' is invalid`, embeds: [], components: [] })
.catch((err) => logger.error(`Clean interaction reply failed: ${err}`));
interaction.editReply({ content: `Error: Amount '${amount}' is invalid`, embeds: [], components: [] });
return;
}
@ -81,6 +77,5 @@ export async function launchCleanActionModal(
interaction.channelId,
submitted,
);
})
.catch((err) => logger.error(`Clean modal interaction failed: ${err}`));
});
}

View file

@ -39,25 +39,21 @@ async function muteAction(
const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasMutePermission(executingMember, interaction.channelId))) {
await interactionToReply
.editReply({
content: "Cannot mute: insufficient permissions",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Cannot mute: insufficient permissions",
embeds: [],
components: [],
});
return;
}
const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply
.editReply({
content: "Cannot mute: insufficient permissions",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Cannot mute: insufficient permissions",
embeds: [],
components: [],
});
return;
}
@ -78,17 +74,13 @@ async function muteAction(
await updateAction(pluginData, executingMember, result.case!, evidence);
}
await interactionToReply
.editReply({ content: muteMessage, embeds: [], components: [] })
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: muteMessage, embeds: [], components: [] });
} catch (e) {
await interactionToReply
.editReply({
content: "Plugin error, please check your BOT_ALERTs",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Plugin error, please check your BOT_ALERTs",
embeds: [],
components: [],
});
if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) {
pluginData.getPlugin(LogsPlugin).logBotAlert({
@ -134,9 +126,7 @@ export async function launchMuteActionModal(
if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Mute interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) {
await submitted
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Mute interaction defer failed: ${err}`));
await submitted.deferReply({ ephemeral: true });
}
const duration = submitted.fields.getTextInputValue("duration");
@ -144,6 +134,5 @@ export async function launchMuteActionModal(
const evidence = submitted.fields.getTextInputValue("evidence");
await muteAction(pluginData, duration, reason, evidence, target, interaction, submitted);
})
.catch((err) => logger.error(`Mute modal interaction failed: ${err}`));
});
}

View file

@ -8,8 +8,8 @@ import {
TextInputStyle,
} from "discord.js";
import { GuildPluginData } from "knub";
import { canActOn } from "src/pluginUtils";
import { ModActionsPlugin } from "src/plugins/ModActions/ModActionsPlugin";
import { canActOn } from "../../../pluginUtils";
import { ModActionsPlugin } from "../../ModActions/ModActionsPlugin";
import { CaseTypes } from "../../../data/CaseTypes";
import { logger } from "../../../logger";
import { CasesPlugin } from "../../../plugins/Cases/CasesPlugin";
@ -34,25 +34,21 @@ async function noteAction(
const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasNotePermission(executingMember, interaction.channelId))) {
await interactionToReply
.editReply({
content: "Cannot note: insufficient permissions",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Note interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Cannot note: insufficient permissions",
embeds: [],
components: [],
});
return;
}
const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply
.editReply({
content: "Cannot note: insufficient permissions",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Note interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Cannot note: insufficient permissions",
embeds: [],
components: [],
});
return;
}
@ -72,13 +68,11 @@ async function noteAction(
});
const userName = renderUserUsername(targetMember.user);
await interactionToReply
.editReply({
content: `Note added on **${userName}** (Case #${createdCase.case_number})`,
embeds: [],
components: [],
})
.catch((err) => logger.error(`Note interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: `Note added on **${userName}** (Case #${createdCase.case_number})`,
embeds: [],
components: [],
});
}
export async function launchNoteActionModal(
@ -99,14 +93,11 @@ export async function launchNoteActionModal(
if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Note interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) {
await submitted
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Note interaction defer failed: ${err}`));
await submitted.deferReply({ ephemeral: true });
}
const reason = submitted.fields.getTextInputValue("reason");
await noteAction(pluginData, reason, target, interaction, submitted);
})
.catch((err) => logger.error(`Note modal interaction failed: ${err}`));
});
}

View file

@ -2,8 +2,8 @@ import { GuildMember } from "discord.js";
import { GuildPluginData } from "knub";
import { CaseTypes } from "../../../data/CaseTypes";
import { Case } from "../../../data/entities/Case";
import { CasesPlugin } from "../../../plugins/Cases/CasesPlugin";
import { LogsPlugin } from "../../../plugins/Logs/LogsPlugin";
import { CasesPlugin } from "../../Cases/CasesPlugin";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { ContextMenuPluginType } from "../types";
export async function updateAction(
@ -19,7 +19,7 @@ export async function updateAction(
body: value,
});
pluginData.getPlugin(LogsPlugin).logCaseUpdate({
void pluginData.getPlugin(LogsPlugin).logCaseUpdate({
mod: executingMember.user,
caseNumber: theCase.case_number,
caseType: CaseTypes[theCase.type],

View file

@ -8,8 +8,8 @@ import {
TextInputStyle,
} from "discord.js";
import { GuildPluginData } from "knub";
import { canActOn } from "src/pluginUtils";
import { ModActionsPlugin } from "src/plugins/ModActions/ModActionsPlugin";
import { canActOn } from "../../../pluginUtils";
import { ModActionsPlugin } from "../../ModActions/ModActionsPlugin";
import { logger } from "../../../logger";
import { renderUserUsername } from "../../../utils";
import { CaseArgs } from "../../Cases/types";
@ -34,25 +34,21 @@ async function warnAction(
const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasWarnPermission(executingMember, interaction.channelId))) {
await interactionToReply
.editReply({
content: "Cannot warn: insufficient permissions",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Cannot warn: insufficient permissions",
embeds: [],
components: [],
});
return;
}
const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply
.editReply({
content: "Cannot warn: insufficient permissions",
embeds: [],
components: [],
})
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
await interactionToReply.editReply({
content: "Cannot warn: insufficient permissions",
embeds: [],
components: [],
});
return;
}
@ -62,9 +58,7 @@ async function warnAction(
const result = await modactions.warnMember(targetMember, reason, reason, { caseArgs });
if (result.status === "failed") {
await interactionToReply
.editReply({ content: "Error: Failed to warn user", embeds: [], components: [] })
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: "Error: Failed to warn user", embeds: [], components: [] });
return;
}
@ -76,9 +70,7 @@ async function warnAction(
await updateAction(pluginData, executingMember, result.case, evidence);
}
await interactionToReply
.editReply({ content: muteMessage, embeds: [], components: [] })
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
await interactionToReply.editReply({ content: muteMessage, embeds: [], components: [] });
}
export async function launchWarnActionModal(
@ -105,15 +97,12 @@ export async function launchWarnActionModal(
if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Warn interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) {
await submitted
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Warn interaction defer failed: ${err}`));
await submitted.deferReply({ ephemeral: true });
}
const reason = submitted.fields.getTextInputValue("reason");
const evidence = submitted.fields.getTextInputValue("evidence");
await warnAction(pluginData, reason, evidence, target, interaction, submitted);
})
.catch((err) => logger.error(`Warn modal interaction failed: ${err}`));
});
}

View file

@ -12,7 +12,7 @@ import {
import { GuildPluginData, guildPluginUserContextMenuCommand } from "knub";
import { Case } from "../../../data/entities/Case";
import { logger } from "../../../logger";
import { ModActionsPlugin } from "../../../plugins/ModActions/ModActionsPlugin";
import { ModActionsPlugin } from "../../ModActions/ModActionsPlugin";
import { SECONDS, UnknownUser, emptyEmbedValue, renderUserUsername, resolveUser, trimLines } from "../../../utils";
import { asyncMap } from "../../../utils/async";
import { getChunkedEmbedFields } from "../../../utils/getChunkedEmbedFields";
@ -40,9 +40,7 @@ export const ModMenuCmd = guildPluginUserContextMenuCommand({
name: "Mod Menu",
defaultMemberPermissions: PermissionFlagsBits.ViewAuditLog.toString(),
async run({ pluginData, interaction }) {
await interaction
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Mod menu interaction defer failed: ${err}`));
await interaction.deferReply({ ephemeral: true });
// Run permission checks for executing user.
const executingMember = await pluginData.guild.members.fetch(interaction.user.id);
@ -50,22 +48,14 @@ export const ModMenuCmd = guildPluginUserContextMenuCommand({
channelId: interaction.channelId,
member: executingMember,
});
const utility = pluginData.getPlugin(UtilityPlugin);
if (
!userCfg.can_use ||
(await !utility.hasPermission(executingMember, interaction.channelId, "can_open_mod_menu"))
) {
await interaction
.followUp({ content: "Error: Insufficient Permissions" })
.catch((err) => logger.error(`Mod menu interaction follow up failed: ${err}`));
if (!userCfg.can_use || !userCfg.can_open_mod_menu) {
await interaction.followUp({ content: "Error: Insufficient Permissions" });
return;
}
const user = await resolveUser(pluginData.client, interaction.targetId);
if (!user.id) {
await interaction
.followUp("Error: User not found")
.catch((err) => logger.error(`Mod menu interaction follow up failed: ${err}`));
await interaction.followUp("Error: User not found");
return;
}

View file

@ -19,6 +19,7 @@ import { offCounterEvent } from "./functions/offCounterEvent";
import { onCounterEvent } from "./functions/onCounterEvent";
import { setCounterValue } from "./functions/setCounterValue";
import { CountersPluginType, zCountersConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const DECAY_APPLY_INTERVAL = 5 * MINUTES;
@ -127,6 +128,10 @@ export const CountersPlugin = guildPlugin<CountersPluginType>()({
await state.counters.markUnusedTriggersToBeDeleted(activeTriggerIds);
},
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
async afterLoad(pluginData) {
const { state } = pluginData;

View file

@ -45,22 +45,22 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
const counter = config.counters[args.counterName];
const counterId = pluginData.state.counterIds[args.counterName];
if (!counter || !counterId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
void pluginData.state.common.sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
return;
}
if (counter.can_edit === false) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Missing permissions to edit this counter's value`);
void pluginData.state.common.sendErrorMessage(message, `Missing permissions to edit this counter's value`);
return;
}
if (args.channel && !counter.per_channel) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-channel`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-channel`);
return;
}
if (args.user && !counter.per_user) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-user`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-user`);
return;
}
@ -69,13 +69,13 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which channel's counter value would you like to add to?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialChannel = pluginData.guild.channels.resolve(reply.content as Snowflake);
if (!potentialChannel || !(potentialChannel instanceof TextChannel)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Channel is not a text channel, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Channel is not a text channel, cancelling");
return;
}
@ -87,13 +87,13 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which user's counter value would you like to add to?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialUser = await resolveUser(pluginData.client, reply.content);
if (!potentialUser || potentialUser instanceof UnknownUser) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Unknown user, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Unknown user, cancelling");
return;
}
@ -105,13 +105,13 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send("How much would you like to add to the counter's value?");
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialAmount = parseInt(reply.content, 10);
if (!potentialAmount) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Not a number, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Not a number, cancelling");
return;
}

View file

@ -15,7 +15,7 @@ export const CountersListCmd = guildPluginMessageCommand<CountersPluginType>()({
const countersToShow = Array.from(Object.values(config.counters)).filter((c) => c.can_view !== false);
if (!countersToShow.length) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "No counters are configured for this server");
void pluginData.state.common.sendErrorMessage(message, "No counters are configured for this server");
return;
}

View file

@ -18,14 +18,12 @@ export const ResetAllCounterValuesCmd = guildPluginMessageCommand<CountersPlugin
const counter = config.counters[args.counterName];
const counterId = pluginData.state.counterIds[args.counterName];
if (!counter || !counterId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
void pluginData.state.common.sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
return;
}
if (counter.can_reset_all === false) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(message, `Missing permissions to reset all of this counter's values`);
void pluginData.state.common.sendErrorMessage(message, `Missing permissions to reset all of this counter's values`);
return;
}
@ -38,7 +36,7 @@ export const ResetAllCounterValuesCmd = guildPluginMessageCommand<CountersPlugin
`),
});
if (!confirmed) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelled");
void pluginData.state.common.sendErrorMessage(message, "Cancelled");
return;
}
@ -49,9 +47,7 @@ export const ResetAllCounterValuesCmd = guildPluginMessageCommand<CountersPlugin
await resetAllCounterValues(pluginData, args.counterName);
loadingMessage?.delete().catch(noop);
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(message, `All counter values for **${counterName}** have been reset`);
void pluginData.state.common.sendSuccessMessage(message, `All counter values for **${counterName}** have been reset`);
pluginData.getKnubInstance().reloadGuild(pluginData.guild.id);
},

View file

@ -40,22 +40,22 @@ export const ResetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
const counter = config.counters[args.counterName];
const counterId = pluginData.state.counterIds[args.counterName];
if (!counter || !counterId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
void pluginData.state.common.sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
return;
}
if (counter.can_edit === false) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Missing permissions to reset this counter's value`);
void pluginData.state.common.sendErrorMessage(message, `Missing permissions to reset this counter's value`);
return;
}
if (args.channel && !counter.per_channel) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-channel`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-channel`);
return;
}
if (args.user && !counter.per_user) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-user`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-user`);
return;
}
@ -64,13 +64,13 @@ export const ResetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which channel's counter value would you like to reset?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialChannel = pluginData.guild.channels.resolve(reply.content as Snowflake);
if (!potentialChannel || !(potentialChannel instanceof TextChannel)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Channel is not a text channel, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Channel is not a text channel, cancelling");
return;
}
@ -82,13 +82,13 @@ export const ResetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which user's counter value would you like to reset?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialUser = await resolveUser(pluginData.client, reply.content);
if (!potentialUser || potentialUser instanceof UnknownUser) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Unknown user, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Unknown user, cancelling");
return;
}

View file

@ -45,22 +45,22 @@ export const SetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
const counter = config.counters[args.counterName];
const counterId = pluginData.state.counterIds[args.counterName];
if (!counter || !counterId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
void pluginData.state.common.sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
return;
}
if (counter.can_edit === false) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Missing permissions to edit this counter's value`);
void pluginData.state.common.sendErrorMessage(message, `Missing permissions to edit this counter's value`);
return;
}
if (args.channel && !counter.per_channel) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-channel`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-channel`);
return;
}
if (args.user && !counter.per_user) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-user`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-user`);
return;
}
@ -69,13 +69,13 @@ export const SetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which channel's counter value would you like to change?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialChannel = pluginData.guild.channels.resolve(reply.content as Snowflake);
if (!potentialChannel || !(potentialChannel instanceof TextChannel)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Channel is not a text channel, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Channel is not a text channel, cancelling");
return;
}
@ -87,13 +87,13 @@ export const SetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which user's counter value would you like to change?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialUser = await resolveUser(pluginData.client, reply.content);
if (!potentialUser || potentialUser instanceof UnknownUser) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Unknown user, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Unknown user, cancelling");
return;
}
@ -105,13 +105,13 @@ export const SetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send("What would you like to set the counter's value to?");
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialValue = parseInt(reply.content, 10);
if (Number.isNaN(potentialValue)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Not a number, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Not a number, cancelling");
return;
}
@ -119,7 +119,7 @@ export const SetCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
}
if (value < 0) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cannot set counter value below 0");
void pluginData.state.common.sendErrorMessage(message, "Cannot set counter value below 0");
return;
}

View file

@ -39,22 +39,22 @@ export const ViewCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
const counter = config.counters[args.counterName];
const counterId = pluginData.state.counterIds[args.counterName];
if (!counter || !counterId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
void pluginData.state.common.sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
return;
}
if (counter.can_view === false) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Missing permissions to view this counter's value`);
void pluginData.state.common.sendErrorMessage(message, `Missing permissions to view this counter's value`);
return;
}
if (args.channel && !counter.per_channel) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-channel`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-channel`);
return;
}
if (args.user && !counter.per_user) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `This counter is not per-user`);
void pluginData.state.common.sendErrorMessage(message, `This counter is not per-user`);
return;
}
@ -63,13 +63,13 @@ export const ViewCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which channel's counter value would you like to view?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialChannel = pluginData.guild.channels.resolve(reply.content as Snowflake);
if (!potentialChannel?.isTextBased()) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Channel is not a text channel, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Channel is not a text channel, cancelling");
return;
}
@ -81,13 +81,13 @@ export const ViewCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which user's counter value would you like to view?`);
const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling");
void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return;
}
const potentialUser = await resolveUser(pluginData.client, reply.content);
if (!potentialUser || potentialUser instanceof UnknownUser) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Unknown user, cancelling");
void pluginData.state.common.sendErrorMessage(message, "Unknown user, cancelling");
return;
}

View file

@ -1,5 +1,5 @@
import { EventEmitter } from "events";
import { BasePluginType } from "knub";
import { BasePluginType, pluginUtils } from "knub";
import z from "zod";
import { GuildCounters, MAX_COUNTER_VALUE, MIN_COUNTER_VALUE } from "../../data/GuildCounters";
import {
@ -10,6 +10,7 @@ import {
} from "../../data/entities/CounterTrigger";
import { zBoundedCharacters, zBoundedRecord, zDelayString } from "../../utils";
import Timeout = NodeJS.Timeout;
import { CommonPlugin } from "../Common/CommonPlugin";
const MAX_COUNTERS = 5;
const MAX_TRIGGERS_PER_COUNTER = 5;
@ -132,5 +133,6 @@ export interface CountersPluginType extends BasePluginType {
decayTimers: Timeout[];
events: CounterEventEmitter;
counterTriggersByCounterId: Map<number, CounterTrigger[]>;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
};
}

View file

@ -14,6 +14,7 @@ import {
import { LogsPlugin } from "../Logs/LogsPlugin";
import { runEvent } from "./functions/runEvent";
import { CustomEventsPluginType, zCustomEventsConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions = {
config: {
@ -28,6 +29,10 @@ export const CustomEventsPlugin = guildPlugin<CustomEventsPluginType>()({
configParser: (input) => zCustomEventsConfig.parse(input),
defaultOptions,
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
afterLoad(pluginData) {
const config = pluginData.config.get();
for (const [key, event] of Object.entries(config.events)) {

View file

@ -39,7 +39,7 @@ export async function runEvent(
} catch (e) {
if (e instanceof ActionError) {
if (event.trigger.type === "command") {
pluginData.getPlugin(CommonPlugin).sendErrorMessage((eventData.msg as Message).channel, e.message);
void pluginData.state.common.sendErrorMessage((eventData.msg as Message).channel, e.message);
} else {
// TODO: Where to log action errors from other kinds of triggers?
}

View file

@ -1,4 +1,4 @@
import { BasePluginType } from "knub";
import { BasePluginType, pluginUtils } from "knub";
import z from "zod";
import { zBoundedCharacters, zBoundedRecord } from "../../utils";
import { zAddRoleAction } from "./actions/addRoleAction";
@ -8,6 +8,7 @@ import { zMakeRoleUnmentionableAction } from "./actions/makeRoleUnmentionableAct
import { zMessageAction } from "./actions/messageAction";
import { zMoveToVoiceChannelAction } from "./actions/moveToVoiceChannelAction";
import { zSetChannelPermissionOverridesAction } from "./actions/setChannelPermissionOverrides";
import { CommonPlugin } from "../Common/CommonPlugin";
const zCommandTrigger = z.strictObject({
type: z.literal("command"),
@ -43,5 +44,6 @@ export interface CustomEventsPluginType extends BasePluginType {
config: z.infer<typeof zCustomEventsConfig>;
state: {
clearTriggers: () => void;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
};
}

View file

@ -9,6 +9,7 @@ import { VoiceStateUpdateAlertEvt } from "./events/SendAlertsEvts";
import { LocateUserPluginType, zLocateUserConfig } from "./types";
import { clearExpiredAlert } from "./utils/clearExpiredAlert";
import { fillActiveAlertsList } from "./utils/fillAlertsList";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions: PluginOptions<LocateUserPluginType> = {
config: {
@ -53,6 +54,10 @@ export const LocateUserPlugin = guildPlugin<LocateUserPluginType>()({
state.usersWithAlerts = [];
},
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
afterLoad(pluginData) {
const { state, guild } = pluginData;

View file

@ -27,9 +27,7 @@ export const FollowCmd = locateUserCmd({
const active = args.active || false;
if (time < 30 * SECONDS) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, "Sorry, but the minimum duration for an alert is 30 seconds!");
void pluginData.state.common.sendErrorMessage(msg, "Sorry, but the minimum duration for an alert is 30 seconds!");
return;
}
@ -48,18 +46,14 @@ export const FollowCmd = locateUserCmd({
}
if (active) {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
void pluginData.state.common.sendSuccessMessage(
msg,
`Every time <@${args.member.id}> joins or switches VC in the next ${humanizeDuration(
time,
)} i will notify and move you.\nPlease make sure to be in a voice channel, otherwise i cannot move you!`,
);
} else {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
void pluginData.state.common.sendSuccessMessage(
msg,
`Every time <@${args.member.id}> joins or switches VC in the next ${humanizeDuration(
time,

View file

@ -13,7 +13,7 @@ export const ListFollowCmd = locateUserCmd({
async run({ message: msg, pluginData }) {
const alerts = await pluginData.state.alerts.getAlertsByRequestorId(msg.member.id);
if (alerts.length === 0) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You have no active alerts!");
void pluginData.state.common.sendErrorMessage(msg, "You have no active alerts!");
return;
}
@ -46,7 +46,7 @@ export const DeleteFollowCmd = locateUserCmd({
alerts.sort(sorter("expires_at"));
if (args.num > alerts.length || args.num <= 0) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Unknown alert!");
void pluginData.state.common.sendErrorMessage(msg, "Unknown alert!");
return;
}
@ -54,6 +54,6 @@ export const DeleteFollowCmd = locateUserCmd({
clearExpiringVCAlert(toDelete);
await pluginData.state.alerts.delete(toDelete.id);
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, "Alert deleted");
void pluginData.state.common.sendSuccessMessage(msg, "Alert deleted");
},
});

View file

@ -1,6 +1,7 @@
import { BasePluginType, guildPluginEventListener, guildPluginMessageCommand } from "knub";
import { BasePluginType, guildPluginEventListener, guildPluginMessageCommand, pluginUtils } from "knub";
import z from "zod";
import { GuildVCAlerts } from "../../data/GuildVCAlerts";
import { CommonPlugin } from "../Common/CommonPlugin";
export const zLocateUserConfig = z.strictObject({
can_where: z.boolean(),
@ -13,6 +14,7 @@ export interface LocateUserPluginType extends BasePluginType {
alerts: GuildVCAlerts;
usersWithAlerts: string[];
unregisterGuildEventListener: () => void;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
};
}

View file

@ -16,14 +16,10 @@ export async function moveMember(
channel: target.voice.channelId,
});
} catch {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(errorChannel, "Failed to move you. Are you in a voice channel?");
void pluginData.state.common.sendErrorMessage(errorChannel, "Failed to move you. Are you in a voice channel?");
return;
}
} else {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(errorChannel, "Failed to move you. Are you in a voice channel?");
void pluginData.state.common.sendErrorMessage(errorChannel, "Failed to move you. Are you in a voice channel?");
}
}

View file

@ -22,7 +22,7 @@ export async function sendWhere(
try {
invite = await createOrReuseInvite(voice);
} catch {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(channel, "Cannot create an invite to that channel!");
void pluginData.state.common.sendErrorMessage(channel, "Cannot create an invite to that channel!");
return;
}
channel.send({

View file

@ -4,6 +4,7 @@ import { SaveMessagesToDBCmd } from "./commands/SaveMessagesToDB";
import { SavePinsToDBCmd } from "./commands/SavePinsToDB";
import { MessageCreateEvt, MessageDeleteBulkEvt, MessageDeleteEvt, MessageUpdateEvt } from "./events/SaveMessagesEvts";
import { MessageSaverPluginType, zMessageSaverConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions: PluginOptions<MessageSaverPluginType> = {
config: {
@ -43,4 +44,8 @@ export const MessageSaverPlugin = guildPlugin<MessageSaverPluginType>()({
const { state, guild } = pluginData;
state.savedMessages = GuildSavedMessages.getGuildInstance(guild.id);
},
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
});

View file

@ -18,14 +18,12 @@ export const SaveMessagesToDBCmd = messageSaverCmd({
const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, args.ids.trim().split(" "));
if (failed.length) {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
void pluginData.state.common.sendSuccessMessage(
msg,
`Saved ${savedCount} messages. The following messages could not be saved: ${failed.join(", ")}`,
);
} else {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Saved ${savedCount} messages!`);
void pluginData.state.common.sendSuccessMessage(msg, `Saved ${savedCount} messages!`);
}
},
});

View file

@ -19,14 +19,12 @@ export const SavePinsToDBCmd = messageSaverCmd({
const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, [...pins.keys()]);
if (failed.length) {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
void pluginData.state.common.sendSuccessMessage(
msg,
`Saved ${savedCount} messages. The following messages could not be saved: ${failed.join(", ")}`,
);
} else {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Saved ${savedCount} messages!`);
void pluginData.state.common.sendSuccessMessage(msg, `Saved ${savedCount} messages!`);
}
},
});

View file

@ -1,6 +1,7 @@
import { BasePluginType, guildPluginEventListener, guildPluginMessageCommand } from "knub";
import { BasePluginType, guildPluginEventListener, guildPluginMessageCommand, pluginUtils } from "knub";
import z from "zod";
import { GuildSavedMessages } from "../../data/GuildSavedMessages";
import { CommonPlugin } from "../Common/CommonPlugin";
export const zMessageSaverConfig = z.strictObject({
can_manage: z.boolean(),
@ -10,6 +11,7 @@ export interface MessageSaverPluginType extends BasePluginType {
config: z.infer<typeof zMessageSaverConfig>;
state: {
savedMessages: GuildSavedMessages;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
};
}

View file

@ -72,6 +72,7 @@ import { onModActionsEvent } from "./functions/onModActionsEvent";
import { updateCase } from "./functions/updateCase";
import { warnMember } from "./functions/warnMember";
import { AttachmentLinkReactionType, ModActionsPluginType, modActionsSlashGroup, zModActionsConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions = {
config: {
@ -94,7 +95,6 @@ const defaultOptions = {
"The user already has **{priorWarnings}** warnings!\n Please check their prior cases and assess whether or not to warn anyways.\n Proceed with the warning?",
ban_delete_message_days: 1,
attachment_link_reaction: "warn" as AttachmentLinkReactionType,
attachment_storing_channel: null,
can_note: false,
can_warn: false,
@ -236,6 +236,10 @@ export const ModActionsPlugin = guildPlugin<ModActionsPluginType>()({
state.events = new EventEmitter();
},
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
afterLoad(pluginData) {
const { state, guild } = pluginData;

View file

@ -2,8 +2,7 @@ import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { CaseTypes } from "../../../../data/CaseTypes";
import { hasPermission } from "../../../../pluginUtils";
import { resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualAddCaseCmd } from "../../functions/actualCommands/actualAddCaseCmd";
import { actualAddCaseCmd } from "./actualAddCaseCmd";
import { modActionsMsgCmd } from "../../types";
const opts = {
@ -28,7 +27,7 @@ export const AddCaseMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
@ -36,7 +35,7 @@ export const AddCaseMsgCmd = modActionsMsgCmd({
let mod = msg.member;
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}
@ -46,7 +45,7 @@ export const AddCaseMsgCmd = modActionsMsgCmd({
// Verify the case type is valid
const type: string = args.type[0].toUpperCase() + args.type.slice(1).toLowerCase();
if (!CaseTypes[type]) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cannot add case: invalid case type");
pluginData.state.common.sendErrorMessage(msg, "Cannot add case: invalid case type");
return;
}

View file

@ -4,8 +4,7 @@ import { CaseTypes } from "../../../../data/CaseTypes";
import { hasPermission } from "../../../../pluginUtils";
import { resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualAddCaseCmd } from "../../functions/actualCommands/actualAddCaseCmd";
import { actualAddCaseCmd } from "./actualAddCaseCmd";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -49,9 +48,10 @@ export const AddCaseSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}

View file

@ -5,11 +5,10 @@ import { Case } from "../../../../data/entities/Case";
import { canActOn } from "../../../../pluginUtils";
import { UnknownUser, renderUsername, resolveMember } from "../../../../utils";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
export async function actualAddCaseCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -28,9 +27,10 @@ export async function actualAddCaseCmd(
// If the user exists as a guild member, make sure we can act on them first
const member = await resolveMember(pluginData.client, pluginData.guild, user.id);
if (member && !canActOn(pluginData, author, member)) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "Cannot add case on this user: insufficient permissions");
pluginData.state.common.sendErrorMessage(
context,
"Cannot add case on this user: insufficient permissions"
);
return;
}
@ -47,11 +47,12 @@ export async function actualAddCaseCmd(
});
if (user) {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(context, `Case #${theCase.case_number} created for **${renderUsername(user)}**`);
pluginData.state.common.sendSuccessMessage(
context,
`Case #${theCase.case_number} created for **${renderUsername(user)}**`
);
} else {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(context, `Case #${theCase.case_number} created`);
pluginData.state.common.sendSuccessMessage(context, `Case #${theCase.case_number} created`);
}
// Log the action

View file

@ -1,8 +1,7 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { hasPermission } from "../../../../pluginUtils";
import { UserNotificationMethod, resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualBanCmd } from "../../functions/actualCommands/actualBanCmd";
import { actualBanCmd } from "./actualBanCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsMsgCmd } from "../../types";
@ -38,7 +37,7 @@ export const BanMsgCmd = modActionsMsgCmd({
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
@ -46,7 +45,7 @@ export const BanMsgCmd = modActionsMsgCmd({
let mod = msg.member;
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}
@ -57,7 +56,7 @@ export const BanMsgCmd = modActionsMsgCmd({
try {
contactMethods = readContactMethodsFromArgs(args) ?? undefined;
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, e.message);
pluginData.state.common.sendErrorMessage(msg, e.message);
return;
}

View file

@ -3,8 +3,7 @@ import { slashOptions } from "knub";
import { hasPermission } from "../../../../pluginUtils";
import { UserNotificationMethod, convertDelayStringToMS, resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualBanCmd } from "../../functions/actualCommands/actualBanCmd";
import { actualBanCmd } from "./actualBanCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -52,9 +51,13 @@ export const BanSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}
@ -67,9 +70,10 @@ export const BanSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}
@ -80,13 +84,13 @@ export const BanSlashCmd = modActionsSlashCmd({
try {
contactMethods = readContactMethodsFromArgs(options) ?? undefined;
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, e.message);
pluginData.state.common.sendErrorMessage(interaction, e.message);
return;
}
const convertedTime = options.time ? convertDelayStringToMS(options.time) : null;
if (options.time && !convertedTime) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
pluginData.state.common.sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
return;
}

View file

@ -9,13 +9,12 @@ import { UnknownUser, UserNotificationMethod, renderUsername, resolveMember } fr
import { banLock } from "../../../../utils/lockNameHelpers";
import { waitForButtonConfirm } from "../../../../utils/waitForInteraction";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { banUserId } from "../banUserId";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { isBanned } from "../isBanned";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { banUserId } from "../../functions/banUserId";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
import { isBanned } from "../../functions/isBanned";
export async function actualBanCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -54,7 +53,7 @@ export async function actualBanCmd(
);
if (!reply) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "User not on server, ban cancelled by moderator");
pluginData.state.common.sendErrorMessage(context, "User not on server, ban cancelled by moderator");
lock.unlock();
return;
} else {
@ -63,7 +62,7 @@ export async function actualBanCmd(
} else {
// Abort if trying to ban user indefinitely if they are already banned indefinitely
if (!existingTempban && !time) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `User is already banned indefinitely.`);
pluginData.state.common.sendErrorMessage(context, `User is already banned indefinitely.`);
return;
}
@ -75,9 +74,10 @@ export async function actualBanCmd(
);
if (!reply) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "User already banned, update cancelled by moderator");
pluginData.state.common.sendErrorMessage(
context,
"User already banned, update cancelled by moderator"
);
lock.unlock();
return;
}
@ -122,9 +122,7 @@ export async function actualBanCmd(
});
}
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
pluginData.state.common.sendSuccessMessage(
context,
`Ban updated to ${time ? "expire in " + humanizeDuration(time) + " from now" : "indefinite"}`,
);
@ -137,11 +135,9 @@ export async function actualBanCmd(
if (!forceban && !canActOn(pluginData, author, memberToBan!)) {
const ourLevel = getMemberLevel(pluginData, author);
const targetLevel = getMemberLevel(pluginData, memberToBan!);
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(
context,
`Cannot ban: target permission level is equal or higher to yours, ${targetLevel} >= ${ourLevel}`,
pluginData.state.common.sendErrorMessage(
context,
`Cannot ban: target permission level is equal or higher to yours, ${targetLevel} >= ${ourLevel}`,
);
lock.unlock();
return;
@ -170,7 +166,7 @@ export async function actualBanCmd(
);
if (banResult.status === "failed") {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `Failed to ban member: ${banResult.error}`);
pluginData.state.common.sendErrorMessage(context, `Failed to ban member: ${banResult.error}`);
lock.unlock();
return;
}
@ -190,5 +186,5 @@ export async function actualBanCmd(
}
lock.unlock();
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(context, response);
pluginData.state.common.sendSuccessMessage(context, response);
}

View file

@ -1,5 +1,5 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { actualCaseCmd } from "../../functions/actualCommands/actualCaseCmd";
import { actualCaseCmd } from "./actualCaseCmd";
import { modActionsMsgCmd } from "../../types";
const opts = {

View file

@ -1,5 +1,5 @@
import { slashOptions } from "knub";
import { actualCaseCmd } from "../../functions/actualCommands/actualCaseCmd";
import { actualCaseCmd } from "./actualCaseCmd";
import { modActionsSlashCmd } from "../../types";
const opts = [

View file

@ -2,7 +2,6 @@ import { ChatInputCommandInteraction, Message } from "discord.js";
import { GuildPluginData } from "knub";
import { sendContextResponse } from "../../../../pluginUtils";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { ModActionsPluginType } from "../../types";
export async function actualCaseCmd(
@ -15,12 +14,12 @@ export async function actualCaseCmd(
const theCase = await pluginData.state.cases.findByCaseNumber(caseNumber);
if (!theCase) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "Case not found", undefined, undefined, show !== true);
void pluginData.state.common.sendErrorMessage(context, "Case not found", undefined, undefined, show !== true);
return;
}
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const embed = await casesPlugin.getCaseEmbed(theCase.id, authorId);
sendContextResponse(context, { ...embed, ephemeral: show !== true });
void sendContextResponse(context, { ...embed, ephemeral: show !== true });
}

View file

@ -1,5 +1,5 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { actualCasesCmd } from "../../functions/actualCommands/actualCasesCmd";
import { actualCasesCmd } from "./actualCasesCmd";
import { modActionsMsgCmd } from "../../types";
const opts = {

View file

@ -1,6 +1,6 @@
import { GuildMember } from "discord.js";
import { slashOptions } from "knub";
import { actualCasesCmd } from "../../functions/actualCommands/actualCasesCmd";
import { actualCasesCmd } from "./actualCasesCmd";
import { modActionsSlashCmd } from "../../types";
const opts = [

View file

@ -1,7 +1,6 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { resolveMember, resolveUser, UnknownUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualCasesCmd } from "../../functions/actualCommands/actualCasesCmd";
import { actualCasesCmd } from "./actualCasesCmd";
import { modActionsMsgCmd } from "../../types";
const opts = {
@ -38,7 +37,7 @@ export const CasesUserMsgCmd = modActionsMsgCmd({
(await resolveUser(pluginData.client, args.user));
if (user instanceof UnknownUser) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}

View file

@ -18,7 +18,6 @@ import { asyncMap } from "../../../../utils/async";
import { createPaginatedMessage } from "../../../../utils/createPaginatedMessage";
import { getGuildPrefix } from "../../../../utils/getGuildPrefix";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { ModActionsPluginType } from "../../types";
const casesPerPage = 5;
@ -160,9 +159,13 @@ async function casesModCmd(
const totalCases = await casesPlugin.getTotalCasesByMod(modId ?? author.id, casesFilters);
if (totalCases === 0) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, `No cases by **${modName}**`, undefined, undefined, !show);
pluginData.state.common.sendErrorMessage(
context,
`No cases by **${modName}**`,
undefined,
undefined,
!show
);
return;
}

View file

@ -1,6 +1,6 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { trimLines } from "../../../../utils";
import { actualDeleteCaseCmd } from "../../functions/actualCommands/actualDeleteCaseCmd";
import { actualDeleteCaseCmd } from "./actualDeleteCaseCmd";
import { modActionsMsgCmd } from "../../types";
export const DeleteCaseMsgCmd = modActionsMsgCmd({

View file

@ -1,6 +1,6 @@
import { GuildMember } from "discord.js";
import { slashOptions } from "knub";
import { actualDeleteCaseCmd } from "../../functions/actualCommands/actualDeleteCaseCmd";
import { actualDeleteCaseCmd } from "./actualDeleteCaseCmd";
import { modActionsSlashCmd } from "../../types";
const opts = [slashOptions.boolean({ name: "force", description: "Whether or not to force delete", required: false })];

View file

@ -4,7 +4,6 @@ import { Case } from "../../../../data/entities/Case";
import { getContextChannel, sendContextResponse } from "../../../../pluginUtils";
import { SECONDS, renderUsername } from "../../../../utils";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { TimeAndDatePlugin } from "../../../TimeAndDate/TimeAndDatePlugin";
import { ModActionsPluginType } from "../../types";
@ -31,7 +30,7 @@ export async function actualDeleteCaseCmd(
}
if (failed.length === caseNumbers.length) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "None of the cases were found!");
pluginData.state.common.sendErrorMessage(context, "None of the cases were found!");
return;
}
@ -83,13 +82,15 @@ export async function actualDeleteCaseCmd(
: "";
const amt = validCases.length - cancelled;
if (amt === 0) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "All deletions were cancelled, no cases were deleted.");
pluginData.state.common.sendErrorMessage(
context,
"All deletions were cancelled, no cases were deleted."
);
return;
}
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(context, `${amt} case${amt === 1 ? " was" : "s were"} deleted!${failedAddendum}`);
pluginData.state.common.sendSuccessMessage(
context,
`${amt} case${amt === 1 ? " was" : "s were"} deleted!${failedAddendum}`
);
}

View file

@ -1,8 +1,7 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { canActOn, hasPermission } from "../../../../pluginUtils";
import { resolveMember, resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualForceBanCmd } from "../../functions/actualCommands/actualForceBanCmd";
import { actualForceBanCmd } from "./actualForceBanCmd";
import { isBanned } from "../../functions/isBanned";
import { modActionsMsgCmd } from "../../types";
@ -27,21 +26,21 @@ export const ForceBanMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
// If the user exists as a guild member, make sure we can act on them first
const member = await resolveMember(pluginData.client, pluginData.guild, user.id);
if (member && !canActOn(pluginData, msg.member, member)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cannot forceban this user: insufficient permissions");
pluginData.state.common.sendErrorMessage(msg, "Cannot forceban this user: insufficient permissions");
return;
}
// Make sure the user isn't already banned
const banned = await isBanned(pluginData, user.id);
if (banned) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User is already banned`);
pluginData.state.common.sendErrorMessage(msg, `User is already banned`);
return;
}
@ -49,7 +48,7 @@ export const ForceBanMsgCmd = modActionsMsgCmd({
let mod = msg.member;
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}

View file

@ -3,8 +3,7 @@ import { slashOptions } from "knub";
import { hasPermission } from "../../../../pluginUtils";
import { convertDelayStringToMS, resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualForceBanCmd } from "../../functions/actualCommands/actualForceBanCmd";
import { actualForceBanCmd } from "./actualForceBanCmd";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -30,9 +29,13 @@ export const ForceBanSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}
@ -45,9 +48,10 @@ export const ForceBanSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}
@ -56,7 +60,7 @@ export const ForceBanSlashCmd = modActionsSlashCmd({
const convertedTime = options.time ? convertDelayStringToMS(options.time) : null;
if (options.time && !convertedTime) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
pluginData.state.common.sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
return;
}

View file

@ -4,12 +4,11 @@ import { CaseTypes } from "../../../../data/CaseTypes";
import { LogType } from "../../../../data/LogType";
import { DAYS, MINUTES, UnknownUser } from "../../../../utils";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { IgnoredEventType, ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { ignoreEvent } from "../ignoreEvent";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
import { ignoreEvent } from "../../functions/ignoreEvent";
export async function actualForceBanCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -37,7 +36,7 @@ export async function actualForceBanCmd(
reason: formattedReasonWithAttachments ?? undefined,
});
} catch {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "Failed to forceban member");
pluginData.state.common.sendErrorMessage(context, "Failed to forceban member");
return;
}
@ -52,9 +51,7 @@ export async function actualForceBanCmd(
});
// Confirm the action
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(context, `Member forcebanned (Case #${createdCase.case_number})`);
pluginData.state.common.sendSuccessMessage(context, `Member forcebanned (Case #${createdCase.case_number})`);
// Log the action
pluginData.getPlugin(LogsPlugin).logMemberForceban({

View file

@ -1,8 +1,7 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { canActOn, hasPermission } from "../../../../pluginUtils";
import { resolveMember, resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMuteCmd } from "../../functions/actualCommands/actualMuteCmd";
import { actualMuteCmd } from "../mute/actualMuteCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsMsgCmd } from "../../types";
@ -36,7 +35,7 @@ export const ForceMuteMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
@ -44,7 +43,7 @@ export const ForceMuteMsgCmd = modActionsMsgCmd({
// Make sure we're allowed to mute this user
if (memberToMute && !canActOn(pluginData, msg.member, memberToMute)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cannot mute: insufficient permissions");
pluginData.state.common.sendErrorMessage(msg, "Cannot mute: insufficient permissions");
return;
}
@ -54,7 +53,7 @@ export const ForceMuteMsgCmd = modActionsMsgCmd({
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}
@ -66,7 +65,7 @@ export const ForceMuteMsgCmd = modActionsMsgCmd({
try {
contactMethods = readContactMethodsFromArgs(args);
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, e.message);
pluginData.state.common.sendErrorMessage(msg, e.message);
return;
}

View file

@ -3,8 +3,7 @@ import { slashOptions } from "knub";
import { hasPermission } from "../../../../pluginUtils";
import { UserNotificationMethod, convertDelayStringToMS, resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMuteCmd } from "../../functions/actualCommands/actualMuteCmd";
import { actualMuteCmd } from "../mute/actualMuteCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -47,9 +46,13 @@ export const ForceMuteSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}
@ -63,9 +66,10 @@ export const ForceMuteSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}
@ -75,7 +79,7 @@ export const ForceMuteSlashCmd = modActionsSlashCmd({
const convertedTime = options.time ? convertDelayStringToMS(options.time) ?? undefined : undefined;
if (options.time && !convertedTime) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
pluginData.state.common.sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
return;
}
@ -83,7 +87,7 @@ export const ForceMuteSlashCmd = modActionsSlashCmd({
try {
contactMethods = readContactMethodsFromArgs(options) ?? undefined;
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, e.message);
pluginData.state.common.sendErrorMessage(interaction, e.message);
return;
}

View file

@ -1,8 +1,7 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { canActOn, hasPermission } from "../../../../pluginUtils";
import { resolveMember, resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualUnmuteCmd } from "../../functions/actualCommands/actualUnmuteCmd";
import { actualUnmuteCmd } from "../unmute/actualUnmuteCmd";
import { modActionsMsgCmd } from "../../types";
const opts = {
@ -33,13 +32,13 @@ export const ForceUnmuteMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
// Check if they're muted in the first place
if (!(await pluginData.state.mutes.isMuted(user.id))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cannot unmute: member is not muted");
pluginData.state.common.sendErrorMessage(msg, "Cannot unmute: member is not muted");
return;
}
@ -48,7 +47,7 @@ export const ForceUnmuteMsgCmd = modActionsMsgCmd({
// Make sure we're allowed to unmute this member
if (memberToUnmute && !canActOn(pluginData, msg.member, memberToUnmute)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cannot unmute: insufficient permissions");
pluginData.state.common.sendErrorMessage(msg, "Cannot unmute: insufficient permissions");
return;
}
@ -58,7 +57,7 @@ export const ForceUnmuteMsgCmd = modActionsMsgCmd({
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}

View file

@ -3,8 +3,7 @@ import { slashOptions } from "knub";
import { hasPermission } from "../../../../pluginUtils";
import { convertDelayStringToMS, resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualUnmuteCmd } from "../../functions/actualCommands/actualUnmuteCmd";
import { actualUnmuteCmd } from "../unmute/actualUnmuteCmd";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -31,9 +30,13 @@ export const ForceUnmuteSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}
@ -47,9 +50,10 @@ export const ForceUnmuteSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}
@ -59,7 +63,7 @@ export const ForceUnmuteSlashCmd = modActionsSlashCmd({
const convertedTime = options.time ? convertDelayStringToMS(options.time) ?? undefined : undefined;
if (options.time && !convertedTime) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
pluginData.state.common.sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
return;
}

View file

@ -1,5 +1,5 @@
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { actualHideCaseCmd } from "../../functions/actualCommands/actualHideCaseCmd";
import { actualHideCaseCmd } from "./actualHideCaseCmd";
import { modActionsMsgCmd } from "../../types";
export const HideCaseMsgCmd = modActionsMsgCmd({

View file

@ -1,5 +1,5 @@
import { slashOptions } from "knub";
import { actualHideCaseCmd } from "../../functions/actualCommands/actualHideCaseCmd";
import { actualHideCaseCmd } from "./actualHideCaseCmd";
import { modActionsSlashCmd } from "../../types";
export const HideCaseSlashCmd = modActionsSlashCmd({

View file

@ -1,6 +1,5 @@
import { ChatInputCommandInteraction, Message } from "discord.js";
import { GuildPluginData } from "knub";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { ModActionsPluginType } from "../../types";
export async function actualHideCaseCmd(
@ -21,7 +20,7 @@ export async function actualHideCaseCmd(
}
if (failed.length === caseNumbers.length) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "None of the cases were found!");
pluginData.state.common.sendErrorMessage(context, "None of the cases were found!");
return;
}
const failedAddendum =
@ -30,9 +29,7 @@ export async function actualHideCaseCmd(
: "";
const amt = caseNumbers.length - failed.length;
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
pluginData.state.common.sendSuccessMessage(
context,
`${amt} case${amt === 1 ? " is" : "s are"} now hidden! Use \`unhidecase\` to unhide them.${failedAddendum}`,
);

View file

@ -1,8 +1,7 @@
import { hasPermission } from "knub/helpers";
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualKickCmd } from "../../functions/actualCommands/actualKickCmd";
import { actualKickCmd } from "./actualKickCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsMsgCmd } from "../../types";
@ -30,7 +29,7 @@ export const KickMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
@ -38,7 +37,7 @@ export const KickMsgCmd = modActionsMsgCmd({
let mod = msg.member;
if (args.mod) {
if (!(await hasPermission(await pluginData.config.getForMessage(msg), "can_act_as_other"))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}
@ -49,7 +48,7 @@ export const KickMsgCmd = modActionsMsgCmd({
try {
contactMethods = readContactMethodsFromArgs(args);
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, e.message);
pluginData.state.common.sendErrorMessage(msg, e.message);
return;
}

View file

@ -3,8 +3,7 @@ import { slashOptions } from "knub";
import { hasPermission } from "../../../../pluginUtils";
import { UserNotificationMethod, resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualKickCmd } from "../../functions/actualCommands/actualKickCmd";
import { actualKickCmd } from "./actualKickCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -51,9 +50,13 @@ export const KickSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}
@ -66,9 +69,10 @@ export const KickSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}
@ -79,7 +83,7 @@ export const KickSlashCmd = modActionsSlashCmd({
try {
contactMethods = readContactMethodsFromArgs(options) ?? undefined;
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, e.message);
pluginData.state.common.sendErrorMessage(interaction, e.message);
return;
}

View file

@ -3,13 +3,12 @@ import { GuildPluginData } from "knub";
import { LogType } from "../../../../data/LogType";
import { canActOn } from "../../../../pluginUtils";
import { DAYS, SECONDS, UnknownUser, UserNotificationMethod, renderUsername, resolveMember } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { IgnoredEventType, ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { ignoreEvent } from "../ignoreEvent";
import { isBanned } from "../isBanned";
import { kickMember } from "../kickMember";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
import { ignoreEvent } from "../../functions/ignoreEvent";
import { isBanned } from "../../functions/isBanned";
import { kickMember } from "../../functions/kickMember";
export async function actualKickCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -31,9 +30,9 @@ export async function actualKickCmd(
if (!memberToKick) {
const banned = await isBanned(pluginData, user.id);
if (banned) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `User is banned`);
pluginData.state.common.sendErrorMessage(context, `User is banned`);
} else {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `User not found on the server`);
pluginData.state.common.sendErrorMessage(context, `User not found on the server`);
}
return;
@ -41,7 +40,7 @@ export async function actualKickCmd(
// Make sure we're allowed to kick this member
if (!canActOn(pluginData, author, memberToKick)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "Cannot kick: insufficient permissions");
pluginData.state.common.sendErrorMessage(context, "Cannot kick: insufficient permissions");
return;
}
@ -63,7 +62,7 @@ export async function actualKickCmd(
try {
await memberToKick.ban({ deleteMessageSeconds: (1 * DAYS) / SECONDS, reason: "kick -clean" });
} catch {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "Failed to ban the user to clean messages (-clean)");
pluginData.state.common.sendErrorMessage(context, "Failed to ban the user to clean messages (-clean)");
}
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, memberToKick.id);
@ -72,14 +71,14 @@ export async function actualKickCmd(
try {
await pluginData.guild.bans.remove(memberToKick.id, "kick -clean");
} catch {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "Failed to unban the user after banning them (-clean)");
pluginData.state.common.sendErrorMessage(
context,
"Failed to unban the user after banning them (-clean)");
}
}
if (kickResult.status === "failed") {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `Failed to kick user`);
pluginData.state.common.sendErrorMessage(context, `Failed to kick user`);
return;
}
@ -87,5 +86,5 @@ export async function actualKickCmd(
let response = `Kicked **${renderUsername(memberToKick.user)}** (Case #${kickResult.case.case_number})`;
if (kickResult.notifyResult.text) response += ` (${kickResult.notifyResult.text})`;
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(context, response);
pluginData.state.common.sendSuccessMessage(context, response);
}

View file

@ -1,8 +1,7 @@
import { waitForReply } from "knub/helpers";
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { getContextChannel, sendContextResponse } from "../../../../pluginUtils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMassBanCmd } from "../../functions/actualCommands/actualMassBanCmd";
import { actualMassBanCmd } from "./actualMassBanCmd";
import { modActionsMsgCmd } from "../../types";
export const MassBanMsgCmd = modActionsMsgCmd({
@ -22,7 +21,7 @@ export const MassBanMsgCmd = modActionsMsgCmd({
const banReasonReply = await waitForReply(pluginData.client, await getContextChannel(msg), msg.author.id);
if (!banReasonReply || !banReasonReply.content || banReasonReply.content.toLowerCase().trim() === "cancel") {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cancelled");
pluginData.state.common.sendErrorMessage(msg, "Cancelled");
return;
}

View file

@ -1,8 +1,7 @@
import { GuildMember } from "discord.js";
import { slashOptions } from "knub";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMassBanCmd } from "../../functions/actualCommands/actualMassBanCmd";
import { actualMassBanCmd } from "./actualMassBanCmd";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -31,9 +30,13 @@ export const MassBanSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}

View file

@ -6,12 +6,11 @@ import { humanizeDurationShort } from "../../../../humanizeDurationShort";
import { canActOn, getContextChannel, isContextInteraction, sendContextResponse } from "../../../../pluginUtils";
import { DAYS, MINUTES, SECONDS, noop } from "../../../../utils";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { IgnoredEventType, ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { ignoreEvent } from "../ignoreEvent";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
import { ignoreEvent } from "../../functions/ignoreEvent";
export async function actualMassBanCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -23,7 +22,7 @@ export async function actualMassBanCmd(
) {
// Limit to 100 users at once (arbitrary?)
if (userIds.length > 100) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `Can only massban max 100 users at once`);
pluginData.state.common.sendErrorMessage(context, `Can only massban max 100 users at once`);
return;
}
@ -38,9 +37,9 @@ export async function actualMassBanCmd(
for (const userId of userIds) {
const member = pluginData.guild.members.cache.get(userId as Snowflake); // TODO: Get members on demand?
if (member && !canActOn(pluginData, author, member)) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "Cannot massban one or more users: insufficient permissions");
pluginData.state.common.sendErrorMessage(
context,
"Cannot massban one or more users: insufficient permissions");
return;
}
}
@ -146,7 +145,7 @@ export async function actualMassBanCmd(
const successfulBanCount = userIds.length - failedBans.length;
if (successfulBanCount === 0) {
// All bans failed - don't create a log entry and notify the user
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "All bans failed. Make sure the IDs are valid.");
pluginData.state.common.sendErrorMessage(context, "All bans failed. Make sure the IDs are valid.");
} else {
// Some or all bans were successful. Create a log entry for the mass ban and notify the user.
pluginData.getPlugin(LogsPlugin).logMassBan({
@ -156,18 +155,17 @@ export async function actualMassBanCmd(
});
if (failedBans.length) {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
context,
`Banned ${successfulBanCount} users in ${formattedTimeTaken}, ${
failedBans.length
} failed: ${failedBans.join(" ")}`,
);
pluginData.state.common.sendSuccessMessage(
context,
`Banned ${successfulBanCount} users in ${formattedTimeTaken}, ${
failedBans.length
} failed: ${failedBans.join(" ")}`,
);
} else {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(context, `Banned ${successfulBanCount} users successfully in ${formattedTimeTaken}`);
pluginData.state.common.sendSuccessMessage(
context,
`Banned ${successfulBanCount} users successfully in ${formattedTimeTaken}`
);
}
}
});

View file

@ -1,8 +1,7 @@
import { waitForReply } from "knub/helpers";
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { getContextChannel, sendContextResponse } from "../../../../pluginUtils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMassMuteCmd } from "../../functions/actualCommands/actualMassMuteCmd";
import { actualMassMuteCmd } from "./actualMassMuteCmd";
import { modActionsMsgCmd } from "../../types";
export const MassMuteMsgCmd = modActionsMsgCmd({
@ -25,7 +24,7 @@ export const MassMuteMsgCmd = modActionsMsgCmd({
!muteReasonReceived.content ||
muteReasonReceived.content.toLowerCase().trim() === "cancel"
) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cancelled");
pluginData.state.common.sendErrorMessage(msg, "Cancelled");
return;
}

View file

@ -1,8 +1,7 @@
import { GuildMember } from "discord.js";
import { slashOptions } from "knub";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMassMuteCmd } from "../../functions/actualCommands/actualMassMuteCmd";
import { actualMassMuteCmd } from "./actualMassMuteCmd";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -31,9 +30,13 @@ export const MassMuteSlashSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}

View file

@ -3,12 +3,11 @@ import { GuildPluginData } from "knub";
import { LogType } from "../../../../data/LogType";
import { logger } from "../../../../logger";
import { canActOn, isContextInteraction, sendContextResponse } from "../../../../pluginUtils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { MutesPlugin } from "../../../Mutes/MutesPlugin";
import { ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
export async function actualMassMuteCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -20,7 +19,7 @@ export async function actualMassMuteCmd(
) {
// Limit to 100 users at once (arbitrary?)
if (userIds.length > 100) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `Can only massmute max 100 users at once`);
pluginData.state.common.sendErrorMessage(context, `Can only massmute max 100 users at once`);
return;
}
@ -35,9 +34,10 @@ export async function actualMassMuteCmd(
for (const userId of userIds) {
const member = pluginData.guild.members.cache.get(userId as Snowflake);
if (member && !canActOn(pluginData, author, member)) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "Cannot massmute one or more users: insufficient permissions");
pluginData.state.common.sendErrorMessage(
context,
"Cannot massmute one or more users: insufficient permissions"
);
return;
}
}
@ -77,7 +77,7 @@ export async function actualMassMuteCmd(
const successfulMuteCount = userIds.length - failedMutes.length;
if (successfulMuteCount === 0) {
// All mutes failed
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "All mutes failed. Make sure the IDs are valid.");
pluginData.state.common.sendErrorMessage(context, "All mutes failed. Make sure the IDs are valid.");
} else {
// Success on all or some mutes
pluginData.getPlugin(LogsPlugin).logMassMute({
@ -86,14 +86,12 @@ export async function actualMassMuteCmd(
});
if (failedMutes.length) {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
pluginData.state.common.sendSuccessMessage(
context,
`Muted ${successfulMuteCount} users, ${failedMutes.length} failed: ${failedMutes.join(" ")}`,
);
} else {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(context, `Muted ${successfulMuteCount} users successfully`);
pluginData.state.common.sendSuccessMessage(context, `Muted ${successfulMuteCount} users successfully`);
}
}
}

View file

@ -1,8 +1,7 @@
import { waitForReply } from "knub/helpers";
import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { getContextChannel, sendContextResponse } from "../../../../pluginUtils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMassUnbanCmd } from "../../functions/actualCommands/actualMassUnbanCmd";
import { actualMassUnbanCmd } from "./actualMassUnbanCmd";
import { modActionsMsgCmd } from "../../types";
export const MassUnbanMsgCmd = modActionsMsgCmd({
@ -21,7 +20,7 @@ export const MassUnbanMsgCmd = modActionsMsgCmd({
sendContextResponse(msg, "Unban reason? `cancel` to cancel");
const unbanReasonReply = await waitForReply(pluginData.client, await getContextChannel(msg), msg.author.id);
if (!unbanReasonReply || !unbanReasonReply.content || unbanReasonReply.content.toLowerCase().trim() === "cancel") {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cancelled");
pluginData.state.common.sendErrorMessage(msg, "Cancelled");
return;
}

View file

@ -1,8 +1,7 @@
import { GuildMember } from "discord.js";
import { slashOptions } from "knub";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMassUnbanCmd } from "../../functions/actualCommands/actualMassUnbanCmd";
import { actualMassUnbanCmd } from "./actualMassUnbanCmd";
import { modActionsSlashCmd } from "../../types";
import { NUMBER_ATTACHMENTS_CASE_CREATION } from "../constants";
@ -31,9 +30,13 @@ export const MassUnbanSlashCmd = modActionsSlashCmd({
const attachments = retrieveMultipleOptions(NUMBER_ATTACHMENTS_CASE_CREATION, options, "attachment");
if ((!options.reason || options.reason.trim() === "") && attachments.length < 1) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "Text or attachment required", undefined, undefined, true);
pluginData.state.common.sendErrorMessage(
interaction,
"Text or attachment required",
undefined,
undefined,
true
);
return;
}

View file

@ -5,13 +5,12 @@ import { LogType } from "../../../../data/LogType";
import { isContextInteraction, sendContextResponse } from "../../../../pluginUtils";
import { MINUTES, noop } from "../../../../utils";
import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { IgnoredEventType, ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { ignoreEvent } from "../ignoreEvent";
import { isBanned } from "../isBanned";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
import { ignoreEvent } from "../../functions/ignoreEvent";
import { isBanned } from "../../functions/isBanned";
export async function actualMassUnbanCmd(
pluginData: GuildPluginData<ModActionsPluginType>,
@ -23,7 +22,7 @@ export async function actualMassUnbanCmd(
) {
// Limit to 100 users at once (arbitrary?)
if (userIds.length > 100) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, `Can only mass-unban max 100 users at once`);
pluginData.state.common.sendErrorMessage(context, `Can only mass-unban max 100 users at once`);
return;
}
@ -76,9 +75,10 @@ export async function actualMassUnbanCmd(
const successfulUnbanCount = userIds.length - failedUnbans.length;
if (successfulUnbanCount === 0) {
// All unbans failed - don't create a log entry and notify the user
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "All unbans failed. Make sure the IDs are valid and banned.");
pluginData.state.common.sendErrorMessage(
context,
"All unbans failed. Make sure the IDs are valid and banned."
);
} else {
// Some or all unbans were successful. Create a log entry for the mass unban and notify the user.
pluginData.getPlugin(LogsPlugin).logMassUnban({
@ -105,16 +105,12 @@ export async function actualMassUnbanCmd(
});
}
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(
pluginData.state.common.sendSuccessMessage(
context,
`Unbanned ${successfulUnbanCount} users, ${failedUnbans.length} failed:\n${failedMsg}`,
);
} else {
pluginData
.getPlugin(CommonPlugin)
.sendSuccessMessage(context, `Unbanned ${successfulUnbanCount} users successfully`);
pluginData.state.common.sendSuccessMessage(context, `Unbanned ${successfulUnbanCount} users successfully`);
}
}
}

View file

@ -2,8 +2,7 @@ import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { canActOn, hasPermission } from "../../../../pluginUtils";
import { resolveMember, resolveUser } from "../../../../utils";
import { waitForButtonConfirm } from "../../../../utils/waitForInteraction";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMuteCmd } from "../../functions/actualCommands/actualMuteCmd";
import { actualMuteCmd } from "./actualMuteCmd";
import { isBanned } from "../../functions/isBanned";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsMsgCmd } from "../../types";
@ -38,7 +37,7 @@ export const MuteMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user);
if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`);
pluginData.state.common.sendErrorMessage(msg, `User not found`);
return;
}
@ -48,9 +47,10 @@ export const MuteMsgCmd = modActionsMsgCmd({
const _isBanned = await isBanned(pluginData, user.id);
const prefix = pluginData.fullConfig.prefix;
if (_isBanned) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `User is banned. Use \`${prefix}forcemute\` if you want to mute them anyway.`);
pluginData.state.common.sendErrorMessage(
msg,
`User is banned. Use \`${prefix}forcemute\` if you want to mute them anyway.`
);
return;
} else {
// Ask the mod if we should upgrade to a forcemute as the user is not on the server
@ -61,7 +61,7 @@ export const MuteMsgCmd = modActionsMsgCmd({
);
if (!reply) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "User not on server, mute cancelled by moderator");
pluginData.state.common.sendErrorMessage(msg, "User not on server, mute cancelled by moderator");
return;
}
}
@ -69,7 +69,7 @@ export const MuteMsgCmd = modActionsMsgCmd({
// Make sure we're allowed to mute this member
if (memberToMute && !canActOn(pluginData, msg.member, memberToMute)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cannot mute: insufficient permissions");
pluginData.state.common.sendErrorMessage(msg, "Cannot mute: insufficient permissions");
return;
}
@ -79,7 +79,7 @@ export const MuteMsgCmd = modActionsMsgCmd({
if (args.mod) {
if (!(await hasPermission(pluginData, "can_act_as_other", { message: msg }))) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "You don't have permission to use -mod");
pluginData.state.common.sendErrorMessage(msg, "You don't have permission to use -mod");
return;
}
@ -91,7 +91,7 @@ export const MuteMsgCmd = modActionsMsgCmd({
try {
contactMethods = readContactMethodsFromArgs(args);
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, e.message);
pluginData.state.common.sendErrorMessage(msg, e.message);
return;
}

View file

@ -4,8 +4,7 @@ import { canActOn, hasPermission } from "../../../../pluginUtils";
import { UserNotificationMethod, convertDelayStringToMS, resolveMember } from "../../../../utils";
import { generateAttachmentSlashOptions, retrieveMultipleOptions } from "../../../../utils/multipleSlashOptions";
import { waitForButtonConfirm } from "../../../../utils/waitForInteraction";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { actualMuteCmd } from "../../functions/actualCommands/actualMuteCmd";
import { actualMuteCmd } from "./actualMuteCmd";
import { isBanned } from "../../functions/isBanned";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsSlashCmd } from "../../types";
@ -53,9 +52,10 @@ export const MuteSlashCmd = modActionsSlashCmd({
const _isBanned = await isBanned(pluginData, options.user.id);
const prefix = pluginData.fullConfig.prefix;
if (_isBanned) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, `User is banned. Use \`${prefix}forcemute\` if you want to mute them anyway.`);
pluginData.state.common.sendErrorMessage(
interaction,
`User is banned. Use \`${prefix}forcemute\` if you want to mute them anyway.`
);
return;
} else {
// Ask the mod if we should upgrade to a forcemute as the user is not on the server
@ -66,9 +66,10 @@ export const MuteSlashCmd = modActionsSlashCmd({
);
if (!reply) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "User not on server, mute cancelled by moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"User not on server, mute cancelled by moderator"
);
return;
}
}
@ -76,7 +77,7 @@ export const MuteSlashCmd = modActionsSlashCmd({
// Make sure we're allowed to mute this member
if (memberToMute && !canActOn(pluginData, interaction.member as GuildMember, memberToMute)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, "Cannot mute: insufficient permissions");
pluginData.state.common.sendErrorMessage(interaction, "Cannot mute: insufficient permissions");
return;
}
@ -89,9 +90,10 @@ export const MuteSlashCmd = modActionsSlashCmd({
if (options.mod) {
if (!canActAsOther) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(interaction, "You don't have permission to act as another moderator");
pluginData.state.common.sendErrorMessage(
interaction,
"You don't have permission to act as another moderator"
);
return;
}
@ -101,7 +103,7 @@ export const MuteSlashCmd = modActionsSlashCmd({
const convertedTime = options.time ? convertDelayStringToMS(options.time) ?? undefined : undefined;
if (options.time && !convertedTime) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
pluginData.state.common.sendErrorMessage(interaction, `Could not convert ${options.time} to a delay`);
return;
}
@ -109,7 +111,7 @@ export const MuteSlashCmd = modActionsSlashCmd({
try {
contactMethods = readContactMethodsFromArgs(options) ?? undefined;
} catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(interaction, e.message);
pluginData.state.common.sendErrorMessage(interaction, e.message);
return;
}

View file

@ -10,12 +10,11 @@ import {
isDiscordAPIError,
renderUsername,
} from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { MutesPlugin } from "../../../Mutes/MutesPlugin";
import { MuteResult } from "../../../Mutes/types";
import { ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
/**
* The actual function run by both !mute and !forcemute.
@ -57,11 +56,12 @@ export async function actualMuteCmd(
});
} catch (e) {
if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) {
pluginData
.getPlugin(CommonPlugin)
.sendErrorMessage(context, "Could not mute the user: no mute role set in config");
pluginData.state.common.sendErrorMessage(
context,
"Could not mute the user: no mute role set in config"
);
} else if (isDiscordAPIError(e) && e.code === 10007) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "Could not mute the user: unknown member");
pluginData.state.common.sendErrorMessage(context, "Could not mute the user: unknown member");
} else {
logger.error(`Failed to mute user ${user.id}: ${e.stack}`);
if (user.id == null) {
@ -69,7 +69,7 @@ export async function actualMuteCmd(
// tslint:disable-next-line:no-console
console.trace("[DEBUG] Null user.id for mute");
}
pluginData.getPlugin(CommonPlugin).sendErrorMessage(context, "Could not mute the user");
pluginData.state.common.sendErrorMessage(context, "Could not mute the user");
}
return;
@ -104,5 +104,5 @@ export async function actualMuteCmd(
}
if (muteResult.notifyResult.text) response += ` (${muteResult.notifyResult.text})`;
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(context, response);
pluginData.state.common.sendSuccessMessage(context, response);
}

Some files were not shown because too many files have changed in this diff Show more