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

Merge remote-tracking branch 'upstream/master' into feat/mime-checking

This commit is contained in:
Hiroyuki 2021-08-14 13:52:08 -04:00
commit 64df1909e7
No known key found for this signature in database
GPG key ID: 843DF434003F6710
76 changed files with 18894 additions and 4637 deletions

View file

@ -37,7 +37,7 @@ export function initDocs(app: express.Express) {
app.get("/docs/plugins", (req: express.Request, res: express.Response) => {
res.json(
docsPlugins.map(plugin => {
const thinInfo = plugin.info ? { prettyName: plugin.info.prettyName } : {};
const thinInfo = plugin.info ? { prettyName: plugin.info.prettyName, legacy: plugin.info.legacy ?? false } : {};
return {
name: plugin.name,
info: thinInfo,

View file

@ -0,0 +1,35 @@
import { DeleteResult, getRepository, InsertResult, Repository } from "typeorm";
import { BaseGuildRepository } from "./BaseGuildRepository";
import { ContextMenuLink } from "./entities/ContextMenuLink";
export class GuildContextMenuLinks extends BaseGuildRepository {
private contextLinks: Repository<ContextMenuLink>;
constructor(guildId) {
super(guildId);
this.contextLinks = getRepository(ContextMenuLink);
}
async get(id: string): Promise<ContextMenuLink | undefined> {
return this.contextLinks.findOne({
where: {
guild_id: this.guildId,
context_id: id,
},
});
}
async create(contextId: string, contextAction: string): Promise<InsertResult> {
return this.contextLinks.insert({
guild_id: this.guildId,
context_id: contextId,
action_name: contextAction,
});
}
async deleteAll(): Promise<DeleteResult> {
return this.contextLinks.delete({
guild_id: this.guildId,
});
}
}

View file

@ -45,9 +45,9 @@ export class GuildSavedMessages extends BaseGuildRepository {
timestamp: msg.createdTimestamp,
};
if (msg.attachments.size) data.attachments = msg.attachments.array();
if (msg.attachments.size) data.attachments = [...msg.attachments.values()];
if (msg.embeds.length) data.embeds = msg.embeds;
if (msg.stickers?.size) data.stickers = msg.stickers.array();
if (msg.stickers?.size) data.stickers = [...msg.stickers.values()];
return data;
}

View file

@ -0,0 +1,10 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity("context_menus")
export class ContextMenuLink {
@Column() guild_id: string;
@Column() @PrimaryColumn() context_id: string;
@Column() action_name: string;
}

View file

@ -26,14 +26,6 @@ if (!process.env.KEY) {
process.exit(1);
}
declare global {
// This is here so TypeScript doesn't give an error when importing twemoji
// since one of the signatures of twemoji.parse() takes an HTMLElement but
// we're not in a browser environment so including the DOM lib would not make
// sense
type HTMLElement = unknown;
}
// Error handling
let recentPluginErrors = 0;
const RECENT_PLUGIN_ERROR_EXIT_THRESHOLD = 5;

View file

@ -0,0 +1,32 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class CreateContextMenuTable1628809879962 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "context_menus",
columns: [
{
name: "guild_id",
type: "bigint",
},
{
name: "context_id",
type: "bigint",
isPrimary: true,
isUnique: true,
},
{
name: "action_name",
type: "varchar",
length: "100",
},
],
}),
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("context_menus");
}
}

View file

@ -73,6 +73,10 @@ const configPreprocessor: ConfigPreprocessorFn<AutomodPluginType> = options => {
rule["enabled"] = true;
}
if (rule["allow_further_rules"] == null) {
rule["allow_further_rules"] = false;
}
if (rule["affects_bots"] == null) {
rule["affects_bots"] = false;
}

View file

@ -53,7 +53,7 @@ export const AddRolesAction = automodAction({
await Promise.all(
members.map(async member => {
const memberRoles = new Set(member.roles.cache.keyArray());
const memberRoles = new Set(member.roles.cache.keys());
for (const roleId of rolesToAssign) {
memberRoles.add(roleId as Snowflake);
ignoreRoleChange(pluginData, member.id, roleId);

View file

@ -54,7 +54,7 @@ export const RemoveRolesAction = automodAction({
await Promise.all(
members.map(async member => {
const memberRoles = new Set(member.roles.cache.keyArray());
const memberRoles = new Set(member.roles.cache.keys());
for (const roleId of rolesToRemove) {
memberRoles.delete(roleId as Snowflake);
ignoreRoleChange(pluginData, member.id, roleId);

View file

@ -72,7 +72,7 @@ export async function runAutomod(pluginData: GuildPluginData<AutomodPluginType>,
matchResult.fullSummary = `Triggered automod rule **${ruleName}**\n${matchResult.summary}`.trim();
break triggerLoop;
if (!rule.allow_further_rules) break triggerLoop;
}
}
}
@ -94,7 +94,7 @@ export async function runAutomod(pluginData: GuildPluginData<AutomodPluginType>,
});
}
break;
if (!rule.allow_further_rules) break;
}
}
}

View file

@ -26,6 +26,7 @@ export const Rule = t.type({
triggers: t.array(t.partial(AvailableTriggers.props)),
actions: t.partial(AvailableActions.props),
cooldown: tNullable(t.string),
allow_further_rules: t.boolean,
});
export type TRule = t.TypeOf<typeof Rule>;

View file

@ -52,6 +52,7 @@ export const CensorPlugin = zeppelinGuildPlugin<CensorPluginType>()({
Censor words, tokens, links, regex, etc.
For more advanced filtering, check out the Automod plugin!
`),
legacy: true,
},
dependencies: [LogsPlugin],

View file

@ -0,0 +1,61 @@
import { PluginOptions } from "knub";
import { StrictValidationError } from "src/validatorUtils";
import { ConfigPreprocessorFn } from "knub/dist/config/configTypes";
import { GuildContextMenuLinks } from "../../data/GuildContextMenuLinks";
import { LogsPlugin } from "../Logs/LogsPlugin";
import { MutesPlugin } from "../Mutes/MutesPlugin";
import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint";
import { availableTypes } from "./actions/availableActions";
import { ContextClickedEvt } from "./events/ContextClickedEvt";
import { ConfigSchema, ContextMenuPluginType } from "./types";
import { loadAllCommands } from "./utils/loadAllCommands";
const defaultOptions: PluginOptions<ContextMenuPluginType> = {
config: {
context_actions: {},
},
};
const configPreprocessor: ConfigPreprocessorFn<ContextMenuPluginType> = options => {
if (options.config.context_actions) {
for (const [name, contextMenu] of Object.entries(options.config.context_actions)) {
if (Object.entries(contextMenu.action).length !== 1) {
throw new StrictValidationError([`Invalid value for context_actions/${name}: Must have exactly one action.`]);
}
const actionName = Object.entries(contextMenu.action)[0][0];
if (!availableTypes[actionName].includes(contextMenu.type)) {
throw new StrictValidationError([
`Invalid value for context_actions/${name}/${actionName}: ${actionName} is not allowed on type ${contextMenu.type}.`,
]);
}
}
}
return options;
};
export const ContextMenuPlugin = zeppelinGuildPlugin<ContextMenuPluginType>()({
name: "context_menu",
configSchema: ConfigSchema,
defaultOptions,
configPreprocessor,
// prettier-ignore
events: [
ContextClickedEvt,
],
beforeLoad(pluginData) {
const { state, guild } = pluginData;
state.contextMenuLinks = new GuildContextMenuLinks(guild.id);
},
afterLoad(pluginData) {
loadAllCommands(pluginData);
},
dependencies: [MutesPlugin, LogsPlugin],
});

View file

@ -0,0 +1,19 @@
import * as t from "io-ts";
import { ContextActionBlueprint } from "../helpers";
import { CleanAction } from "./clean";
import { MuteAction } from "./mute";
export const availableActions: Record<string, ContextActionBlueprint<any>> = {
mute: MuteAction,
clean: CleanAction,
};
export const AvailableActions = t.type({
mute: MuteAction.configType,
clean: CleanAction.configType,
});
export const availableTypes: Record<string, string[]> = {
mute: ["USER"],
clean: ["MESSAGE"],
};

View file

@ -0,0 +1,64 @@
import { TextChannel } from "discord.js";
import * as t from "io-ts";
import { canActOn } from "src/pluginUtils";
import { LogType } from "../../../data/LogType";
import { UtilityPlugin } from "../../../plugins/Utility/UtilityPlugin";
import { ERRORS, RecoverablePluginError } from "../../../RecoverablePluginError";
import { tNullable } from "../../../utils";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { contextMenuAction } from "../helpers";
export const CleanAction = contextMenuAction({
configType: t.type({
amount: tNullable(t.number),
targetUserOnly: tNullable(t.boolean),
"delete-pins": tNullable(t.boolean),
}),
defaultConfig: {
amount: 10,
targetUserOnly: false,
"delete-pins": false,
},
async apply({ pluginData, actionConfig, actionName, interaction }) {
interaction.deferReply({ ephemeral: true });
const targetMessage = interaction.channel
? await interaction.channel.messages.fetch(interaction.targetId)
: await (pluginData.guild.channels.resolve(interaction.channelId) as TextChannel).messages.fetch(
interaction.targetId,
);
const amount = actionConfig.amount ?? 10;
const targetUserOnly = actionConfig.targetUserOnly ?? false;
const deletePins = actionConfig["delete-pins"] ?? false;
const user = targetUserOnly ? targetMessage.author.id : undefined;
const targetMember = await pluginData.guild.members.fetch(targetMessage.author.id);
const executingMember = await pluginData.guild.members.fetch(interaction.user.id);
const utility = pluginData.getPlugin(UtilityPlugin);
if (targetUserOnly && !canActOn(pluginData, executingMember, targetMember)) {
interaction.followUp({ ephemeral: true, content: "Cannot clean users messages: insufficient permissions" });
return;
}
try {
interaction.followUp(`Cleaning... Amount: ${amount}, User Only: ${targetUserOnly}, Pins: ${deletePins}`);
utility.clean(
{ count: amount, user, channel: targetMessage.channel.id, "delete-pins": deletePins },
targetMessage,
);
} catch (e) {
interaction.followUp({ ephemeral: true, content: "Plugin error, please check your BOT_ALERTs" });
if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) {
pluginData.getPlugin(LogsPlugin).log(LogType.BOT_ALERT, {
body: `Failed to clean in <#${interaction.channelId}> in ContextMenu action \`${actionName}\``,
});
} else {
throw e;
}
}
},
});

View file

@ -0,0 +1,83 @@
import humanizeDuration from "humanize-duration";
import * as t from "io-ts";
import { canActOn } from "src/pluginUtils";
import { LogType } from "../../../data/LogType";
import { ERRORS, RecoverablePluginError } from "../../../RecoverablePluginError";
import { convertDelayStringToMS, tDelayString, tNullable } from "../../../utils";
import { CaseArgs } from "../../Cases/types";
import { LogsPlugin } from "../../Logs/LogsPlugin";
import { MutesPlugin } from "../../Mutes/MutesPlugin";
import { contextMenuAction } from "../helpers";
import { resolveActionContactMethods } from "../utils/resolveActionContactMethods";
export const MuteAction = contextMenuAction({
configType: t.type({
reason: tNullable(t.string),
duration: tNullable(tDelayString),
notify: tNullable(t.string),
notifyChannel: tNullable(t.string),
remove_roles_on_mute: tNullable(t.union([t.boolean, t.array(t.string)])),
restore_roles_on_mute: tNullable(t.union([t.boolean, t.array(t.string)])),
postInCaseLog: tNullable(t.boolean),
hide_case: tNullable(t.boolean),
}),
defaultConfig: {
notify: null, // Use defaults from ModActions
hide_case: false,
},
async apply({ pluginData, actionConfig, actionName, interaction }) {
const duration = actionConfig.duration ? convertDelayStringToMS(actionConfig.duration)! : undefined;
const reason = actionConfig.reason || "Context Menu Action";
const contactMethods = actionConfig.notify ? resolveActionContactMethods(pluginData, actionConfig) : undefined;
const rolesToRemove = actionConfig.remove_roles_on_mute;
const rolesToRestore = actionConfig.restore_roles_on_mute;
const caseArgs: Partial<CaseArgs> = {
modId: pluginData.client.user!.id,
automatic: true,
postInCaseLogOverride: actionConfig.postInCaseLog ?? undefined,
hide: Boolean(actionConfig.hide_case),
};
interaction.deferReply({ ephemeral: true });
const mutes = pluginData.getPlugin(MutesPlugin);
const userId = interaction.targetId;
const targetMember = await pluginData.guild.members.fetch(interaction.targetId);
const executingMember = await pluginData.guild.members.fetch(interaction.user.id);
if (!canActOn(pluginData, executingMember, targetMember)) {
interaction.followUp({ ephemeral: true, content: "Cannot mute: insufficient permissions" });
return;
}
try {
const result = await mutes.muteUser(
userId,
duration,
reason,
{ contactMethods, caseArgs, isAutomodAction: true },
rolesToRemove,
rolesToRestore,
);
const muteMessage = `Muted **${result.case.user_name}** ${
duration ? `for ${humanizeDuration(duration)}` : "indefinitely"
} (Case #${result.case.case_number}) (user notified via ${result.notifyResult.method ??
"dm"})\nPlease update the new case with the \`update\` command`;
interaction.followUp({ ephemeral: true, content: muteMessage });
} catch (e) {
interaction.followUp({ ephemeral: true, content: "Plugin error, please check your BOT_ALERTs" });
if (e instanceof RecoverablePluginError && e.code === ERRORS.NO_MUTE_ROLE_IN_CONFIG) {
pluginData.getPlugin(LogsPlugin).log(LogType.BOT_ALERT, {
body: `Failed to mute <@!${userId}> in ContextMenu action \`${actionName}\` because a mute role has not been specified in server config`,
});
} else {
throw e;
}
}
},
});

View file

@ -0,0 +1,13 @@
import { ContextMenuInteraction } from "discord.js";
import { contextMenuEvt } from "../types";
import { routeContextAction } from "../utils/contextRouter";
export const ContextClickedEvt = contextMenuEvt({
event: "interactionCreate",
async listener(meta) {
if (!meta.args.interaction.isContextMenu) return;
const inter = meta.args.interaction as ContextMenuInteraction;
await routeContextAction(meta.pluginData, inter);
},
});

View file

@ -0,0 +1,25 @@
import { ContextMenuInteraction } from "discord.js";
import * as t from "io-ts";
import { GuildPluginData } from "knub";
import { Awaitable } from "knub/dist/utils";
import { ContextMenuPluginType } from "./types";
type ContextActionApplyFn<TConfigType> = (meta: {
actionName: string;
pluginData: GuildPluginData<ContextMenuPluginType>;
actionConfig: TConfigType;
interaction: ContextMenuInteraction;
}) => Awaitable<void>;
export interface ContextActionBlueprint<TConfigType extends t.Any> {
configType: TConfigType;
defaultConfig: Partial<t.TypeOf<TConfigType>>;
apply: ContextActionApplyFn<t.TypeOf<TConfigType>>;
}
export function contextMenuAction<TConfigType extends t.Any>(
blueprint: ContextActionBlueprint<TConfigType>,
): ContextActionBlueprint<TConfigType> {
return blueprint;
}

View file

@ -0,0 +1,38 @@
import * as t from "io-ts";
import { BasePluginType, typedGuildCommand, typedGuildEventListener } from "knub";
import { GuildContextMenuLinks } from "../../data/GuildContextMenuLinks";
import { tNullable } from "../../utils";
import { AvailableActions } from "./actions/availableActions";
export enum ContextMenuTypes {
USER = 2,
MESSAGE = 3,
}
export const ContextMenuTypeNameToNumber: Record<string, number> = {
USER: 2,
MESSAGE: 3,
};
const ContextActionOpts = t.type({
enabled: tNullable(t.boolean),
label: t.string,
type: t.keyof(ContextMenuTypes),
action: t.partial(AvailableActions.props),
});
export type TContextActionOpts = t.TypeOf<typeof ContextActionOpts>;
export const ConfigSchema = t.type({
context_actions: t.record(t.string, ContextActionOpts),
});
export type TConfigSchema = t.TypeOf<typeof ConfigSchema>;
export interface ContextMenuPluginType extends BasePluginType {
config: TConfigSchema;
state: {
contextMenuLinks: GuildContextMenuLinks;
};
}
export const contextMenuCmd = typedGuildCommand<ContextMenuPluginType>();
export const contextMenuEvt = typedGuildEventListener<ContextMenuPluginType>();

View file

@ -0,0 +1,28 @@
import { ContextMenuInteraction } from "discord.js";
import { GuildPluginData } from "knub";
import { availableActions } from "../actions/availableActions";
import { ContextMenuPluginType } from "../types";
export async function routeContextAction(
pluginData: GuildPluginData<ContextMenuPluginType>,
interaction: ContextMenuInteraction,
) {
const contextLink = await pluginData.state.contextMenuLinks.get(interaction.commandId);
if (!contextLink) return;
const contextActions = Object.entries(pluginData.config.get().context_actions);
const configLink = contextActions.find(x => x[0] === contextLink.action_name);
if (!configLink) return;
for (const [actionName, actionConfig] of Object.entries(configLink[1].action)) {
if (actionConfig == null) return;
const action = availableActions[actionName];
action.apply({
actionName,
pluginData,
actionConfig,
interaction,
});
return;
}
}

View file

@ -0,0 +1,37 @@
import { ApplicationCommandData } from "discord.js";
import { LogType } from "src/data/LogType";
import { LogsPlugin } from "src/plugins/Logs/LogsPlugin";
import { GuildPluginData } from "knub";
import { ContextMenuPluginType, ContextMenuTypeNameToNumber } from "../types";
export async function loadAllCommands(pluginData: GuildPluginData<ContextMenuPluginType>) {
const comms = await pluginData.client.application!.commands;
const actions = pluginData.config.get().context_actions;
const newCommands: ApplicationCommandData[] = [];
const addedNames: string[] = [];
for (const [name, configAction] of Object.entries(actions)) {
if (!configAction.enabled) continue;
const data: ApplicationCommandData = {
type: ContextMenuTypeNameToNumber[configAction.type],
name: configAction.label,
};
addedNames.push(name);
newCommands.push(data);
}
const setCommands = await comms.set(newCommands, pluginData.guild.id).catch(e => {
pluginData.getPlugin(LogsPlugin).log(LogType.BOT_ALERT, `Unable to overwrite context menus: ${e}`);
return undefined;
});
if (!setCommands) return;
const setCommandsArray = [...setCommands.values()];
await pluginData.state.contextMenuLinks.deleteAll();
for (let i = 0; i < setCommandsArray.length; i++) {
const command = setCommandsArray[i];
pluginData.state.contextMenuLinks.create(command.id, addedNames[i]);
}
}

View file

@ -0,0 +1,32 @@
import { Snowflake, TextChannel } from "discord.js";
import { GuildPluginData } from "knub";
import { ERRORS, RecoverablePluginError } from "../../../RecoverablePluginError";
import { disableUserNotificationStrings, UserNotificationMethod } from "../../../utils";
import { ContextMenuPluginType } from "../types";
export function resolveActionContactMethods(
pluginData: GuildPluginData<ContextMenuPluginType>,
actionConfig: {
notify?: string | null;
notifyChannel?: string | null;
},
): UserNotificationMethod[] {
if (actionConfig.notify === "dm") {
return [{ type: "dm" }];
} else if (actionConfig.notify === "channel") {
if (!actionConfig.notifyChannel) {
throw new RecoverablePluginError(ERRORS.NO_USER_NOTIFICATION_CHANNEL);
}
const channel = pluginData.guild.channels.cache.get(actionConfig.notifyChannel as Snowflake);
if (!(channel instanceof TextChannel)) {
throw new RecoverablePluginError(ERRORS.INVALID_USER_NOTIFICATION_CHANNEL);
}
return [{ type: "channel", channel }];
} else if (actionConfig.notify && disableUserNotificationStrings.includes(actionConfig.notify)) {
return [];
}
return [];
}

View file

@ -31,6 +31,6 @@ export async function addRoleAction(
const rolesToAdd = Array.isArray(action.role) ? action.role : [action.role];
await target.edit({
roles: Array.from(new Set([...target.roles.cache.array(), ...rolesToAdd])) as Snowflake[],
roles: Array.from(new Set([...target.roles.cache.values(), ...rolesToAdd])) as Snowflake[],
});
}

View file

@ -27,8 +27,8 @@ export const LogsGuildMemberUpdateEvt = logsEvt({
}
if (!isEqual(oldMember.roles, member.roles)) {
const addedRoles = diff(member.roles.cache.keyArray(), oldMember.roles.cache.keyArray());
const removedRoles = diff(oldMember.roles.cache.keyArray(), member.roles.cache.keyArray());
const addedRoles = diff([...member.roles.cache.keys()], [...oldMember.roles.cache.keys()]);
const removedRoles = diff([...oldMember.roles.cache.keys()], [...member.roles.cache.keys()]);
let skip = false;
if (

View file

@ -14,6 +14,11 @@ import {
} from "../../../utils";
import { TimeAndDatePlugin } from "../../TimeAndDate/TimeAndDatePlugin";
import { FORMAT_NO_TIMESTAMP, LogsPluginType, TLogChannel } from "../types";
import {
getConfigAccessibleMemberLevel,
IConfigAccessibleMember,
memberToConfigAccessibleMember,
} from "../../../utils/configAccessibleObjects";
export async function getLogMessage(
pluginData: GuildPluginData<LogsPluginType>,
@ -48,17 +53,26 @@ export async function getLogMessage(
const mentions: string[] = [];
for (const userOrMember of usersOrMembers) {
let user;
let member;
let member: IConfigAccessibleMember | null = null;
if (userOrMember.user) {
member = userOrMember;
member = userOrMember as IConfigAccessibleMember;
user = member.user;
} else {
user = userOrMember;
member = await resolveMember(pluginData.client, pluginData.guild, user.id);
const apiMember = await resolveMember(pluginData.client, pluginData.guild, user.id);
if (apiMember) {
member = memberToConfigAccessibleMember(apiMember);
}
}
const memberConfig = (await pluginData.config.getMatchingConfig({ member, userId: user.id })) || ({} as any);
const level = member ? getConfigAccessibleMemberLevel(pluginData, member) : 0;
const memberConfig =
(await pluginData.config.getMatchingConfig({
level,
memberRoles: member ? member.roles.map(r => r.id) : [],
userId: user.id,
})) || ({} as any);
// Revert to old behavior (verbose name w/o ping if allow_user_mentions is enabled (for whatever reason))
if (config.allow_user_mentions) {

View file

@ -16,7 +16,7 @@ export const SavePinsToDBCmd = messageSaverCmd({
await msg.channel.send(`Saving pins from <#${args.channel.id}>...`);
const pins = await args.channel.messages.fetchPinned();
const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, pins.keyArray());
const { savedCount, failed } = await saveMessagesToDB(pluginData, args.channel, [...pins.keys()]);
if (failed.length) {
sendSuccessMessage(

View file

@ -60,7 +60,7 @@ export const AddCaseCmd = modActionsCmd({
return;
}
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const reason = formatReasonWithAttachments(args.reason, [...msg.attachments.values()]);
// Create the case
const casesPlugin = pluginData.getPlugin(CasesPlugin);

View file

@ -51,7 +51,7 @@ export const BanCmd = modActionsCmd({
}
const time = args["time"] ? args["time"] : null;
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const reason = formatReasonWithAttachments(args.reason, [...msg.attachments.values()]);
const memberToBan = await resolveMember(pluginData.client, pluginData.guild, user.id);
// The moderator who did the action is the message author or, if used, the specified -mod
let mod = msg.member;

View file

@ -61,7 +61,7 @@ export const ForcebanCmd = modActionsCmd({
mod = args.mod;
}
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const reason = formatReasonWithAttachments(args.reason, [...msg.attachments.values()]);
ignoreEvent(pluginData, IgnoredEventType.Ban, user.id);
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_BAN, user.id);

View file

@ -39,7 +39,7 @@ export const MassbanCmd = modActionsCmd({
return;
}
const banReason = formatReasonWithAttachments(banReasonReply.content, msg.attachments.array());
const banReason = formatReasonWithAttachments(banReasonReply.content, [...msg.attachments.values()]);
// Verify we can act on each of the users specified
for (const userId of args.userIds) {

View file

@ -37,7 +37,7 @@ export const MassunbanCmd = modActionsCmd({
return;
}
const unbanReason = formatReasonWithAttachments(unbanReasonReply.content, msg.attachments.array());
const unbanReason = formatReasonWithAttachments(unbanReasonReply.content, [...msg.attachments.values()]);
// Ignore automatic unban cases and logs for these users
// We'll create our own cases below and post a single "mass unbanned" log instead

View file

@ -39,7 +39,7 @@ export const MassmuteCmd = modActionsCmd({
return;
}
const muteReason = formatReasonWithAttachments(muteReasonReceived.content, msg.attachments.array());
const muteReason = formatReasonWithAttachments(muteReasonReceived.content, [...msg.attachments.values()]);
// Verify we can act upon all users
for (const userId of args.userIds) {

View file

@ -31,7 +31,7 @@ export const NoteCmd = modActionsCmd({
}
const userName = user.tag;
const reason = formatReasonWithAttachments(args.note, msg.attachments.array());
const reason = formatReasonWithAttachments(args.note, [...msg.attachments.values()]);
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const createdCase = await casesPlugin.createCase({

View file

@ -47,7 +47,7 @@ export const UnbanCmd = modActionsCmd({
}
pluginData.state.serverLogs.ignoreLog(LogType.MEMBER_UNBAN, user.id);
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const reason = formatReasonWithAttachments(args.reason, [...msg.attachments.values()]);
try {
ignoreEvent(pluginData, IgnoredEventType.Unban, user.id);

View file

@ -63,7 +63,7 @@ export const WarnCmd = modActionsCmd({
}
const config = pluginData.config.get();
const reason = formatReasonWithAttachments(args.reason, msg.attachments.array());
const reason = formatReasonWithAttachments(args.reason, [...msg.attachments.values()]);
const casesPlugin = pluginData.getPlugin(CasesPlugin);
const priorWarnAmount = await casesPlugin.getCaseTypeAmountForUserId(memberToWarn.id, CaseTypes.Warn);

View file

@ -42,7 +42,7 @@ export async function actualMuteUserCmd(
}
const timeUntilUnmute = args.time && humanizeDuration(args.time);
const reason = args.reason ? formatReasonWithAttachments(args.reason, msg.attachments.array()) : undefined;
const reason = args.reason ? formatReasonWithAttachments(args.reason, [...msg.attachments.values()]) : undefined;
let muteResult: MuteResult;
const mutesPlugin = pluginData.getPlugin(MutesPlugin);

View file

@ -27,7 +27,7 @@ export async function actualUnmuteCmd(
pp = msg.author;
}
const reason = args.reason ? formatReasonWithAttachments(args.reason, msg.attachments.array()) : undefined;
const reason = args.reason ? formatReasonWithAttachments(args.reason, [...msg.attachments.values()]) : undefined;
const mutesPlugin = pluginData.getPlugin(MutesPlugin);
const result = await mutesPlugin.unmuteUser(user.id, args.time, {

View file

@ -24,7 +24,7 @@ export async function updateCase(pluginData, msg: Message, args) {
return;
}
const note = formatReasonWithAttachments(args.note, msg.attachments.array());
const note = formatReasonWithAttachments(args.note, [...msg.attachments.values()]);
const casesPlugin = pluginData.getPlugin(CasesPlugin);
await casesPlugin.createCaseNote({

View file

@ -21,7 +21,7 @@ export async function clearExpiredMutes(pluginData: GuildPluginData<MutesPluginT
}
if (mute.roles_to_restore) {
const guildRoles = pluginData.guild.roles.cache;
let newRoles: string[] = member.roles.cache.keyArray();
let newRoles = [...member.roles.cache.keys()];
newRoles =
muteRole && newRoles.includes(muteRole) ? newRoles.splice(newRoles.indexOf(muteRole), 1) : newRoles;
for (const toRestore of mute.roles_to_restore) {

View file

@ -58,7 +58,7 @@ export async function muteUser(
if (member) {
const logs = pluginData.getPlugin(LogsPlugin);
// remove and store any roles to be removed/restored
const currentUserRoles = member.roles.cache.keyArray();
const currentUserRoles = [...member.roles.cache.keys()];
let newRoles: string[] = currentUserRoles;
const removeRoles = removeRolesOnMuteOverride ?? config.remove_roles_on_mute;
const restoreRoles = restoreRolesOnMuteOverride ?? config.restore_roles_on_mute;

View file

@ -42,7 +42,7 @@ export async function unmuteUser(
}
if (existingMute?.roles_to_restore) {
const guildRoles = pluginData.guild.roles.cache;
let newRoles: string[] = member.roles.cache.keyArray();
let newRoles = [...member.roles.cache.keys()];
newRoles = muteRole && newRoles.includes(muteRole) ? newRoles.splice(newRoles.indexOf(muteRole), 1) : newRoles;
for (const toRestore of existingMute.roles_to_restore) {
if (guildRoles.has(toRestore as Snowflake) && toRestore !== muteRole) newRoles.push(toRestore);

View file

@ -141,7 +141,7 @@ export async function actualPostCmd(
author_name: msg.author.tag,
channel_id: targetChannel.id,
content,
attachments: msg.attachments.array(),
attachments: [...msg.attachments.values()],
post_at: postAt
.clone()
.tz("Etc/UTC")
@ -180,7 +180,7 @@ export async function actualPostCmd(
// When the message isn't scheduled for later, post it immediately
if (!opts.schedule) {
await postMessage(pluginData, targetChannel, content, msg.attachments.array(), opts["enable-mentions"]);
await postMessage(pluginData, targetChannel, content, [...msg.attachments.values()], opts["enable-mentions"]);
}
if (opts.repeat) {

View file

@ -24,7 +24,7 @@ export async function addMemberPendingRoleChange(
const member = await resolveMember(pluginData.client, pluginData.guild, memberId);
if (member) {
const newRoleIds = new Set(member.roles.cache.keyArray());
const newRoleIds = new Set(member.roles.cache.keys());
for (const change of newPendingRoleChangeObj.changes) {
if (change.mode === "+") newRoleIds.add(change.roleId as Snowflake);
else newRoleIds.delete(change.roleId as Snowflake);

View file

@ -43,6 +43,7 @@ export const RoleAddCmd = selfGrantableRolesCmd({
pluginData,
msg.channel,
`<@!${msg.author.id}> Unknown ${args.roleNames.length === 1 ? "role" : "roles"}`,
{ users: [msg.author.id] },
);
lock.unlock();
return;
@ -87,6 +88,7 @@ export const RoleAddCmd = selfGrantableRolesCmd({
pluginData,
msg.channel,
`<@!${msg.author.id}> Got an error while trying to grant you the roles`,
{ users: [msg.author.id] },
);
return;
}
@ -118,7 +120,9 @@ export const RoleAddCmd = selfGrantableRolesCmd({
messageParts.push("couldn't recognize some of the roles");
}
sendSuccessMessage(pluginData, msg.channel, `<@!${msg.author.id}> ${messageParts.join("; ")}`);
sendSuccessMessage(pluginData, msg.channel, `<@!${msg.author.id}> ${messageParts.join("; ")}`, {
users: [msg.author.id],
});
lock.unlock();
},

View file

@ -51,12 +51,14 @@ export const RoleRemoveCmd = selfGrantableRolesCmd({
msg.channel,
`<@!${msg.author.id}> Removed ${removedRolesStr.join(", ")} ${removedRolesWord};` +
` couldn't recognize the other roles you mentioned`,
{ users: [msg.author.id] },
);
} else {
sendSuccessMessage(
pluginData,
msg.channel,
`<@!${msg.author.id}> Removed ${removedRolesStr.join(", ")} ${removedRolesWord}`,
{ users: [msg.author.id] },
);
}
} catch {
@ -64,6 +66,7 @@ export const RoleRemoveCmd = selfGrantableRolesCmd({
pluginData,
msg.channel,
`<@!${msg.author.id}> Got an error while trying to remove the roles`,
{ users: [msg.author.id] },
);
}
} else {
@ -71,6 +74,7 @@ export const RoleRemoveCmd = selfGrantableRolesCmd({
pluginData,
msg.channel,
`<@!${msg.author.id}> Unknown ${args.roleNames.length === 1 ? "role" : "roles"}`,
{ users: [msg.author.id] },
);
}

View file

@ -51,6 +51,7 @@ export const SpamPlugin = zeppelinGuildPlugin<SpamPluginType>()({
Basic spam detection and auto-muting.
For more advanced spam filtering, check out the Automod plugin!
`),
legacy: true,
},
dependencies: [LogsPlugin],

View file

@ -31,7 +31,7 @@ export const MigratePinsCmd = starboardCmd({
msg.channel.send(`Migrating pins from <#${args.pinChannel.id}> to <#${starboardChannel.id}>...`);
const pins = (await args.pinChannel.messages.fetchPinned()).array();
const pins = [...(await args.pinChannel.messages.fetchPinned().catch(() => [])).values()];
pins.reverse(); // Migrate pins starting from the oldest message
for (const pin of pins) {

View file

@ -13,7 +13,7 @@ import { AboutCmd } from "./commands/AboutCmd";
import { AvatarCmd } from "./commands/AvatarCmd";
import { BanSearchCmd } from "./commands/BanSearchCmd";
import { ChannelInfoCmd } from "./commands/ChannelInfoCmd";
import { CleanCmd } from "./commands/CleanCmd";
import { CleanArgs, cleanCmd, CleanCmd } from "./commands/CleanCmd";
import { ContextCmd } from "./commands/ContextCmd";
import { EmojiInfoCmd } from "./commands/EmojiInfoCmd";
import { HelpCmd } from "./commands/HelpCmd";
@ -156,6 +156,14 @@ export const UtilityPlugin = zeppelinGuildPlugin<UtilityPluginType>()({
AutoJoinThreadSyncEvt,
],
public: {
clean(pluginData) {
return (args: CleanArgs, msg) => {
cleanCmd(pluginData, args, msg);
};
},
},
beforeLoad(pluginData) {
const { state, guild } = pluginData;

View file

@ -10,12 +10,13 @@ import { getBaseUrl, sendErrorMessage, sendSuccessMessage } from "../../../plugi
import { allowTimeout } from "../../../RegExpRunner";
import { DAYS, getInviteCodesInString, noop, SECONDS } from "../../../utils";
import { utilityCmd, UtilityPluginType } from "../types";
import { boolean, number } from "io-ts";
const MAX_CLEAN_COUNT = 150;
const MAX_CLEAN_TIME = 1 * DAYS;
const CLEAN_COMMAND_DELETE_DELAY = 5 * SECONDS;
async function cleanMessages(
export async function cleanMessages(
pluginData: GuildPluginData<UtilityPluginType>,
channel: TextChannel,
savedMessages: SavedMessage[],
@ -61,6 +62,142 @@ const opts = {
"to-id": ct.anyId({ option: true, shortcut: "id" }),
};
export interface CleanArgs {
count: number;
update?: boolean;
user?: string;
channel?: string;
bots?: boolean;
"delete-pins"?: boolean;
"has-invites"?: boolean;
match?: RegExp;
"to-id"?: string;
}
export async function cleanCmd(pluginData: GuildPluginData<UtilityPluginType>, args: CleanArgs | any, msg) {
if (args.count > MAX_CLEAN_COUNT || args.count <= 0) {
sendErrorMessage(pluginData, msg.channel, `Clean count must be between 1 and ${MAX_CLEAN_COUNT}`);
return;
}
const targetChannel = args.channel ? pluginData.guild.channels.cache.get(args.channel as Snowflake) : msg.channel;
if (!targetChannel || !(targetChannel instanceof TextChannel)) {
sendErrorMessage(pluginData, msg.channel, `Invalid channel specified`);
return;
}
if (targetChannel.id !== msg.channel.id) {
const configForTargetChannel = await pluginData.config.getMatchingConfig({
userId: msg.author.id,
member: msg.member,
channelId: targetChannel.id,
categoryId: targetChannel.parentId,
});
if (configForTargetChannel.can_clean !== true) {
sendErrorMessage(pluginData, msg.channel, `Missing permissions to use clean on that channel`);
return;
}
}
const cleaningMessage = msg.channel.send("Cleaning...");
const messagesToClean: SavedMessage[] = [];
let beforeId = msg.id;
const timeCutoff = msg.createdTimestamp - MAX_CLEAN_TIME;
const upToMsgId = args["to-id"];
let foundId = false;
const deletePins = args["delete-pins"] != null ? args["delete-pins"] : false;
let pins: Message[] = [];
if (!deletePins) {
pins = [...(await msg.channel.messages.fetchPinned().catch(() => [])).values()];
}
while (messagesToClean.length < args.count) {
const potentialMessages = await targetChannel.messages.fetch({
before: beforeId,
limit: args.count,
});
if (potentialMessages.size === 0) break;
const existingStored = await pluginData.state.savedMessages.getMultiple([...potentialMessages.keys()]);
const alreadyStored = existingStored.map(stored => stored.id);
const messagesToStore = [
...potentialMessages.filter(potentialMsg => !alreadyStored.includes(potentialMsg.id)).values(),
];
await pluginData.state.savedMessages.createFromMessages(messagesToStore);
const potentialMessagesToClean = await pluginData.state.savedMessages.getMultiple([...potentialMessages.keys()]);
if (potentialMessagesToClean.length === 0) break;
const filtered: SavedMessage[] = [];
for (const message of potentialMessagesToClean) {
const contentString = message.data.content || "";
if (args.user && message.user_id !== args.user) continue;
if (args.bots && !message.is_bot) continue;
if (!deletePins && pins.find(x => x.id === message.id) != null) continue;
if (args["has-invites"] && getInviteCodesInString(contentString).length === 0) continue;
if (upToMsgId != null && message.id < upToMsgId) {
foundId = true;
break;
}
if (moment.utc(message.posted_at).valueOf() < timeCutoff) continue;
if (args.match && !(await pluginData.state.regexRunner.exec(args.match, contentString).catch(allowTimeout))) {
continue;
}
filtered.push(message);
}
const remaining = args.count - messagesToClean.length;
const withoutOverflow = filtered.slice(0, remaining);
messagesToClean.push(...withoutOverflow);
beforeId = potentialMessages.lastKey()!;
if (foundId || moment.utc(potentialMessages.last()!.createdTimestamp).valueOf() < timeCutoff) {
break;
}
}
let responseMsg: Message | undefined;
if (messagesToClean.length > 0) {
const cleanResult = await cleanMessages(pluginData, targetChannel, messagesToClean, msg.author);
let responseText = `Cleaned ${messagesToClean.length} ${messagesToClean.length === 1 ? "message" : "messages"}`;
if (targetChannel.id !== msg.channel.id) {
responseText += ` in <#${targetChannel.id}>: ${cleanResult.archiveUrl}`;
}
if (args.update) {
const modActions = pluginData.getPlugin(ModActionsPlugin);
const channelId = targetChannel.id !== msg.channel.id ? targetChannel.id : msg.channel.id;
const updateMessage = `Cleaned ${messagesToClean.length} ${
messagesToClean.length === 1 ? "message" : "messages"
} in <#${channelId}>: ${cleanResult.archiveUrl}`;
if (typeof args.update === "number") {
modActions.updateCase(msg, args.update, updateMessage);
} else {
modActions.updateCase(msg, null, updateMessage);
}
}
responseMsg = await sendSuccessMessage(pluginData, msg.channel, responseText);
} else {
responseMsg = await sendErrorMessage(pluginData, msg.channel, `Found no messages to clean!`);
}
await (await cleaningMessage).delete();
if (targetChannel.id === msg.channel.id) {
// Delete the !clean command and the bot response if a different channel wasn't specified
// (so as not to spam the cleaned channel with the command itself)
setTimeout(() => {
msg.delete().catch(noop);
responseMsg?.delete().catch(noop);
}, CLEAN_COMMAND_DELETE_DELAY);
}
}
export const CleanCmd = utilityCmd({
trigger: ["clean", "clear"],
description: "Remove a number of recent messages",
@ -83,126 +220,6 @@ export const CleanCmd = utilityCmd({
],
async run({ message: msg, args, pluginData }) {
if (args.count > MAX_CLEAN_COUNT || args.count <= 0) {
sendErrorMessage(pluginData, msg.channel, `Clean count must be between 1 and ${MAX_CLEAN_COUNT}`);
return;
}
const targetChannel = args.channel ? pluginData.guild.channels.cache.get(args.channel as Snowflake) : msg.channel;
if (!targetChannel || !(targetChannel instanceof TextChannel)) {
sendErrorMessage(pluginData, msg.channel, `Invalid channel specified`);
return;
}
if (targetChannel.id !== msg.channel.id) {
const configForTargetChannel = await pluginData.config.getMatchingConfig({
userId: msg.author.id,
member: msg.member,
channelId: targetChannel.id,
categoryId: targetChannel.parentId,
});
if (configForTargetChannel.can_clean !== true) {
sendErrorMessage(pluginData, msg.channel, `Missing permissions to use clean on that channel`);
return;
}
}
const cleaningMessage = msg.channel.send("Cleaning...");
const messagesToClean: SavedMessage[] = [];
let beforeId = msg.id;
const timeCutoff = msg.createdTimestamp - MAX_CLEAN_TIME;
const upToMsgId = args["to-id"];
let foundId = false;
const deletePins = args["delete-pins"] != null ? args["delete-pins"] : false;
let pins: Message[] = [];
if (!deletePins) {
pins = (await msg.channel.messages.fetchPinned()).array();
}
while (messagesToClean.length < args.count) {
const potentialMessages = await targetChannel.messages.fetch({
before: beforeId,
limit: args.count,
});
if (potentialMessages.size === 0) break;
const existingStored = await pluginData.state.savedMessages.getMultiple(potentialMessages.keyArray());
const alreadyStored = existingStored.map(stored => stored.id);
const messagesToStore = potentialMessages
.array()
.filter(potentialMsg => !alreadyStored.includes(potentialMsg.id));
await pluginData.state.savedMessages.createFromMessages(messagesToStore);
const potentialMessagesToClean = await pluginData.state.savedMessages.getMultiple(potentialMessages.keyArray());
if (potentialMessagesToClean.length === 0) break;
const filtered: SavedMessage[] = [];
for (const message of potentialMessagesToClean) {
const contentString = message.data.content || "";
if (args.user && message.user_id !== args.user) continue;
if (args.bots && !message.is_bot) continue;
if (!deletePins && pins.find(x => x.id === message.id) != null) continue;
if (args["has-invites"] && getInviteCodesInString(contentString).length === 0) continue;
if (upToMsgId != null && message.id < upToMsgId) {
foundId = true;
break;
}
if (moment.utc(message.posted_at).valueOf() < timeCutoff) continue;
if (args.match && !(await pluginData.state.regexRunner.exec(args.match, contentString).catch(allowTimeout))) {
continue;
}
filtered.push(message);
}
const remaining = args.count - messagesToClean.length;
const withoutOverflow = filtered.slice(0, remaining);
messagesToClean.push(...withoutOverflow);
beforeId = potentialMessages.lastKey()!;
if (foundId || moment.utc(potentialMessages.last()!.createdTimestamp).valueOf() < timeCutoff) {
break;
}
}
let responseMsg: Message | undefined;
if (messagesToClean.length > 0) {
const cleanResult = await cleanMessages(pluginData, targetChannel, messagesToClean, msg.author);
let responseText = `Cleaned ${messagesToClean.length} ${messagesToClean.length === 1 ? "message" : "messages"}`;
if (targetChannel.id !== msg.channel.id) {
responseText += ` in <#${targetChannel.id}>: ${cleanResult.archiveUrl}`;
}
if (args.update) {
const modActions = pluginData.getPlugin(ModActionsPlugin);
const channelId = targetChannel.id !== msg.channel.id ? targetChannel.id : msg.channel.id;
const updateMessage = `Cleaned ${messagesToClean.length} ${
messagesToClean.length === 1 ? "message" : "messages"
} in <#${channelId}>: ${cleanResult.archiveUrl}`;
if (typeof args.update === "number") {
modActions.updateCase(msg, args.update, updateMessage);
} else {
modActions.updateCase(msg, null, updateMessage);
}
}
responseMsg = await sendSuccessMessage(pluginData, msg.channel, responseText);
} else {
responseMsg = await sendErrorMessage(pluginData, msg.channel, `Found no messages to clean!`);
}
await (await cleaningMessage).delete();
if (targetChannel.id === msg.channel.id) {
// Delete the !clean command and the bot response if a different channel wasn't specified
// (so as not to spam the cleaned channel with the command itself)
setTimeout(() => {
msg.delete().catch(noop);
responseMsg?.delete().catch(noop);
}, CLEAN_COMMAND_DELETE_DELAY);
}
cleanCmd(pluginData, args, msg);
},
});

View file

@ -1,7 +1,7 @@
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage } from "../../../pluginUtils";
import { customEmojiRegex } from "../../../utils";
import { getEmojiInfoEmbed } from "../functions/getEmojiInfoEmbed";
import { getCustomEmojiId } from "../functions/getCustomEmojiId";
import { utilityCmd } from "../types";
export const EmojiInfoCmd = utilityCmd({
@ -11,17 +11,17 @@ export const EmojiInfoCmd = utilityCmd({
permission: "can_emojiinfo",
signature: {
emoji: ct.string({ required: false }),
emoji: ct.string({ required: true }),
},
async run({ message, args, pluginData }) {
const emojiIdMatch = args.emoji.match(customEmojiRegex);
if (!emojiIdMatch?.[2]) {
const emojiId = getCustomEmojiId(args.emoji);
if (!emojiId) {
sendErrorMessage(pluginData, message.channel, "Emoji not found");
return;
}
const embed = await getEmojiInfoEmbed(pluginData, emojiIdMatch[2]);
const embed = await getEmojiInfoEmbed(pluginData, emojiId);
if (!embed) {
sendErrorMessage(pluginData, message.channel, "Emoji not found");
return;

View file

@ -2,26 +2,20 @@ import { Snowflake } from "discord.js";
import { getChannelId, getRoleId } from "knub/dist/utils";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage } from "../../../pluginUtils";
import {
customEmojiRegex,
isValidSnowflake,
noop,
parseInviteCodeInput,
resolveInvite,
resolveUser,
} from "../../../utils";
import { isValidSnowflake, noop, parseInviteCodeInput, resolveInvite, resolveUser } from "../../../utils";
import { getUserInfoEmbed } from "../functions/getUserInfoEmbed";
import { canReadChannel } from "../../../utils/canReadChannel";
import { resolveMessageTarget } from "../../../utils/resolveMessageTarget";
import { getChannelInfoEmbed } from "../functions/getChannelInfoEmbed";
import { getEmojiInfoEmbed } from "../functions/getEmojiInfoEmbed";
import { getGuildPreview } from "../functions/getGuildPreview";
import { getInviteInfoEmbed } from "../functions/getInviteInfoEmbed";
import { getMessageInfoEmbed } from "../functions/getMessageInfoEmbed";
import { getRoleInfoEmbed } from "../functions/getRoleInfoEmbed";
import { getEmojiInfoEmbed } from "../functions/getEmojiInfoEmbed";
import { getCustomEmojiId } from "../functions/getCustomEmojiId";
import { utilityCmd } from "../types";
import { getServerInfoEmbed } from "../functions/getServerInfoEmbed";
import { getSnowflakeInfoEmbed } from "../functions/getSnowflakeInfoEmbed";
import { getUserInfoEmbed } from "../functions/getUserInfoEmbed";
import { utilityCmd } from "../types";
export const InfoCmd = utilityCmd({
trigger: "info",
@ -139,9 +133,9 @@ export const InfoCmd = utilityCmd({
// 8. Emoji
if (userCfg.can_emojiinfo) {
const emojiIdMatch = value.match(customEmojiRegex);
if (emojiIdMatch?.[2]) {
const embed = await getEmojiInfoEmbed(pluginData, emojiIdMatch[2]);
const emojiId = getCustomEmojiId(value);
if (emojiId) {
const embed = await getEmojiInfoEmbed(pluginData, emojiId);
if (embed) {
message.channel.send({ embeds: [embed] });
return;

View file

@ -1,6 +1,6 @@
import { MessageAttachment } from "discord.js";
import fs from "fs";
import sharp from "sharp";
import photon from "@silvia-odwyer/photon-node";
import twemoji from "twemoji";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { sendErrorMessage } from "../../../pluginUtils";
@ -14,12 +14,21 @@ async function getBufferFromUrl(url: string): Promise<Buffer> {
return fsp.readFile(downloadedEmoji.path);
}
async function resizeBuffer(input: Buffer, width: number, height: number): Promise<Buffer> {
return sharp(input, { density: 800 })
.resize(width, height, {
fit: "inside",
})
.toBuffer();
function bufferToPhotonImage(input: Buffer): photon.PhotonImage {
const base64 = input.toString("base64").replace(/^data:image\/\w+;base64,/, "");
return photon.PhotonImage.new_from_base64(base64);
}
function photonImageToBuffer(image: photon.PhotonImage): Buffer {
const base64 = image.get_base64().replace(/^data:image\/\w+;base64,/, "");
return Buffer.from(base64, "base64");
}
function resizeBuffer(input: Buffer, width: number, height: number): Buffer {
const photonImage = bufferToPhotonImage(input);
photon.resize(photonImage, width, height, photon.SamplingFilter.Lanczos3);
return photonImageToBuffer(photonImage);
}
const CDN_URL = "https://twemoji.maxcdn.com/2/svg";

View file

@ -1,6 +1,7 @@
import { Util } from "discord.js";
import { commandTypeHelpers as ct } from "../../../commandTypes";
import { canActOn, sendSuccessMessage } from "../../../pluginUtils";
import { errorMessage } from "../../../utils";
import { canActOn, sendSuccessMessage } from "../../../pluginUtils";
import { utilityCmd } from "../types";
export const NicknameCmd = utilityCmd({
@ -11,10 +12,19 @@ export const NicknameCmd = utilityCmd({
signature: {
member: ct.resolvedMember(),
nickname: ct.string({ catchAll: true }),
nickname: ct.string({ catchAll: true, required: false }),
},
async run({ message: msg, args, pluginData }) {
if (!args.nickname) {
if (!args.member.nickname) {
msg.channel.send(`<@!${args.member.id}> does not have a nickname`);
} else {
msg.channel.send(`The nickname of <@!${args.member.id}> is **${Util.escapeBold(args.nickname)}**`);
}
return;
}
if (msg.member.id !== args.member.id && !canActOn(pluginData, msg.member, args.member)) {
msg.channel.send(errorMessage("Cannot change nickname: insufficient permissions"));
return;
@ -29,9 +39,7 @@ export const NicknameCmd = utilityCmd({
const oldNickname = args.member.nickname || "<none>";
try {
await args.member.edit({
nick: args.nickname,
});
await args.member.setNickname(args.nickname ?? null);
} catch {
msg.channel.send(errorMessage("Failed to change nickname"));
return;

View file

@ -19,10 +19,13 @@ export const NicknameResetCmd = utilityCmd({
return;
}
if (!args.member.nickname) {
msg.channel.send(errorMessage("User does not have a nickname"));
return;
}
try {
await args.member.edit({
nick: "",
});
await args.member.setNickname(null);
} catch {
msg.channel.send(errorMessage("Failed to reset nickname"));
return;

View file

@ -5,7 +5,7 @@ import { utilityCmd } from "../types";
const { performance } = require("perf_hooks");
export const PingCmd = utilityCmd({
trigger: "ping",
trigger: ["ping", "pong"],
description: "Test the bot's ping to the Discord API",
permission: "can_ping",

View file

@ -32,7 +32,7 @@ export const VcdisconnectCmd = utilityCmd({
const channel = pluginData.guild.channels.cache.get(args.member.voice.channelId) as VoiceChannel;
try {
await args.member.voice.kick();
await args.member.voice.disconnect();
} catch {
sendErrorMessage(pluginData, msg.channel, "Failed to disconnect member");
return;

View file

@ -9,6 +9,7 @@ import { LogType } from "../../../data/LogType";
import { canActOn, sendErrorMessage, sendSuccessMessage } from "../../../pluginUtils";
import { channelMentionRegex, isSnowflake, simpleClosestStringMatch } from "../../../utils";
import { utilityCmd } from "../types";
import { ChannelTypeStrings } from "../../../types";
export const VcmoveCmd = utilityCmd({
trigger: "vcmove",
@ -45,9 +46,9 @@ export const VcmoveCmd = utilityCmd({
channel = potentialChannel;
} else {
// Search string -> find closest matching voice channel name
const voiceChannels = pluginData.guild.channels.cache.array().filter(theChannel => {
return theChannel instanceof VoiceChannel;
}) as VoiceChannel[];
const voiceChannels = [...pluginData.guild.channels.cache.values()].filter(
(c): c is VoiceChannel => c.type === ChannelTypeStrings.VOICE,
);
const closestMatch = simpleClosestStringMatch(args.channel, voiceChannels, ch => ch.name);
if (!closestMatch) {
sendErrorMessage(pluginData, msg.channel, "No matching voice channels");
@ -124,9 +125,9 @@ export const VcmoveAllCmd = utilityCmd({
channel = potentialChannel;
} else {
// Search string -> find closest matching voice channel name
const voiceChannels = pluginData.guild.channels.cache.array().filter(theChannel => {
return theChannel instanceof VoiceChannel;
}) as VoiceChannel[];
const voiceChannels = [...pluginData.guild.channels.cache.values()].filter(
(c): c is VoiceChannel => c.type === ChannelTypeStrings.VOICE,
);
const closestMatch = simpleClosestStringMatch(args.channel, voiceChannels, ch => ch.name);
if (!closestMatch) {
sendErrorMessage(pluginData, msg.channel, "No matching voice channels");

View file

@ -130,11 +130,12 @@ export async function getChannelInfoEmbed(
if (channel.type === ChannelTypeStrings.PRIVATE_THREAD || channel.type === ChannelTypeStrings.PUBLIC_THREAD) {
const thread = channel as ThreadChannel;
const parentChannelName = thread.parent?.name ? thread.parent.name : `<#${thread.parentId}>`;
const parentChannelName = thread.parent?.name ?? `<#${thread.parentId}>`;
const memberCount = thread.memberCount ?? thread.members.cache.size;
const owner = await pluginData.guild.members.fetch(thread.ownerId).catch(() => null);
const ownerMention = owner ? verboseUserMention(owner.user) : "Unknown#0000";
const humanizedArchiveTime = `Archive duration: **${humanizeDuration(thread.autoArchiveDuration * MINUTES)}**`;
const owner = await thread.fetchOwner().catch(() => null);
const ownerMention = owner?.user ? verboseUserMention(owner.user) : "Unknown#0000";
const autoArchiveDuration = thread.autoArchiveDuration === "MAX" ? 10080 : thread.autoArchiveDuration; // TODO: Boost level check
const humanizedArchiveTime = `Archive duration: **${humanizeDuration((autoArchiveDuration ?? 0) * MINUTES)}**`;
embed.fields.push({
name: preEmbedPadding + "Thread information",

View file

@ -0,0 +1,6 @@
const customEmojiRegex = /(?:<a?:[a-z0-9_]{2,32}:)?([1-9]\d+)>?/i;
export function getCustomEmojiId(str: string): string | null {
const emojiIdMatch = str.match(customEmojiRegex);
return emojiIdMatch?.[1] ?? null;
}

View file

@ -27,6 +27,7 @@ export interface ZeppelinGuildPluginBlueprint<TPluginData extends GuildPluginDat
description?: TMarkdown;
usageGuide?: TMarkdown;
configurationGuide?: TMarkdown;
legacy?: boolean;
};
configPreprocessor?: (

View file

@ -6,6 +6,7 @@ import { CasesPlugin } from "./Cases/CasesPlugin";
import { CensorPlugin } from "./Censor/CensorPlugin";
import { ChannelArchiverPlugin } from "./ChannelArchiver/ChannelArchiverPlugin";
import { CompanionChannelsPlugin } from "./CompanionChannels/CompanionChannelsPlugin";
import { ContextMenuPlugin } from "./ContextMenus/ContextMenuPlugin";
import { CountersPlugin } from "./Counters/CountersPlugin";
import { CustomEventsPlugin } from "./CustomEvents/CustomEventsPlugin";
import { GuildAccessMonitorPlugin } from "./GuildAccessMonitor/GuildAccessMonitorPlugin";
@ -67,6 +68,7 @@ export const guildPlugins: Array<ZeppelinGuildPluginBlueprint<any>> = [
CustomEventsPlugin,
TimeAndDatePlugin,
CountersPlugin,
ContextMenuPlugin,
];
// prettier-ignore

View file

@ -49,6 +49,7 @@ export interface ZeppelinPluginInfo {
description?: TMarkdown;
usageGuide?: TMarkdown;
configurationGuide?: TMarkdown;
legacy?: boolean;
}
export interface CommandInfo {

View file

@ -8,6 +8,7 @@ import {
GuildChannel,
GuildMember,
Invite,
InviteGuild,
LimitedCollection,
Message,
MessageAttachment,
@ -248,9 +249,8 @@ export function nonNullish<V>(v: V): v is NonNullable<V> {
return v != null;
}
export type InviteOpts = "withMetadata" | "withCount" | "withoutCount";
export type GuildInvite<CT extends InviteOpts = "withMetadata"> = Invite & { guild: Guild };
export type GroupDMInvite<CT extends InviteOpts = "withMetadata"> = Invite & {
export type GuildInvite = Invite & { guild: InviteGuild | Guild };
export type GroupDMInvite = Invite & {
channel: PartialChannelData;
type: typeof Constants.ChannelTypes.GROUP_DM;
};
@ -535,7 +535,7 @@ export async function findRelevantAuditLogEntry(
}
}
const entries = auditLogs ? auditLogs.entries.array() : [];
const entries = auditLogs ? [...auditLogs.entries.values()] : [];
entries.sort((a, b) => {
if (a.createdAt > b.createdAt) return -1;
@ -1302,7 +1302,7 @@ export async function resolveInvite<T extends boolean>(
return promise as ResolveInviteReturnType<T>;
}
const internalStickerCache: LimitedCollection<Snowflake, Sticker> = new LimitedCollection(500);
const internalStickerCache: LimitedCollection<Snowflake, Sticker> = new LimitedCollection({ maxSize: 500 });
export async function resolveStickerId(bot: Client, id: Snowflake): Promise<Sticker | null> {
const cachedSticker = internalStickerCache.get(id);
@ -1480,11 +1480,11 @@ export function isFullMessage(msg: Message | PartialMessage): msg is Message {
return (msg as Message).createdAt != null;
}
export function isGuildInvite<CT extends InviteOpts>(invite: Invite): invite is GuildInvite<CT> {
export function isGuildInvite(invite: Invite): invite is GuildInvite {
return invite.guild != null;
}
export function isGroupDMInvite<CT extends InviteOpts>(invite: Invite): invite is GroupDMInvite<CT> {
export function isGroupDMInvite(invite: Invite): invite is GroupDMInvite {
return invite.guild == null && invite.channel?.type === ChannelTypeStrings.GROUP;
}

View file

@ -11,6 +11,7 @@ import {
User,
} from "discord.js";
import { UnknownUser } from "src/utils";
import { GuildPluginData } from "knub";
export interface IConfigAccessibleUser {
id: Snowflake | string;
@ -87,7 +88,7 @@ export function memberToConfigAccessibleMember(member: GuildMember | PartialGuil
...user,
user,
nick: member.nickname ?? "*None*",
roles: member.roles.cache.mapValues(r => roleToConfigAccessibleRole(r)).array(),
roles: [...member.roles.cache.mapValues(r => roleToConfigAccessibleRole(r)).values()],
joinedAt: member.joinedTimestamp ?? undefined,
guildName: member.guild.name,
};
@ -180,3 +181,21 @@ export function stickerToConfigAccessibleSticker(sticker: Sticker): IConfigAcces
return toReturn;
}
export function getConfigAccessibleMemberLevel(
pluginData: GuildPluginData<any>,
member: IConfigAccessibleMember,
): number {
if (member.id === pluginData.guild.ownerId) {
return 99999;
}
const levels = pluginData.fullConfig.levels ?? {};
for (const [id, level] of Object.entries(levels)) {
if (member.id === id || member.roles?.find(r => r.id === id)) {
return level as number;
}
}
return 0;
}

View file

@ -1,4 +1,4 @@
import { Permissions } from "discord.js";
import { Permissions, PermissionString } from "discord.js";
/**
* @param resolvedPermissions A Permission object from e.g. GuildChannel#permissionsOf() or Member#permission
@ -8,12 +8,14 @@ export function hasDiscordPermissions(
resolvedPermissions: Permissions | Readonly<Permissions> | null,
requiredPermissions: number | bigint,
) {
const allowedPermissions = resolvedPermissions;
const nRequiredPermissions = requiredPermissions;
if (resolvedPermissions == null) {
return false;
}
if (Boolean(allowedPermissions?.bitfield! & Permissions.FLAGS.ADMINISTRATOR)) {
if (resolvedPermissions.has(Permissions.FLAGS.ADMINISTRATOR)) {
return true;
}
return Boolean((allowedPermissions?.bitfield! & BigInt(nRequiredPermissions)) === nRequiredPermissions);
const nRequiredPermissions = BigInt(requiredPermissions);
return Boolean((resolvedPermissions?.bitfield! & nRequiredPermissions) === nRequiredPermissions);
}