feat: add internal role manager plugin; add role buttons plugin
This commit is contained in:
parent
9314d57645
commit
3fe71b3e27
23 changed files with 732 additions and 1 deletions
56
backend/src/plugins/RoleButtons/RoleButtonsPlugin.ts
Normal file
56
backend/src/plugins/RoleButtons/RoleButtonsPlugin.ts
Normal file
|
@ -0,0 +1,56 @@
|
|||
import { zeppelinGuildPlugin } from "../ZeppelinPluginBlueprint";
|
||||
import { ConfigSchema, RoleButtonsPluginType } from "./types";
|
||||
import { mapToPublicFn } from "../../pluginUtils";
|
||||
import { LogsPlugin } from "../Logs/LogsPlugin";
|
||||
import { applyAllRoleButtons } from "./functions/applyAllRoleButtons";
|
||||
import { GuildRoleButtons } from "../../data/GuildRoleButtons";
|
||||
import { RoleManagerPlugin } from "../RoleManager/RoleManagerPlugin";
|
||||
import { StrictValidationError } from "../../validatorUtils";
|
||||
import { onButtonInteraction } from "./events/buttonInteraction";
|
||||
|
||||
export const RoleButtonsPlugin = zeppelinGuildPlugin<RoleButtonsPluginType>()({
|
||||
name: "role_buttons",
|
||||
configSchema: ConfigSchema,
|
||||
|
||||
configPreprocessor(options) {
|
||||
// Auto-fill "name" property for buttons based on the object key
|
||||
const buttonsArray = Array.isArray(options.config?.buttons) ? options.config.buttons : [];
|
||||
const seenMessages = new Set();
|
||||
for (const [name, buttonsConfig] of Object.entries(options.config?.buttons ?? {})) {
|
||||
if (name.length > 16) {
|
||||
throw new StrictValidationError(["Name for role buttons can be at most 16 characters long"]);
|
||||
}
|
||||
|
||||
if (buttonsConfig) {
|
||||
buttonsConfig.name = name;
|
||||
// 5 action rows * 5 buttons
|
||||
if (buttonsConfig.options?.length > 25) {
|
||||
throw new StrictValidationError(["A single message can have at most 25 role buttons"]);
|
||||
}
|
||||
|
||||
if (buttonsConfig.message) {
|
||||
if ("message_id" in buttonsConfig.message) {
|
||||
if (seenMessages.has(buttonsConfig.message.message_id)) {
|
||||
throw new StrictValidationError(["Can't target the same message with two sets of role buttons"]);
|
||||
}
|
||||
seenMessages.add(buttonsConfig.message.message_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
},
|
||||
|
||||
dependencies: () => [LogsPlugin, RoleManagerPlugin],
|
||||
|
||||
events: [onButtonInteraction],
|
||||
|
||||
beforeLoad(pluginData) {
|
||||
pluginData.state.roleButtons = GuildRoleButtons.getGuildInstance(pluginData.guild.id);
|
||||
},
|
||||
|
||||
async afterLoad(pluginData) {
|
||||
await applyAllRoleButtons(pluginData);
|
||||
},
|
||||
});
|
50
backend/src/plugins/RoleButtons/events/buttonInteraction.ts
Normal file
50
backend/src/plugins/RoleButtons/events/buttonInteraction.ts
Normal file
|
@ -0,0 +1,50 @@
|
|||
import { typedGuildEventListener } from "knub";
|
||||
import { RoleButtonsPluginType, TRoleButtonOption } from "../types";
|
||||
import { RoleManagerPlugin } from "../../RoleManager/RoleManagerPlugin";
|
||||
|
||||
export const onButtonInteraction = typedGuildEventListener<RoleButtonsPluginType>()({
|
||||
event: "interactionCreate",
|
||||
async listener({ pluginData, args }) {
|
||||
if (!args.interaction.isButton() || !args.interaction.customId.startsWith("roleButtons:")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const config = pluginData.config.get();
|
||||
const [, name, optionIndex] = args.interaction.customId.split(":");
|
||||
// For some reason TS's type inference fails here so using a type annotation
|
||||
const option: TRoleButtonOption | undefined = config.buttons[name]?.options[optionIndex];
|
||||
if (!option) {
|
||||
args.interaction.reply({
|
||||
ephemeral: true,
|
||||
content: "Invalid option selected",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const member = args.interaction.member || (await pluginData.guild.members.fetch(args.interaction.user.id));
|
||||
if (!member) {
|
||||
args.interaction.reply({
|
||||
ephemeral: true,
|
||||
content: "Error while fetching member to apply roles for",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const hasRole = Array.isArray(member.roles)
|
||||
? member.roles.includes(option.role_id)
|
||||
: member.roles.cache.has(option.role_id);
|
||||
if (hasRole) {
|
||||
pluginData.getPlugin(RoleManagerPlugin).removeRole(member.user.id, option.role_id);
|
||||
args.interaction.reply({
|
||||
ephemeral: true,
|
||||
content: "The selected role will be removed shortly!",
|
||||
});
|
||||
} else {
|
||||
pluginData.getPlugin(RoleManagerPlugin).addRole(member.user.id, option.role_id);
|
||||
args.interaction.reply({
|
||||
ephemeral: true,
|
||||
content: "You will receive the selected role shortly!",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
|
@ -0,0 +1,42 @@
|
|||
import { GuildPluginData } from "knub";
|
||||
import { RoleButtonsPluginType } from "../types";
|
||||
import { createHash } from "crypto";
|
||||
import { applyRoleButtons } from "./applyRoleButtons";
|
||||
|
||||
export async function applyAllRoleButtons(pluginData: GuildPluginData<RoleButtonsPluginType>) {
|
||||
const savedRoleButtons = await pluginData.state.roleButtons.getSavedRoleButtons();
|
||||
const config = pluginData.config.get();
|
||||
for (const buttons of Object.values(config.buttons)) {
|
||||
// Use the hash of the config to quickly check if we need to update buttons
|
||||
const hash = createHash("md5").update(JSON.stringify(buttons)).digest("hex");
|
||||
const savedButtonsItem = savedRoleButtons.find((bt) => bt.name === buttons.name);
|
||||
if (savedButtonsItem?.hash === hash) {
|
||||
// No changes
|
||||
continue;
|
||||
}
|
||||
|
||||
if (savedButtonsItem) {
|
||||
await pluginData.state.roleButtons.deleteRoleButtonItem(buttons.name);
|
||||
}
|
||||
|
||||
const applyResult = await applyRoleButtons(pluginData, buttons, savedButtonsItem ?? null);
|
||||
if (!applyResult) {
|
||||
return;
|
||||
}
|
||||
|
||||
await pluginData.state.roleButtons.saveRoleButtonItem(
|
||||
buttons.name,
|
||||
applyResult.channel_id,
|
||||
applyResult.message_id,
|
||||
hash,
|
||||
);
|
||||
}
|
||||
|
||||
// Remove saved role buttons from the DB that are no longer in the config
|
||||
const savedRoleButtonsToDelete = savedRoleButtons
|
||||
.filter((savedRoleButton) => !config.buttons[savedRoleButton.name])
|
||||
.map((savedRoleButton) => savedRoleButton.name);
|
||||
for (const name of savedRoleButtonsToDelete) {
|
||||
await pluginData.state.roleButtons.deleteRoleButtonItem(name);
|
||||
}
|
||||
}
|
129
backend/src/plugins/RoleButtons/functions/applyRoleButtons.ts
Normal file
129
backend/src/plugins/RoleButtons/functions/applyRoleButtons.ts
Normal file
|
@ -0,0 +1,129 @@
|
|||
import { GuildPluginData } from "knub";
|
||||
import { RoleButtonsPluginType, TRoleButtonsConfigItem } from "../types";
|
||||
import { isSnowflake, snowflakeRegex } from "../../../utils";
|
||||
import { LogsPlugin } from "../../Logs/LogsPlugin";
|
||||
import { Message, MessageButton, MessageEditOptions, MessageOptions, Snowflake } from "discord.js";
|
||||
import { RoleButtonsItem } from "../../../data/entities/RoleButtonsItem";
|
||||
import { splitButtonsIntoRows } from "./splitButtonsIntoRows";
|
||||
|
||||
const channelMessageRegex = new RegExp(`^(${snowflakeRegex.source})-(${snowflakeRegex.source})$`);
|
||||
|
||||
export async function applyRoleButtons(
|
||||
pluginData: GuildPluginData<RoleButtonsPluginType>,
|
||||
configItem: TRoleButtonsConfigItem,
|
||||
existingSavedButtons: RoleButtonsItem | null,
|
||||
): Promise<{ channel_id: string; message_id: string } | null> {
|
||||
let message: Message;
|
||||
|
||||
// Remove existing role buttons, if any
|
||||
if (existingSavedButtons?.channel_id) {
|
||||
const existingChannel = await pluginData.guild.channels.fetch(configItem.message.channel_id);
|
||||
const existingMessage = await (existingChannel?.isText() &&
|
||||
existingChannel.messages.fetch(existingSavedButtons.message_id));
|
||||
if (existingMessage && existingMessage.components.length) {
|
||||
await existingMessage.edit({
|
||||
components: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Find or create message for role buttons
|
||||
if ("message_id" in configItem.message) {
|
||||
// channel id + message id: apply role buttons to existing message
|
||||
const channel = await pluginData.guild.channels.fetch(configItem.message.channel_id);
|
||||
const messageCandidate = await (channel?.isText() && channel.messages.fetch(configItem.message.message_id));
|
||||
if (!messageCandidate) {
|
||||
pluginData.getPlugin(LogsPlugin).logBotAlert({
|
||||
body: `Message not found for role_buttons/${configItem.name}`,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
message = messageCandidate;
|
||||
} else {
|
||||
// channel id + message content: post new message to apply role buttons to
|
||||
const contentIsValid =
|
||||
typeof configItem.message.content === "string"
|
||||
? configItem.message.content.trim() !== ""
|
||||
: Boolean(configItem.message.content.content?.trim()) || configItem.message.content.embeds?.length;
|
||||
if (!contentIsValid) {
|
||||
pluginData.getPlugin(LogsPlugin).logBotAlert({
|
||||
body: `Invalid message content for role_buttons/${configItem.name}`,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const channel = await pluginData.guild.channels.fetch(configItem.message.channel_id);
|
||||
if (!channel || !channel.isText()) {
|
||||
pluginData.getPlugin(LogsPlugin).logBotAlert({
|
||||
body: `Text channel not found for role_buttons/${configItem.name}`,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let candidateMessage: Message | null = null;
|
||||
|
||||
if (existingSavedButtons?.channel_id === configItem.message.channel_id && existingSavedButtons.message_id) {
|
||||
try {
|
||||
candidateMessage = await channel.messages.fetch(existingSavedButtons.message_id);
|
||||
// Make sure message contents are up-to-date
|
||||
const editContent =
|
||||
typeof configItem.message.content === "string"
|
||||
? { content: configItem.message.content }
|
||||
: { ...configItem.message.content };
|
||||
if (!editContent.content) {
|
||||
// Editing with empty content doesn't go through at all for whatever reason, even if there's differences in e.g. the embeds,
|
||||
// so send a space as the content instead. This still functions as if there's no content at all.
|
||||
editContent.content = " ";
|
||||
}
|
||||
await candidateMessage.edit(editContent as MessageEditOptions);
|
||||
} catch (err) {
|
||||
// Message was deleted or is inaccessible. Proceed with reposting it.
|
||||
}
|
||||
}
|
||||
|
||||
if (!candidateMessage) {
|
||||
try {
|
||||
candidateMessage = await channel.send(configItem.message.content as string | MessageOptions);
|
||||
} catch (err) {
|
||||
pluginData.getPlugin(LogsPlugin).logBotAlert({
|
||||
body: `Error while posting message for role_buttons/${configItem.name}`,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
message = candidateMessage;
|
||||
}
|
||||
|
||||
if (message.author.id !== pluginData.client.user?.id) {
|
||||
pluginData.getPlugin(LogsPlugin).logBotAlert({
|
||||
body: `Error applying role buttons for role_buttons/${configItem.name}: target message must be posted by the bot`,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Apply role buttons
|
||||
const buttons = configItem.options.map((opt, index) => {
|
||||
const button = new MessageButton()
|
||||
.setLabel(opt.label ?? "")
|
||||
.setStyle(opt.style ?? "PRIMARY")
|
||||
.setCustomId(`roleButtons:${configItem.name}:${index}:${Math.round(Date.now() / 1000)}`);
|
||||
|
||||
if (opt.emoji) {
|
||||
const emo = pluginData.client.emojis.resolve(opt.emoji as Snowflake) ?? opt.emoji;
|
||||
button.setEmoji(emo);
|
||||
}
|
||||
|
||||
return button;
|
||||
});
|
||||
const rows = splitButtonsIntoRows(buttons);
|
||||
|
||||
await message.edit({
|
||||
components: rows,
|
||||
});
|
||||
|
||||
return {
|
||||
channel_id: message.channelId,
|
||||
message_id: message.id,
|
||||
};
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
import { MessageActionRow, MessageButton } from "discord.js";
|
||||
import { chunkArray } from "../../../utils";
|
||||
|
||||
export function splitButtonsIntoRows(buttons: MessageButton[]): MessageActionRow[] {
|
||||
// Max 5 buttons per row
|
||||
const buttonChunks = chunkArray(buttons, 5);
|
||||
return buttonChunks.map((chunk) => {
|
||||
const row = new MessageActionRow();
|
||||
row.setComponents(chunk);
|
||||
return row;
|
||||
});
|
||||
}
|
48
backend/src/plugins/RoleButtons/types.ts
Normal file
48
backend/src/plugins/RoleButtons/types.ts
Normal file
|
@ -0,0 +1,48 @@
|
|||
import * as t from "io-ts";
|
||||
import { BasePluginType } from "knub";
|
||||
import { tMessageContent, tNullable } from "../../utils";
|
||||
import { GuildRoleButtons } from "../../data/GuildRoleButtons";
|
||||
|
||||
enum ButtonStyles {
|
||||
PRIMARY = 1,
|
||||
SECONDARY = 2,
|
||||
SUCCESS = 3,
|
||||
DANGER = 4,
|
||||
// LINK = 5, We do not want users to create link buttons, but it would be style 5
|
||||
}
|
||||
|
||||
const RoleButtonOption = t.type({
|
||||
role_id: t.string,
|
||||
label: tNullable(t.string),
|
||||
emoji: tNullable(t.string),
|
||||
style: tNullable(t.keyof(ButtonStyles)), // https://discord.js.org/#/docs/discord.js/v13/typedef/MessageButtonStyle
|
||||
});
|
||||
export type TRoleButtonOption = t.TypeOf<typeof RoleButtonOption>;
|
||||
|
||||
const RoleButtonsConfigItem = t.type({
|
||||
name: t.string,
|
||||
message: t.union([
|
||||
t.type({
|
||||
channel_id: t.string,
|
||||
message_id: t.string,
|
||||
}),
|
||||
t.type({
|
||||
channel_id: t.string,
|
||||
content: tMessageContent,
|
||||
}),
|
||||
]),
|
||||
options: t.array(RoleButtonOption),
|
||||
});
|
||||
export type TRoleButtonsConfigItem = t.TypeOf<typeof RoleButtonsConfigItem>;
|
||||
|
||||
export const ConfigSchema = t.type({
|
||||
buttons: t.record(t.string, RoleButtonsConfigItem),
|
||||
});
|
||||
export type TConfigSchema = t.TypeOf<typeof ConfigSchema>;
|
||||
|
||||
export interface RoleButtonsPluginType extends BasePluginType {
|
||||
config: TConfigSchema;
|
||||
state: {
|
||||
roleButtons: GuildRoleButtons;
|
||||
};
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue