3
0
Fork 0
mirror of https://github.com/ZeppelinBot/Zeppelin.git synced 2025-03-18 06:51: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(); const rootRouter = express.Router();
initAuth(app); initAuth(rootRouter);
initGuildsAPI(app); initGuildsAPI(rootRouter);
initArchives(app); initArchives(rootRouter);
initDocs(app); initDocs(rootRouter);
// Default route // Default route
rootRouter.get("/", (req, res) => { rootRouter.get("/", (req, res) => {

View file

@ -6,6 +6,7 @@ import { DisableAutoReactionsCmd } from "./commands/DisableAutoReactionsCmd";
import { NewAutoReactionsCmd } from "./commands/NewAutoReactionsCmd"; import { NewAutoReactionsCmd } from "./commands/NewAutoReactionsCmd";
import { AddReactionsEvt } from "./events/AddReactionsEvt"; import { AddReactionsEvt } from "./events/AddReactionsEvt";
import { AutoReactionsPluginType, zAutoReactionsConfig } from "./types"; import { AutoReactionsPluginType, zAutoReactionsConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions: PluginOptions<AutoReactionsPluginType> = { const defaultOptions: PluginOptions<AutoReactionsPluginType> = {
config: { config: {
@ -50,4 +51,8 @@ export const AutoReactionsPlugin = guildPlugin<AutoReactionsPluginType>()({
state.autoReactions = GuildAutoReactions.getGuildInstance(guild.id); state.autoReactions = GuildAutoReactions.getGuildInstance(guild.id);
state.cache = new Map(); 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 }) { async run({ message: msg, args, pluginData }) {
const autoReaction = await pluginData.state.autoReactions.getForChannel(args.channelId); const autoReaction = await pluginData.state.autoReactions.getForChannel(args.channelId);
if (!autoReaction) { 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; return;
} }
await pluginData.state.autoReactions.removeFromChannel(args.channelId); await pluginData.state.autoReactions.removeFromChannel(args.channelId);
pluginData.state.cache.delete(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,9 +25,7 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
const me = pluginData.guild.members.cache.get(pluginData.client.user!.id)!; const me = pluginData.guild.members.cache.get(pluginData.client.user!.id)!;
const missingPermissions = getMissingChannelPermissions(me, args.channel, requiredPermissions); const missingPermissions = getMissingChannelPermissions(me, args.channel, requiredPermissions);
if (missingPermissions) { if (missingPermissions) {
pluginData pluginData.state.common.sendErrorMessage(
.getPlugin(CommonPlugin)
.sendErrorMessage(
msg, msg,
`Cannot set auto-reactions for that channel. ${missingPermissionError(missingPermissions)}`, `Cannot set auto-reactions for that channel. ${missingPermissionError(missingPermissions)}`,
); );
@ -36,9 +34,7 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
for (const reaction of args.reactions) { for (const reaction of args.reactions) {
if (!isEmoji(reaction)) { if (!isEmoji(reaction)) {
pluginData void pluginData.state.common.sendErrorMessage(msg, "One or more of the specified reactions were invalid!");
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, "One or more of the specified reactions were invalid!");
return; return;
} }
@ -48,9 +44,7 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
if (customEmojiMatch) { if (customEmojiMatch) {
// Custom emoji // Custom emoji
if (!canUseEmoji(pluginData.client, customEmojiMatch[2])) { if (!canUseEmoji(pluginData.client, customEmojiMatch[2])) {
pluginData pluginData.state.common.sendErrorMessage(msg, "I can only use regular emojis and custom emojis from this server");
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, "I can only use regular emojis and custom emojis from this server");
return; return;
} }
@ -65,6 +59,6 @@ export const NewAutoReactionsCmd = autoReactionsCmd({
await pluginData.state.autoReactions.set(args.channel.id, finalReactions); await pluginData.state.autoReactions.set(args.channel.id, finalReactions);
pluginData.state.cache.delete(args.channel.id); 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 z from "zod";
import { GuildAutoReactions } from "../../data/GuildAutoReactions"; import { GuildAutoReactions } from "../../data/GuildAutoReactions";
import { GuildLogs } from "../../data/GuildLogs"; import { GuildLogs } from "../../data/GuildLogs";
import { GuildSavedMessages } from "../../data/GuildSavedMessages"; import { GuildSavedMessages } from "../../data/GuildSavedMessages";
import { AutoReaction } from "../../data/entities/AutoReaction"; import { AutoReaction } from "../../data/entities/AutoReaction";
import { CommonPlugin } from "../Common/CommonPlugin";
export const zAutoReactionsConfig = z.strictObject({ export const zAutoReactionsConfig = z.strictObject({
can_manage: z.boolean(), can_manage: z.boolean(),
@ -16,6 +17,7 @@ export interface AutoReactionsPluginType extends BasePluginType {
savedMessages: GuildSavedMessages; savedMessages: GuildSavedMessages;
autoReactions: GuildAutoReactions; autoReactions: GuildAutoReactions;
cache: Map<string, AutoReaction | null>; 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 { clearOldRecentActions } from "./functions/clearOldRecentActions";
import { clearOldRecentSpam } from "./functions/clearOldRecentSpam"; import { clearOldRecentSpam } from "./functions/clearOldRecentSpam";
import { AutomodPluginType, zAutomodConfig } from "./types"; import { AutomodPluginType, zAutomodConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions = { const defaultOptions = {
config: { config: {
@ -117,6 +118,10 @@ export const AutomodPlugin = guildPlugin<AutomodPluginType>()({
state.cachedAntiraidLevel = await state.antiraidLevels.get(); state.cachedAntiraidLevel = await state.antiraidLevels.get();
}, },
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
async afterLoad(pluginData) { async afterLoad(pluginData) {
const { state } = pluginData; const { state } = pluginData;

View file

@ -1,5 +1,4 @@
import { guildPluginMessageCommand } from "knub"; import { guildPluginMessageCommand } from "knub";
import { CommonPlugin } from "../../Common/CommonPlugin";
import { setAntiraidLevel } from "../functions/setAntiraidLevel"; import { setAntiraidLevel } from "../functions/setAntiraidLevel";
import { AutomodPluginType } from "../types"; import { AutomodPluginType } from "../types";
@ -9,6 +8,6 @@ export const AntiraidClearCmd = guildPluginMessageCommand<AutomodPluginType>()({
async run({ pluginData, message }) { async run({ pluginData, message }) {
await setAntiraidLevel(pluginData, null, message.author); 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 { guildPluginMessageCommand } from "knub";
import { commandTypeHelpers as ct } from "../../../commandTypes"; import { commandTypeHelpers as ct } from "../../../commandTypes";
import { CommonPlugin } from "../../Common/CommonPlugin";
import { setAntiraidLevel } from "../functions/setAntiraidLevel"; import { setAntiraidLevel } from "../functions/setAntiraidLevel";
import { AutomodPluginType } from "../types"; import { AutomodPluginType } from "../types";
@ -15,11 +14,11 @@ export const SetAntiraidCmd = guildPluginMessageCommand<AutomodPluginType>()({
async run({ pluginData, message, args }) { async run({ pluginData, message, args }) {
const config = pluginData.config.get(); const config = pluginData.config.get();
if (!config.antiraid_levels.includes(args.level)) { 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; return;
} }
await setAntiraidLevel(pluginData, args.level, message.author); 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 { GuildMember, GuildTextBasedChannel, PartialGuildMember, ThreadChannel, User } from "discord.js";
import { BasePluginType, CooldownManager } from "knub"; import { BasePluginType, CooldownManager, pluginUtils } from "knub";
import z from "zod"; import z from "zod";
import { Queue } from "../../Queue"; import { Queue } from "../../Queue";
import { RegExpRunner } from "../../RegExpRunner"; import { RegExpRunner } from "../../RegExpRunner";
@ -17,6 +17,7 @@ import { RecentActionType } from "./constants";
import { availableTriggers } from "./triggers/availableTriggers"; import { availableTriggers } from "./triggers/availableTriggers";
import Timeout = NodeJS.Timeout; import Timeout = NodeJS.Timeout;
import { CommonPlugin } from "../Common/CommonPlugin";
export type ZTriggersMapHelper = { export type ZTriggersMapHelper = {
[TriggerName in keyof typeof availableTriggers]: (typeof availableTriggers)[TriggerName]["configSchema"]; [TriggerName in keyof typeof availableTriggers]: (typeof availableTriggers)[TriggerName]["configSchema"];
@ -139,6 +140,8 @@ export interface AutomodPluginType extends BasePluginType {
modActionsListeners: Map<keyof ModActionsEvents, any>; modActionsListeners: Map<keyof ModActionsEvents, any>;
mutesListeners: Map<keyof MutesEvents, 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 { ApiPermissionAssignments } from "../../data/ApiPermissionAssignments";
import { Configs } from "../../data/Configs"; import { Configs } from "../../data/Configs";
import { GuildArchives } from "../../data/GuildArchives"; import { GuildArchives } from "../../data/GuildArchives";
import { CommonPlugin } from "../Common/CommonPlugin";
import { getActiveReload, resetActiveReload } from "./activeReload"; import { getActiveReload, resetActiveReload } from "./activeReload";
import { AddDashboardUserCmd } from "./commands/AddDashboardUserCmd"; import { AddDashboardUserCmd } from "./commands/AddDashboardUserCmd";
import { AddServerFromInviteCmd } from "./commands/AddServerFromInviteCmd"; import { AddServerFromInviteCmd } from "./commands/AddServerFromInviteCmd";
@ -77,7 +76,7 @@ export const BotControlPlugin = globalPlugin<BotControlPluginType>()({
if (guild) { if (guild) {
const channel = guild.channels.cache.get(channelId as Snowflake); const channel = guild.channels.cache.get(channelId as Snowflake);
if (channel instanceof TextChannel) { 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 }) { async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId); const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) { if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin"); void msg.channel.send("Server is not using Zeppelin");
return; return;
} }
@ -38,11 +38,6 @@ export const AddDashboardUserCmd = botControlCmd({
const userNameList = args.users.map((user) => `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`)`); const userNameList = args.users.map((user) => `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`)`);
pluginData msg.channel.send(`The following users were given dashboard access for **${guild.name}**:\n\n${userNameList}`);
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg,
`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 }) { async run({ pluginData, message: msg, args }) {
const invite = await resolveInvite(pluginData.client, args.inviteCode, true); const invite = await resolveInvite(pluginData.client, args.inviteCode, true);
if (!invite || !isGuildInvite(invite)) { if (!invite || !isGuildInvite(invite)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Could not resolve invite"); // :D void msg.channel.send("Could not resolve invite"); // :D
return; return;
} }
const existing = await pluginData.state.allowedGuilds.find(invite.guild.id); const existing = await pluginData.state.allowedGuilds.find(invite.guild.id);
if (existing) { if (existing) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is already allowed!"); void msg.channel.send("Server is already allowed!");
return; return;
} }
const { result, explanation } = await isEligible(pluginData, args.user, invite); const { result, explanation } = await isEligible(pluginData, args.user, invite);
if (!result) { if (!result) {
pluginData msg.channel.send(`Could not add server because it's not eligible: ${explanation}`);
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `Could not add server because it's not eligible: ${explanation}`);
return; return;
} }
@ -53,8 +51,6 @@ export const AddServerFromInviteCmd = botControlCmd({
); );
} }
pluginData msg.channel.send("Server was eligible and is now allowed to use Zeppelin!");
.getPlugin(CommonPlugin)
.sendSuccessMessage(msg, "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 }) { async run({ pluginData, message: msg, args }) {
const existing = await pluginData.state.allowedGuilds.find(args.guildId); const existing = await pluginData.state.allowedGuilds.find(args.guildId);
if (existing) { if (existing) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is already allowed!"); void msg.channel.send("Server is already allowed!");
return; return;
} }
if (!isSnowflake(args.guildId)) { if (!isSnowflake(args.guildId)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Invalid server ID!"); void msg.channel.send("Invalid server ID!");
return; return;
} }
if (args.userId && !isSnowflake(args.userId)) { if (args.userId && !isSnowflake(args.userId)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Invalid user ID!"); void msg.channel.send("Invalid user ID!");
return; 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 }) { async run({ pluginData, message: msg, args }) {
const channel = pluginData.client.channels.cache.get(args.channelId); const channel = pluginData.client.channels.cache.get(args.channelId);
if (!channel) { if (!channel) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Channel not found in cache!"); void msg.channel.send("Channel not found in cache!");
return; return;
} }

View file

@ -19,7 +19,7 @@ export const DisallowServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) { async run({ pluginData, message: msg, args }) {
const existing = await pluginData.state.allowedGuilds.find(args.guildId); const existing = await pluginData.state.allowedGuilds.find(args.guildId);
if (!existing) { 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; return;
} }
@ -28,6 +28,6 @@ export const DisallowServerCmd = botControlCmd({
.get(args.guildId as Snowflake) .get(args.guildId as Snowflake)
?.leave() ?.leave()
.catch(noop); .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 }) { async run({ pluginData, message: msg, args }) {
const invite = await resolveInvite(pluginData.client, args.inviteCode, true); const invite = await resolveInvite(pluginData.client, args.inviteCode, true);
if (!invite || !isGuildInvite(invite)) { if (!invite || !isGuildInvite(invite)) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Could not resolve invite"); void msg.channel.send("Could not resolve invite");
return; return;
} }
const { result, explanation } = await isEligible(pluginData, args.user, invite); const { result, explanation } = await isEligible(pluginData, args.user, invite);
if (result) { if (result) {
pluginData.getPlugin(CommonPlugin).sendSuccessMessage(msg, `Server is eligible: ${explanation}`); void msg.channel.send(`Server is eligible: ${explanation}`);
return; 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 }) { async run({ pluginData, message: msg, args }) {
if (!pluginData.client.guilds.cache.has(args.guildId as Snowflake)) { 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; return;
} }
@ -27,10 +27,10 @@ export const LeaveServerCmd = botControlCmd({
try { try {
await pluginData.client.guilds.cache.get(args.guildId as Snowflake)?.leave(); await pluginData.client.guilds.cache.get(args.guildId as Snowflake)?.leave();
} catch (e) { } catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `Failed to leave guild: ${e.message}`); void msg.channel.send(`Failed to leave guild: ${e.message}`);
return; 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 }) { async run({ pluginData, message: msg, args }) {
if (!args.user && !args.guildId) { 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; return;
} }
@ -24,7 +24,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (args.guildId) { if (args.guildId) {
guild = await pluginData.state.allowedGuilds.find(args.guildId); guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) { if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin"); void msg.channel.send("Server is not using Zeppelin");
return; return;
} }
} }
@ -33,7 +33,7 @@ export const ListDashboardPermsCmd = botControlCmd({
if (args.user) { if (args.user) {
existingUserAssignment = await pluginData.state.apiPermissionAssignments.getByUserId(args.user.id); existingUserAssignment = await pluginData.state.apiPermissionAssignments.getByUserId(args.user.id);
if (existingUserAssignment.length === 0) { 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; return;
} }
} }
@ -54,9 +54,7 @@ export const ListDashboardPermsCmd = botControlCmd({
} }
if (finalMessage === "") { if (finalMessage === "") {
pluginData msg.channel.send(`The user ${userInfo} has no assigned permissions on the specified server.`);
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `The user ${userInfo} has no assigned permissions on the specified server.`);
return; return;
} }
// Else display all users that have permissions on the specified guild // 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); const existingGuildAssignment = await pluginData.state.apiPermissionAssignments.getByGuildId(guild.id);
if (existingGuildAssignment.length === 0) { if (existingGuildAssignment.length === 0) {
pluginData msg.channel.send(`The server ${guildInfo} has no assigned permissions.`);
.getPlugin(CommonPlugin)
.sendErrorMessage(msg, `The server ${guildInfo} has no assigned permissions.`);
return; 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 }) { async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId); const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) { if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin"); void msg.channel.send("Server is not using Zeppelin");
return; return;
} }
@ -30,12 +30,9 @@ export const ListDashboardUsersCmd = botControlCmd({
`<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`): ${permission.permissions.join(", ")}`, `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`): ${permission.permissions.join(", ")}`,
); );
pluginData msg.channel.send({
.getPlugin(CommonPlugin) content: `The following users have dashboard access for **${guild.name}**:\n\n${userNameList.join("\n")}`,
.sendSuccessMessage( allowedMentions: {},
msg, });
`The following users have dashboard access for **${guild.name}**:\n\n${userNameList.join("\n")}`,
{},
);
}, },
}); });

View file

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

View file

@ -15,7 +15,7 @@ export const ReloadGlobalPluginsCmd = botControlCmd({
const guildId = "guild" in message.channel ? message.channel.guild.id : null; const guildId = "guild" in message.channel ? message.channel.guild.id : null;
if (!guildId) { 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; return;
} }

View file

@ -17,18 +17,18 @@ export const ReloadServerCmd = botControlCmd({
async run({ pluginData, message: msg, args }) { async run({ pluginData, message: msg, args }) {
if (!pluginData.client.guilds.cache.has(args.guildId as Snowflake)) { 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; return;
} }
try { try {
await pluginData.getKnubInstance().reloadGuild(args.guildId); await pluginData.getKnubInstance().reloadGuild(args.guildId);
} catch (e) { } catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `Failed to reload guild: ${e.message}`); void msg.channel.send(`Failed to reload guild: ${e.message}`);
return; return;
} }
const guild = await pluginData.client.guilds.fetch(args.guildId as Snowflake); 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 }) { async run({ pluginData, message: msg, args }) {
const guild = await pluginData.state.allowedGuilds.find(args.guildId); const guild = await pluginData.state.allowedGuilds.find(args.guildId);
if (!guild) { if (!guild) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Server is not using Zeppelin"); void msg.channel.send("Server is not using Zeppelin");
return; return;
} }
@ -37,10 +37,7 @@ export const RemoveDashboardUserCmd = botControlCmd({
const userNameList = args.users.map((user) => `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`)`); const userNameList = args.users.map((user) => `<@!${user.id}> (**${renderUsername(user)}**, \`${user.id}\`)`);
pluginData msg.channel.send(
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg,
`The following users were removed from the dashboard for **${guild.name}**:\n\n${userNameList}`, `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 z from "zod";
import { AllowedGuilds } from "../../data/AllowedGuilds"; import { AllowedGuilds } from "../../data/AllowedGuilds";
import { ApiPermissionAssignments } from "../../data/ApiPermissionAssignments"; import { ApiPermissionAssignments } from "../../data/ApiPermissionAssignments";

View file

@ -3,6 +3,7 @@ import z from "zod";
import { TimeAndDatePlugin } from "../TimeAndDate/TimeAndDatePlugin"; import { TimeAndDatePlugin } from "../TimeAndDate/TimeAndDatePlugin";
import { ArchiveChannelCmd } from "./commands/ArchiveChannelCmd"; import { ArchiveChannelCmd } from "./commands/ArchiveChannelCmd";
import { ChannelArchiverPluginType } from "./types"; import { ChannelArchiverPluginType } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
export const ChannelArchiverPlugin = guildPlugin<ChannelArchiverPluginType>()({ export const ChannelArchiverPlugin = guildPlugin<ChannelArchiverPluginType>()({
name: "channel_archiver", name: "channel_archiver",
@ -14,4 +15,8 @@ export const ChannelArchiverPlugin = guildPlugin<ChannelArchiverPluginType>()({
messageCommands: [ messageCommands: [
ArchiveChannelCmd, 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.", "No `-attachment-channel` specified. Continue? Attachments will not be available in the log if their message is deleted.",
}); });
if (!confirmed) { if (!confirmed) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Canceled"); void pluginData.state.common.sendErrorMessage(msg, "Canceled");
return; 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>(); export const channelArchiverCmd = guildPluginMessageCommand<ChannelArchiverPluginType>();

View file

@ -1,4 +1,5 @@
import { import {
Attachment,
ChatInputCommandInteraction, ChatInputCommandInteraction,
Message, Message,
MessageCreateOptions, MessageCreateOptions,
@ -7,11 +8,10 @@ import {
TextBasedChannel, TextBasedChannel,
User, User,
} from "discord.js"; } from "discord.js";
import { PluginOptions } from "knub"; import { PluginOptions, guildPlugin } from "knub";
import { logger } from "../../logger"; import { logger } from "../../logger";
import { isContextInteraction, sendContextResponse } from "../../pluginUtils"; import { isContextInteraction, sendContextResponse } from "../../pluginUtils";
import { errorMessage, successMessage } from "../../utils"; import { errorMessage, successMessage } from "../../utils";
import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint";
import { getErrorEmoji, getSuccessEmoji } from "./functions/getEmoji"; import { getErrorEmoji, getSuccessEmoji } from "./functions/getEmoji";
import { CommonPluginType, zCommonConfig } from "./types"; import { CommonPluginType, zCommonConfig } from "./types";
@ -19,30 +19,21 @@ const defaultOptions: PluginOptions<CommonPluginType> = {
config: { config: {
success_emoji: "✅", success_emoji: "✅",
error_emoji: "❌", error_emoji: "❌",
attachment_storing_channel: null,
}, },
}; };
export const CommonPlugin = zeppelinGuildPlugin<CommonPluginType>()({ export const CommonPlugin = guildPlugin<CommonPluginType>()({
name: "common", name: "common",
showInDocs: false,
info: {
prettyName: "Common",
},
dependencies: () => [], dependencies: () => [],
configParser: (input) => zCommonConfig.parse(input), configParser: (input) => zCommonConfig.parse(input),
defaultOptions, defaultOptions,
public: { public(pluginData) {
getSuccessEmoji(pluginData) { return {
return () => getSuccessEmoji(pluginData); getSuccessEmoji,
}, getErrorEmoji,
getErrorEmoji(pluginData) { sendSuccessMessage: async (
return () => getErrorEmoji(pluginData);
},
sendSuccessMessage(pluginData) {
return async (
context: TextBasedChannel | Message | User | ChatInputCommandInteraction, context: TextBasedChannel | Message | User | ChatInputCommandInteraction,
body: string, body: string,
allowedMentions?: MessageMentionOptions, allowedMentions?: MessageMentionOptions,
@ -89,11 +80,9 @@ export const CommonPlugin = zeppelinGuildPlugin<CommonPluginType>()({
return undefined; return undefined;
}) as Promise<Message>; }) as Promise<Message>;
};
}, },
sendErrorMessage(pluginData) { sendErrorMessage: async (
return async (
context: TextBasedChannel | Message | User | ChatInputCommandInteraction, context: TextBasedChannel | Message | User | ChatInputCommandInteraction,
body: string, body: string,
allowedMentions?: MessageMentionOptions, allowedMentions?: MessageMentionOptions,
@ -140,7 +129,25 @@ export const CommonPlugin = zeppelinGuildPlugin<CommonPluginType>()({
return undefined; return undefined;
}) as Promise<Message>; }) 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({ export const zCommonConfig = z.strictObject({
success_emoji: z.string(), success_emoji: z.string(),
error_emoji: z.string(), error_emoji: z.string(),
attachment_storing_channel: z.nullable(z.string()),
}); });
export interface CommonPluginType extends BasePluginType { export interface CommonPluginType extends BasePluginType {

View file

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

View file

@ -39,25 +39,21 @@ async function muteAction(
const modactions = pluginData.getPlugin(ModActionsPlugin); const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasMutePermission(executingMember, interaction.channelId))) { if (!userCfg.can_use || !(await modactions.hasMutePermission(executingMember, interaction.channelId))) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Cannot mute: insufficient permissions", content: "Cannot mute: insufficient permissions",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
return; return;
} }
const targetMember = await pluginData.guild.members.fetch(target); const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) { if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Cannot mute: insufficient permissions", content: "Cannot mute: insufficient permissions",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
return; return;
} }
@ -78,17 +74,13 @@ async function muteAction(
await updateAction(pluginData, executingMember, result.case!, evidence); await updateAction(pluginData, executingMember, result.case!, evidence);
} }
await interactionToReply await interactionToReply.editReply({ content: muteMessage, embeds: [], components: [] });
.editReply({ content: muteMessage, embeds: [], components: [] })
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
} catch (e) { } catch (e) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Plugin error, please check your BOT_ALERTs", content: "Plugin error, please check your BOT_ALERTs",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Mute interaction reply failed: ${err}`));
if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) { if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) {
pluginData.getPlugin(LogsPlugin).logBotAlert({ pluginData.getPlugin(LogsPlugin).logBotAlert({
@ -134,9 +126,7 @@ export async function launchMuteActionModal(
if (interaction.isButton()) { if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Mute interaction defer failed: ${err}`)); await submitted.deferUpdate().catch((err) => logger.error(`Mute interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) { } else if (interaction.isContextMenuCommand()) {
await submitted await submitted.deferReply({ ephemeral: true });
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Mute interaction defer failed: ${err}`));
} }
const duration = submitted.fields.getTextInputValue("duration"); const duration = submitted.fields.getTextInputValue("duration");
@ -144,6 +134,5 @@ export async function launchMuteActionModal(
const evidence = submitted.fields.getTextInputValue("evidence"); const evidence = submitted.fields.getTextInputValue("evidence");
await muteAction(pluginData, duration, reason, evidence, target, interaction, submitted); 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, TextInputStyle,
} from "discord.js"; } from "discord.js";
import { GuildPluginData } from "knub"; import { GuildPluginData } from "knub";
import { canActOn } from "src/pluginUtils"; import { canActOn } from "../../../pluginUtils";
import { ModActionsPlugin } from "src/plugins/ModActions/ModActionsPlugin"; import { ModActionsPlugin } from "../../ModActions/ModActionsPlugin";
import { CaseTypes } from "../../../data/CaseTypes"; import { CaseTypes } from "../../../data/CaseTypes";
import { logger } from "../../../logger"; import { logger } from "../../../logger";
import { CasesPlugin } from "../../../plugins/Cases/CasesPlugin"; import { CasesPlugin } from "../../../plugins/Cases/CasesPlugin";
@ -34,25 +34,21 @@ async function noteAction(
const modactions = pluginData.getPlugin(ModActionsPlugin); const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasNotePermission(executingMember, interaction.channelId))) { if (!userCfg.can_use || !(await modactions.hasNotePermission(executingMember, interaction.channelId))) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Cannot note: insufficient permissions", content: "Cannot note: insufficient permissions",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Note interaction reply failed: ${err}`));
return; return;
} }
const targetMember = await pluginData.guild.members.fetch(target); const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) { if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Cannot note: insufficient permissions", content: "Cannot note: insufficient permissions",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Note interaction reply failed: ${err}`));
return; return;
} }
@ -72,13 +68,11 @@ async function noteAction(
}); });
const userName = renderUserUsername(targetMember.user); const userName = renderUserUsername(targetMember.user);
await interactionToReply await interactionToReply.editReply({
.editReply({
content: `Note added on **${userName}** (Case #${createdCase.case_number})`, content: `Note added on **${userName}** (Case #${createdCase.case_number})`,
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Note interaction reply failed: ${err}`));
} }
export async function launchNoteActionModal( export async function launchNoteActionModal(
@ -99,14 +93,11 @@ export async function launchNoteActionModal(
if (interaction.isButton()) { if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Note interaction defer failed: ${err}`)); await submitted.deferUpdate().catch((err) => logger.error(`Note interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) { } else if (interaction.isContextMenuCommand()) {
await submitted await submitted.deferReply({ ephemeral: true });
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Note interaction defer failed: ${err}`));
} }
const reason = submitted.fields.getTextInputValue("reason"); const reason = submitted.fields.getTextInputValue("reason");
await noteAction(pluginData, reason, target, interaction, submitted); 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 { GuildPluginData } from "knub";
import { CaseTypes } from "../../../data/CaseTypes"; import { CaseTypes } from "../../../data/CaseTypes";
import { Case } from "../../../data/entities/Case"; import { Case } from "../../../data/entities/Case";
import { CasesPlugin } from "../../../plugins/Cases/CasesPlugin"; import { CasesPlugin } from "../../Cases/CasesPlugin";
import { LogsPlugin } from "../../../plugins/Logs/LogsPlugin"; import { LogsPlugin } from "../../Logs/LogsPlugin";
import { ContextMenuPluginType } from "../types"; import { ContextMenuPluginType } from "../types";
export async function updateAction( export async function updateAction(
@ -19,7 +19,7 @@ export async function updateAction(
body: value, body: value,
}); });
pluginData.getPlugin(LogsPlugin).logCaseUpdate({ void pluginData.getPlugin(LogsPlugin).logCaseUpdate({
mod: executingMember.user, mod: executingMember.user,
caseNumber: theCase.case_number, caseNumber: theCase.case_number,
caseType: CaseTypes[theCase.type], caseType: CaseTypes[theCase.type],

View file

@ -8,8 +8,8 @@ import {
TextInputStyle, TextInputStyle,
} from "discord.js"; } from "discord.js";
import { GuildPluginData } from "knub"; import { GuildPluginData } from "knub";
import { canActOn } from "src/pluginUtils"; import { canActOn } from "../../../pluginUtils";
import { ModActionsPlugin } from "src/plugins/ModActions/ModActionsPlugin"; import { ModActionsPlugin } from "../../ModActions/ModActionsPlugin";
import { logger } from "../../../logger"; import { logger } from "../../../logger";
import { renderUserUsername } from "../../../utils"; import { renderUserUsername } from "../../../utils";
import { CaseArgs } from "../../Cases/types"; import { CaseArgs } from "../../Cases/types";
@ -34,25 +34,21 @@ async function warnAction(
const modactions = pluginData.getPlugin(ModActionsPlugin); const modactions = pluginData.getPlugin(ModActionsPlugin);
if (!userCfg.can_use || !(await modactions.hasWarnPermission(executingMember, interaction.channelId))) { if (!userCfg.can_use || !(await modactions.hasWarnPermission(executingMember, interaction.channelId))) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Cannot warn: insufficient permissions", content: "Cannot warn: insufficient permissions",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
return; return;
} }
const targetMember = await pluginData.guild.members.fetch(target); const targetMember = await pluginData.guild.members.fetch(target);
if (!canActOn(pluginData, executingMember, targetMember)) { if (!canActOn(pluginData, executingMember, targetMember)) {
await interactionToReply await interactionToReply.editReply({
.editReply({
content: "Cannot warn: insufficient permissions", content: "Cannot warn: insufficient permissions",
embeds: [], embeds: [],
components: [], components: [],
}) });
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
return; return;
} }
@ -62,9 +58,7 @@ async function warnAction(
const result = await modactions.warnMember(targetMember, reason, reason, { caseArgs }); const result = await modactions.warnMember(targetMember, reason, reason, { caseArgs });
if (result.status === "failed") { if (result.status === "failed") {
await interactionToReply await interactionToReply.editReply({ content: "Error: Failed to warn user", embeds: [], components: [] });
.editReply({ content: "Error: Failed to warn user", embeds: [], components: [] })
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
return; return;
} }
@ -76,9 +70,7 @@ async function warnAction(
await updateAction(pluginData, executingMember, result.case, evidence); await updateAction(pluginData, executingMember, result.case, evidence);
} }
await interactionToReply await interactionToReply.editReply({ content: muteMessage, embeds: [], components: [] });
.editReply({ content: muteMessage, embeds: [], components: [] })
.catch((err) => logger.error(`Warn interaction reply failed: ${err}`));
} }
export async function launchWarnActionModal( export async function launchWarnActionModal(
@ -105,15 +97,12 @@ export async function launchWarnActionModal(
if (interaction.isButton()) { if (interaction.isButton()) {
await submitted.deferUpdate().catch((err) => logger.error(`Warn interaction defer failed: ${err}`)); await submitted.deferUpdate().catch((err) => logger.error(`Warn interaction defer failed: ${err}`));
} else if (interaction.isContextMenuCommand()) { } else if (interaction.isContextMenuCommand()) {
await submitted await submitted.deferReply({ ephemeral: true });
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Warn interaction defer failed: ${err}`));
} }
const reason = submitted.fields.getTextInputValue("reason"); const reason = submitted.fields.getTextInputValue("reason");
const evidence = submitted.fields.getTextInputValue("evidence"); const evidence = submitted.fields.getTextInputValue("evidence");
await warnAction(pluginData, reason, evidence, target, interaction, submitted); 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 { GuildPluginData, guildPluginUserContextMenuCommand } from "knub";
import { Case } from "../../../data/entities/Case"; import { Case } from "../../../data/entities/Case";
import { logger } from "../../../logger"; 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 { SECONDS, UnknownUser, emptyEmbedValue, renderUserUsername, resolveUser, trimLines } from "../../../utils";
import { asyncMap } from "../../../utils/async"; import { asyncMap } from "../../../utils/async";
import { getChunkedEmbedFields } from "../../../utils/getChunkedEmbedFields"; import { getChunkedEmbedFields } from "../../../utils/getChunkedEmbedFields";
@ -40,9 +40,7 @@ export const ModMenuCmd = guildPluginUserContextMenuCommand({
name: "Mod Menu", name: "Mod Menu",
defaultMemberPermissions: PermissionFlagsBits.ViewAuditLog.toString(), defaultMemberPermissions: PermissionFlagsBits.ViewAuditLog.toString(),
async run({ pluginData, interaction }) { async run({ pluginData, interaction }) {
await interaction await interaction.deferReply({ ephemeral: true });
.deferReply({ ephemeral: true })
.catch((err) => logger.error(`Mod menu interaction defer failed: ${err}`));
// Run permission checks for executing user. // Run permission checks for executing user.
const executingMember = await pluginData.guild.members.fetch(interaction.user.id); const executingMember = await pluginData.guild.members.fetch(interaction.user.id);
@ -50,22 +48,14 @@ export const ModMenuCmd = guildPluginUserContextMenuCommand({
channelId: interaction.channelId, channelId: interaction.channelId,
member: executingMember, member: executingMember,
}); });
const utility = pluginData.getPlugin(UtilityPlugin); if (!userCfg.can_use || !userCfg.can_open_mod_menu) {
if ( await interaction.followUp({ content: "Error: Insufficient Permissions" });
!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}`));
return; return;
} }
const user = await resolveUser(pluginData.client, interaction.targetId); const user = await resolveUser(pluginData.client, interaction.targetId);
if (!user.id) { if (!user.id) {
await interaction await interaction.followUp("Error: User not found");
.followUp("Error: User not found")
.catch((err) => logger.error(`Mod menu interaction follow up failed: ${err}`));
return; return;
} }

View file

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

View file

@ -45,22 +45,22 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
const counter = config.counters[args.counterName]; const counter = config.counters[args.counterName];
const counterId = pluginData.state.counterIds[args.counterName]; const counterId = pluginData.state.counterIds[args.counterName];
if (!counter || !counterId) { if (!counter || !counterId) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, `Unknown counter: ${args.counterName}`); void pluginData.state.common.sendErrorMessage(message, `Unknown counter: ${args.counterName}`);
return; return;
} }
if (counter.can_edit === false) { 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; return;
} }
if (args.channel && !counter.per_channel) { 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; return;
} }
if (args.user && !counter.per_user) { 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; return;
} }
@ -69,13 +69,13 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which channel's counter value would you like to add to?`); 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); const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) { if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling"); void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return; return;
} }
const potentialChannel = pluginData.guild.channels.resolve(reply.content as Snowflake); const potentialChannel = pluginData.guild.channels.resolve(reply.content as Snowflake);
if (!potentialChannel || !(potentialChannel instanceof TextChannel)) { 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; return;
} }
@ -87,13 +87,13 @@ export const AddCounterCmd = guildPluginMessageCommand<CountersPluginType>()({
message.channel.send(`Which user's counter value would you like to add to?`); 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); const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) { if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling"); void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return; return;
} }
const potentialUser = await resolveUser(pluginData.client, reply.content); const potentialUser = await resolveUser(pluginData.client, reply.content);
if (!potentialUser || potentialUser instanceof UnknownUser) { if (!potentialUser || potentialUser instanceof UnknownUser) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Unknown user, cancelling"); void pluginData.state.common.sendErrorMessage(message, "Unknown user, cancelling");
return; 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?"); 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); const reply = await waitForReply(pluginData.client, message.channel, message.author.id);
if (!reply || !reply.content) { if (!reply || !reply.content) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Cancelling"); void pluginData.state.common.sendErrorMessage(message, "Cancelling");
return; return;
} }
const potentialAmount = parseInt(reply.content, 10); const potentialAmount = parseInt(reply.content, 10);
if (!potentialAmount) { if (!potentialAmount) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(message, "Not a number, cancelling"); void pluginData.state.common.sendErrorMessage(message, "Not a number, cancelling");
return; 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); const countersToShow = Array.from(Object.values(config.counters)).filter((c) => c.can_view !== false);
if (!countersToShow.length) { 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; return;
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -39,7 +39,7 @@ export async function runEvent(
} catch (e) { } catch (e) {
if (e instanceof ActionError) { if (e instanceof ActionError) {
if (event.trigger.type === "command") { 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 { } else {
// TODO: Where to log action errors from other kinds of triggers? // 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 z from "zod";
import { zBoundedCharacters, zBoundedRecord } from "../../utils"; import { zBoundedCharacters, zBoundedRecord } from "../../utils";
import { zAddRoleAction } from "./actions/addRoleAction"; import { zAddRoleAction } from "./actions/addRoleAction";
@ -8,6 +8,7 @@ import { zMakeRoleUnmentionableAction } from "./actions/makeRoleUnmentionableAct
import { zMessageAction } from "./actions/messageAction"; import { zMessageAction } from "./actions/messageAction";
import { zMoveToVoiceChannelAction } from "./actions/moveToVoiceChannelAction"; import { zMoveToVoiceChannelAction } from "./actions/moveToVoiceChannelAction";
import { zSetChannelPermissionOverridesAction } from "./actions/setChannelPermissionOverrides"; import { zSetChannelPermissionOverridesAction } from "./actions/setChannelPermissionOverrides";
import { CommonPlugin } from "../Common/CommonPlugin";
const zCommandTrigger = z.strictObject({ const zCommandTrigger = z.strictObject({
type: z.literal("command"), type: z.literal("command"),
@ -43,5 +44,6 @@ export interface CustomEventsPluginType extends BasePluginType {
config: z.infer<typeof zCustomEventsConfig>; config: z.infer<typeof zCustomEventsConfig>;
state: { state: {
clearTriggers: () => void; clearTriggers: () => void;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
}; };
} }

View file

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

View file

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

View file

@ -13,7 +13,7 @@ export const ListFollowCmd = locateUserCmd({
async run({ message: msg, pluginData }) { async run({ message: msg, pluginData }) {
const alerts = await pluginData.state.alerts.getAlertsByRequestorId(msg.member.id); const alerts = await pluginData.state.alerts.getAlertsByRequestorId(msg.member.id);
if (alerts.length === 0) { 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; return;
} }
@ -46,7 +46,7 @@ export const DeleteFollowCmd = locateUserCmd({
alerts.sort(sorter("expires_at")); alerts.sort(sorter("expires_at"));
if (args.num > alerts.length || args.num <= 0) { if (args.num > alerts.length || args.num <= 0) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Unknown alert!"); void pluginData.state.common.sendErrorMessage(msg, "Unknown alert!");
return; return;
} }
@ -54,6 +54,6 @@ export const DeleteFollowCmd = locateUserCmd({
clearExpiringVCAlert(toDelete); clearExpiringVCAlert(toDelete);
await pluginData.state.alerts.delete(toDelete.id); 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 z from "zod";
import { GuildVCAlerts } from "../../data/GuildVCAlerts"; import { GuildVCAlerts } from "../../data/GuildVCAlerts";
import { CommonPlugin } from "../Common/CommonPlugin";
export const zLocateUserConfig = z.strictObject({ export const zLocateUserConfig = z.strictObject({
can_where: z.boolean(), can_where: z.boolean(),
@ -13,6 +14,7 @@ export interface LocateUserPluginType extends BasePluginType {
alerts: GuildVCAlerts; alerts: GuildVCAlerts;
usersWithAlerts: string[]; usersWithAlerts: string[];
unregisterGuildEventListener: () => void; unregisterGuildEventListener: () => void;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
}; };
} }

View file

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

View file

@ -22,7 +22,7 @@ export async function sendWhere(
try { try {
invite = await createOrReuseInvite(voice); invite = await createOrReuseInvite(voice);
} catch { } 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; return;
} }
channel.send({ channel.send({

View file

@ -4,6 +4,7 @@ import { SaveMessagesToDBCmd } from "./commands/SaveMessagesToDB";
import { SavePinsToDBCmd } from "./commands/SavePinsToDB"; import { SavePinsToDBCmd } from "./commands/SavePinsToDB";
import { MessageCreateEvt, MessageDeleteBulkEvt, MessageDeleteEvt, MessageUpdateEvt } from "./events/SaveMessagesEvts"; import { MessageCreateEvt, MessageDeleteBulkEvt, MessageDeleteEvt, MessageUpdateEvt } from "./events/SaveMessagesEvts";
import { MessageSaverPluginType, zMessageSaverConfig } from "./types"; import { MessageSaverPluginType, zMessageSaverConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions: PluginOptions<MessageSaverPluginType> = { const defaultOptions: PluginOptions<MessageSaverPluginType> = {
config: { config: {
@ -43,4 +44,8 @@ export const MessageSaverPlugin = guildPlugin<MessageSaverPluginType>()({
const { state, guild } = pluginData; const { state, guild } = pluginData;
state.savedMessages = GuildSavedMessages.getGuildInstance(guild.id); 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(" ")); const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, args.ids.trim().split(" "));
if (failed.length) { if (failed.length) {
pluginData void pluginData.state.common.sendSuccessMessage(
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg, msg,
`Saved ${savedCount} messages. The following messages could not be saved: ${failed.join(", ")}`, `Saved ${savedCount} messages. The following messages could not be saved: ${failed.join(", ")}`,
); );
} else { } 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()]); const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, [...pins.keys()]);
if (failed.length) { if (failed.length) {
pluginData void pluginData.state.common.sendSuccessMessage(
.getPlugin(CommonPlugin)
.sendSuccessMessage(
msg, msg,
`Saved ${savedCount} messages. The following messages could not be saved: ${failed.join(", ")}`, `Saved ${savedCount} messages. The following messages could not be saved: ${failed.join(", ")}`,
); );
} else { } 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 z from "zod";
import { GuildSavedMessages } from "../../data/GuildSavedMessages"; import { GuildSavedMessages } from "../../data/GuildSavedMessages";
import { CommonPlugin } from "../Common/CommonPlugin";
export const zMessageSaverConfig = z.strictObject({ export const zMessageSaverConfig = z.strictObject({
can_manage: z.boolean(), can_manage: z.boolean(),
@ -10,6 +11,7 @@ export interface MessageSaverPluginType extends BasePluginType {
config: z.infer<typeof zMessageSaverConfig>; config: z.infer<typeof zMessageSaverConfig>;
state: { state: {
savedMessages: GuildSavedMessages; savedMessages: GuildSavedMessages;
common: pluginUtils.PluginPublicInterface<typeof CommonPlugin>;
}; };
} }

View file

@ -72,6 +72,7 @@ import { onModActionsEvent } from "./functions/onModActionsEvent";
import { updateCase } from "./functions/updateCase"; import { updateCase } from "./functions/updateCase";
import { warnMember } from "./functions/warnMember"; import { warnMember } from "./functions/warnMember";
import { AttachmentLinkReactionType, ModActionsPluginType, modActionsSlashGroup, zModActionsConfig } from "./types"; import { AttachmentLinkReactionType, ModActionsPluginType, modActionsSlashGroup, zModActionsConfig } from "./types";
import { CommonPlugin } from "../Common/CommonPlugin";
const defaultOptions = { const defaultOptions = {
config: { 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?", "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, ban_delete_message_days: 1,
attachment_link_reaction: "warn" as AttachmentLinkReactionType, attachment_link_reaction: "warn" as AttachmentLinkReactionType,
attachment_storing_channel: null,
can_note: false, can_note: false,
can_warn: false, can_warn: false,
@ -236,6 +236,10 @@ export const ModActionsPlugin = guildPlugin<ModActionsPluginType>()({
state.events = new EventEmitter(); state.events = new EventEmitter();
}, },
beforeStart(pluginData) {
pluginData.state.common = pluginData.getPlugin(CommonPlugin);
},
afterLoad(pluginData) { afterLoad(pluginData) {
const { state, guild } = pluginData; const { state, guild } = pluginData;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,7 +2,6 @@ import { ChatInputCommandInteraction, Message } from "discord.js";
import { GuildPluginData } from "knub"; import { GuildPluginData } from "knub";
import { sendContextResponse } from "../../../../pluginUtils"; import { sendContextResponse } from "../../../../pluginUtils";
import { CasesPlugin } from "../../../Cases/CasesPlugin"; import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { ModActionsPluginType } from "../../types"; import { ModActionsPluginType } from "../../types";
export async function actualCaseCmd( export async function actualCaseCmd(
@ -15,12 +14,12 @@ export async function actualCaseCmd(
const theCase = await pluginData.state.cases.findByCaseNumber(caseNumber); const theCase = await pluginData.state.cases.findByCaseNumber(caseNumber);
if (!theCase) { 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; return;
} }
const casesPlugin = pluginData.getPlugin(CasesPlugin); const casesPlugin = pluginData.getPlugin(CasesPlugin);
const embed = await casesPlugin.getCaseEmbed(theCase.id, authorId); 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 { commandTypeHelpers as ct } from "../../../../commandTypes";
import { actualCasesCmd } from "../../functions/actualCommands/actualCasesCmd"; import { actualCasesCmd } from "./actualCasesCmd";
import { modActionsMsgCmd } from "../../types"; import { modActionsMsgCmd } from "../../types";
const opts = { const opts = {

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,6 @@
import { GuildMember } from "discord.js"; import { GuildMember } from "discord.js";
import { slashOptions } from "knub"; import { slashOptions } from "knub";
import { actualDeleteCaseCmd } from "../../functions/actualCommands/actualDeleteCaseCmd"; import { actualDeleteCaseCmd } from "./actualDeleteCaseCmd";
import { modActionsSlashCmd } from "../../types"; import { modActionsSlashCmd } from "../../types";
const opts = [slashOptions.boolean({ name: "force", description: "Whether or not to force delete", required: false })]; 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 { getContextChannel, sendContextResponse } from "../../../../pluginUtils";
import { SECONDS, renderUsername } from "../../../../utils"; import { SECONDS, renderUsername } from "../../../../utils";
import { CasesPlugin } from "../../../Cases/CasesPlugin"; import { CasesPlugin } from "../../../Cases/CasesPlugin";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin"; import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { TimeAndDatePlugin } from "../../../TimeAndDate/TimeAndDatePlugin"; import { TimeAndDatePlugin } from "../../../TimeAndDate/TimeAndDatePlugin";
import { ModActionsPluginType } from "../../types"; import { ModActionsPluginType } from "../../types";
@ -31,7 +30,7 @@ export async function actualDeleteCaseCmd(
} }
if (failed.length === caseNumbers.length) { 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; return;
} }
@ -83,13 +82,15 @@ export async function actualDeleteCaseCmd(
: ""; : "";
const amt = validCases.length - cancelled; const amt = validCases.length - cancelled;
if (amt === 0) { if (amt === 0) {
pluginData pluginData.state.common.sendErrorMessage(
.getPlugin(CommonPlugin) context,
.sendErrorMessage(context, "All deletions were cancelled, no cases were deleted."); "All deletions were cancelled, no cases were deleted."
);
return; return;
} }
pluginData pluginData.state.common.sendSuccessMessage(
.getPlugin(CommonPlugin) context,
.sendSuccessMessage(context, `${amt} case${amt === 1 ? " was" : "s were"} deleted!${failedAddendum}`); `${amt} case${amt === 1 ? " was" : "s were"} deleted!${failedAddendum}`
);
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,5 @@
import { ChatInputCommandInteraction, Message } from "discord.js"; import { ChatInputCommandInteraction, Message } from "discord.js";
import { GuildPluginData } from "knub"; import { GuildPluginData } from "knub";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { ModActionsPluginType } from "../../types"; import { ModActionsPluginType } from "../../types";
export async function actualHideCaseCmd( export async function actualHideCaseCmd(
@ -21,7 +20,7 @@ export async function actualHideCaseCmd(
} }
if (failed.length === caseNumbers.length) { 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; return;
} }
const failedAddendum = const failedAddendum =
@ -30,9 +29,7 @@ export async function actualHideCaseCmd(
: ""; : "";
const amt = caseNumbers.length - failed.length; const amt = caseNumbers.length - failed.length;
pluginData pluginData.state.common.sendSuccessMessage(
.getPlugin(CommonPlugin)
.sendSuccessMessage(
context, context,
`${amt} case${amt === 1 ? " is" : "s are"} now hidden! Use \`unhidecase\` to unhide them.${failedAddendum}`, `${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 { hasPermission } from "knub/helpers";
import { commandTypeHelpers as ct } from "../../../../commandTypes"; import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { resolveUser } from "../../../../utils"; import { resolveUser } from "../../../../utils";
import { CommonPlugin } from "../../../Common/CommonPlugin"; import { actualKickCmd } from "./actualKickCmd";
import { actualKickCmd } from "../../functions/actualCommands/actualKickCmd";
import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs"; import { readContactMethodsFromArgs } from "../../functions/readContactMethodsFromArgs";
import { modActionsMsgCmd } from "../../types"; import { modActionsMsgCmd } from "../../types";
@ -30,7 +29,7 @@ export const KickMsgCmd = modActionsMsgCmd({
async run({ pluginData, message: msg, args }) { async run({ pluginData, message: msg, args }) {
const user = await resolveUser(pluginData.client, args.user); const user = await resolveUser(pluginData.client, args.user);
if (!user.id) { if (!user.id) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, `User not found`); pluginData.state.common.sendErrorMessage(msg, `User not found`);
return; return;
} }
@ -38,7 +37,7 @@ export const KickMsgCmd = modActionsMsgCmd({
let mod = msg.member; let mod = msg.member;
if (args.mod) { if (args.mod) {
if (!(await hasPermission(await pluginData.config.getForMessage(msg), "can_act_as_other"))) { 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; return;
} }
@ -49,7 +48,7 @@ export const KickMsgCmd = modActionsMsgCmd({
try { try {
contactMethods = readContactMethodsFromArgs(args); contactMethods = readContactMethodsFromArgs(args);
} catch (e) { } catch (e) {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, e.message); pluginData.state.common.sendErrorMessage(msg, e.message);
return; return;
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,12 +3,11 @@ import { GuildPluginData } from "knub";
import { LogType } from "../../../../data/LogType"; import { LogType } from "../../../../data/LogType";
import { logger } from "../../../../logger"; import { logger } from "../../../../logger";
import { canActOn, isContextInteraction, sendContextResponse } from "../../../../pluginUtils"; import { canActOn, isContextInteraction, sendContextResponse } from "../../../../pluginUtils";
import { CommonPlugin } from "../../../Common/CommonPlugin";
import { LogsPlugin } from "../../../Logs/LogsPlugin"; import { LogsPlugin } from "../../../Logs/LogsPlugin";
import { MutesPlugin } from "../../../Mutes/MutesPlugin"; import { MutesPlugin } from "../../../Mutes/MutesPlugin";
import { ModActionsPluginType } from "../../types"; import { ModActionsPluginType } from "../../types";
import { handleAttachmentLinkDetectionAndGetRestriction } from "../attachmentLinkReaction"; import { handleAttachmentLinkDetectionAndGetRestriction } from "../../functions/attachmentLinkReaction";
import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../formatReasonForAttachments"; import { formatReasonWithAttachments, formatReasonWithMessageLinkForAttachments } from "../../functions/formatReasonForAttachments";
export async function actualMassMuteCmd( export async function actualMassMuteCmd(
pluginData: GuildPluginData<ModActionsPluginType>, pluginData: GuildPluginData<ModActionsPluginType>,
@ -20,7 +19,7 @@ export async function actualMassMuteCmd(
) { ) {
// Limit to 100 users at once (arbitrary?) // Limit to 100 users at once (arbitrary?)
if (userIds.length > 100) { 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; return;
} }
@ -35,9 +34,10 @@ export async function actualMassMuteCmd(
for (const userId of userIds) { for (const userId of userIds) {
const member = pluginData.guild.members.cache.get(userId as Snowflake); const member = pluginData.guild.members.cache.get(userId as Snowflake);
if (member && !canActOn(pluginData, author, member)) { if (member && !canActOn(pluginData, author, member)) {
pluginData pluginData.state.common.sendErrorMessage(
.getPlugin(CommonPlugin) context,
.sendErrorMessage(context, "Cannot massmute one or more users: insufficient permissions"); "Cannot massmute one or more users: insufficient permissions"
);
return; return;
} }
} }
@ -77,7 +77,7 @@ export async function actualMassMuteCmd(
const successfulMuteCount = userIds.length - failedMutes.length; const successfulMuteCount = userIds.length - failedMutes.length;
if (successfulMuteCount === 0) { if (successfulMuteCount === 0) {
// All mutes failed // 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 { } else {
// Success on all or some mutes // Success on all or some mutes
pluginData.getPlugin(LogsPlugin).logMassMute({ pluginData.getPlugin(LogsPlugin).logMassMute({
@ -86,14 +86,12 @@ export async function actualMassMuteCmd(
}); });
if (failedMutes.length) { if (failedMutes.length) {
pluginData pluginData.state.common.sendSuccessMessage(
.getPlugin(CommonPlugin)
.sendSuccessMessage(
context, context,
`Muted ${successfulMuteCount} users, ${failedMutes.length} failed: ${failedMutes.join(" ")}`, `Muted ${successfulMuteCount} users, ${failedMutes.length} failed: ${failedMutes.join(" ")}`,
); );
} else { } 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 { waitForReply } from "knub/helpers";
import { commandTypeHelpers as ct } from "../../../../commandTypes"; import { commandTypeHelpers as ct } from "../../../../commandTypes";
import { getContextChannel, sendContextResponse } from "../../../../pluginUtils"; import { getContextChannel, sendContextResponse } from "../../../../pluginUtils";
import { CommonPlugin } from "../../../Common/CommonPlugin"; import { actualMassUnbanCmd } from "./actualMassUnbanCmd";
import { actualMassUnbanCmd } from "../../functions/actualCommands/actualMassUnbanCmd";
import { modActionsMsgCmd } from "../../types"; import { modActionsMsgCmd } from "../../types";
export const MassUnbanMsgCmd = modActionsMsgCmd({ export const MassUnbanMsgCmd = modActionsMsgCmd({
@ -21,7 +20,7 @@ export const MassUnbanMsgCmd = modActionsMsgCmd({
sendContextResponse(msg, "Unban reason? `cancel` to cancel"); sendContextResponse(msg, "Unban reason? `cancel` to cancel");
const unbanReasonReply = await waitForReply(pluginData.client, await getContextChannel(msg), msg.author.id); const unbanReasonReply = await waitForReply(pluginData.client, await getContextChannel(msg), msg.author.id);
if (!unbanReasonReply || !unbanReasonReply.content || unbanReasonReply.content.toLowerCase().trim() === "cancel") { if (!unbanReasonReply || !unbanReasonReply.content || unbanReasonReply.content.toLowerCase().trim() === "cancel") {
pluginData.getPlugin(CommonPlugin).sendErrorMessage(msg, "Cancelled"); pluginData.state.common.sendErrorMessage(msg, "Cancelled");
return; return;
} }

View file

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

View file

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

View file

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

View file

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

View file

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