fix: Starboard
This commit is contained in:
@@ -214,11 +214,17 @@ export async function routeCommand(interaction: ChatInputCommandInteraction, con
|
||||
moduleId
|
||||
);
|
||||
if (!enabled) {
|
||||
await interaction.reply({
|
||||
content: t(locale, 'generic.moduleDisabled'),
|
||||
ephemeral: true
|
||||
});
|
||||
return;
|
||||
// Allow first-time setup while the module is still disabled (chicken-egg).
|
||||
const sub = interaction.options.getSubcommand(false);
|
||||
const isBootstrapSetup =
|
||||
interaction.commandName === 'starboard' && sub === 'setup';
|
||||
if (!isBootstrapSetup) {
|
||||
await interaction.reply({
|
||||
content: t(locale, 'generic.moduleDisabled'),
|
||||
ephemeral: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { ChannelType } from 'discord.js';
|
||||
import { ChannelType, PermissionFlagsBits } from 'discord.js';
|
||||
import { applyCommandDescription, applyOptionDescription } from '@nexumi/shared';
|
||||
import { SlashCommandBuilder } from 'discord.js';
|
||||
|
||||
export const starboardCommandData = applyCommandDescription(
|
||||
new SlashCommandBuilder()
|
||||
.setName('starboard')
|
||||
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
|
||||
.addSubcommand((s) =>
|
||||
applyCommandDescription(s.setName('setup'), 'starboard.setup.description')
|
||||
.addChannelOption((o) =>
|
||||
applyOptionDescription(
|
||||
o.setName('channel').addChannelTypes(ChannelType.GuildText).setRequired(true),
|
||||
o
|
||||
.setName('channel')
|
||||
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)
|
||||
.setRequired(true),
|
||||
'starboard.setup.options.channel'
|
||||
)
|
||||
)
|
||||
@@ -28,6 +32,9 @@ export const starboardCommandData = applyCommandDescription(
|
||||
'starboard.setup.options.allow_self_star'
|
||||
)
|
||||
)
|
||||
)
|
||||
.addSubcommand((s) =>
|
||||
applyCommandDescription(s.setName('status'), 'starboard.status.description')
|
||||
),
|
||||
'starboard.description'
|
||||
);
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { PermissionFlagsBits } from 'discord.js';
|
||||
import { t } from '@nexumi/shared';
|
||||
import { t, tf } from '@nexumi/shared';
|
||||
import type { SlashCommand } from '../../types.js';
|
||||
import { getGuildLocale } from '../../i18n.js';
|
||||
import { requirePermission } from '../../permissions.js';
|
||||
import { ephemeral } from '../../interaction-reply.js';
|
||||
import { starboardCommandData } from './command-definitions.js';
|
||||
import { getStarboardConfig, updateStarboardConfig } from './service.js';
|
||||
import { botCanPostStarboard, getStarboardConfig, updateStarboardConfig } from './service.js';
|
||||
|
||||
const starboardCommand: SlashCommand = {
|
||||
data: starboardCommandData,
|
||||
async execute(interaction, context) {
|
||||
const locale = await getGuildLocale(context.prisma, interaction.guildId);
|
||||
if (!interaction.inGuild()) {
|
||||
await interaction.reply({ content: t(locale, 'generic.guildOnly'), ephemeral: true });
|
||||
await interaction.reply({ content: t(locale, 'generic.guildOnly'), ...ephemeral() });
|
||||
return;
|
||||
}
|
||||
if (!(await requirePermission(interaction, PermissionFlagsBits.ManageGuild, locale))) {
|
||||
@@ -22,11 +23,21 @@ const starboardCommand: SlashCommand = {
|
||||
const sub = interaction.options.getSubcommand();
|
||||
|
||||
if (sub === 'setup') {
|
||||
const channel = interaction.options.getChannel('channel', true);
|
||||
const channelOption = interaction.options.getChannel('channel', true);
|
||||
const threshold = interaction.options.getInteger('threshold', true);
|
||||
const emoji = interaction.options.getString('emoji') ?? '⭐';
|
||||
const allowSelfStar = interaction.options.getBoolean('allow_self_star') ?? false;
|
||||
|
||||
const channel = await interaction.guild!.channels.fetch(channelOption.id).catch(() => null);
|
||||
const me = interaction.guild!.members.me;
|
||||
if (!channel || !me || !botCanPostStarboard(channel, me.id)) {
|
||||
await interaction.reply({
|
||||
content: t(locale, 'starboard.invalidChannel'),
|
||||
...ephemeral()
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await updateStarboardConfig(context.prisma, guildId, {
|
||||
enabled: true,
|
||||
channelId: channel.id,
|
||||
@@ -35,13 +46,30 @@ const starboardCommand: SlashCommand = {
|
||||
allowSelfStar
|
||||
});
|
||||
|
||||
await interaction.reply({ content: t(locale, 'starboard.setupDone'), ephemeral: true });
|
||||
await interaction.reply({ content: t(locale, 'starboard.setupDone'), ...ephemeral() });
|
||||
return;
|
||||
}
|
||||
|
||||
const config = await getStarboardConfig(context.prisma, guildId);
|
||||
if (!config.enabled || !config.channelId) {
|
||||
await interaction.reply({ content: t(locale, 'starboard.notConfigured'), ephemeral: true });
|
||||
if (sub === 'status') {
|
||||
const config = await getStarboardConfig(context.prisma, guildId);
|
||||
if (!config.enabled || !config.channelId) {
|
||||
await interaction.reply({
|
||||
content: t(locale, 'starboard.notConfigured'),
|
||||
...ephemeral()
|
||||
});
|
||||
return;
|
||||
}
|
||||
await interaction.reply({
|
||||
content: tf(locale, 'starboard.statusLine', {
|
||||
channel: `<#${config.channelId}>`,
|
||||
emoji: config.emoji,
|
||||
threshold: String(config.threshold),
|
||||
selfStar: config.allowSelfStar
|
||||
? t(locale, 'starboard.selfStarOn')
|
||||
: t(locale, 'starboard.selfStarOff')
|
||||
}),
|
||||
...ephemeral()
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { Message, PartialMessage } from 'discord.js';
|
||||
import type { BotContext } from '../../types.js';
|
||||
import { logger } from '../../logger.js';
|
||||
import { processStarboardReaction } from './service.js';
|
||||
import {
|
||||
processStarboardReaction,
|
||||
processStarboardSourceDelete,
|
||||
processStarboardSourceUpdate
|
||||
} from './service.js';
|
||||
|
||||
export function registerStarboardEvents(context: BotContext): void {
|
||||
const handleReaction = async (
|
||||
@@ -26,4 +31,48 @@ export function registerStarboardEvents(context: BotContext): void {
|
||||
}
|
||||
await handleReaction(_reaction);
|
||||
});
|
||||
|
||||
context.client.on('messageReactionRemoveAll', async (message) => {
|
||||
try {
|
||||
if (message.partial) {
|
||||
await message.fetch().catch(() => null);
|
||||
}
|
||||
if (!message.guild || !('author' in message) || !message.author) {
|
||||
return;
|
||||
}
|
||||
await processStarboardSourceUpdate(context, message as Message | PartialMessage);
|
||||
} catch (error) {
|
||||
logger.warn({ error }, 'Starboard remove-all handler failed');
|
||||
}
|
||||
});
|
||||
|
||||
context.client.on('messageReactionRemoveEmoji', async (reaction) => {
|
||||
await handleReaction(reaction);
|
||||
});
|
||||
|
||||
context.client.on('messageDelete', async (message) => {
|
||||
try {
|
||||
await processStarboardSourceDelete(context, message);
|
||||
} catch (error) {
|
||||
logger.warn({ error }, 'Starboard source-delete handler failed');
|
||||
}
|
||||
});
|
||||
|
||||
context.client.on('messageDeleteBulk', async (messages) => {
|
||||
for (const message of messages.values()) {
|
||||
try {
|
||||
await processStarboardSourceDelete(context, message);
|
||||
} catch (error) {
|
||||
logger.warn({ error }, 'Starboard bulk-delete handler failed');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
context.client.on('messageUpdate', async (_oldMessage, newMessage) => {
|
||||
try {
|
||||
await processStarboardSourceUpdate(context, newMessage);
|
||||
} catch (error) {
|
||||
logger.warn({ error }, 'Starboard source-update handler failed');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
85
apps/bot/src/modules/starboard/service.test.ts
Normal file
85
apps/bot/src/modules/starboard/service.test.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { emojiMatches, shouldIgnoreMessage } from './service.js';
|
||||
|
||||
function reactionEmoji(partial: { id?: string | null; name?: string | null }) {
|
||||
return {
|
||||
id: partial.id ?? null,
|
||||
name: partial.name ?? null,
|
||||
identifier: partial.id ? `${partial.name}:${partial.id}` : (partial.name ?? ''),
|
||||
toString() {
|
||||
if (partial.id) {
|
||||
return `<:${partial.name}:${partial.id}>`;
|
||||
}
|
||||
return partial.name ?? '';
|
||||
}
|
||||
} as unknown as import('discord.js').Emoji;
|
||||
}
|
||||
|
||||
describe('starboard emojiMatches', () => {
|
||||
it('matches unicode emoji', () => {
|
||||
expect(emojiMatches('⭐', reactionEmoji({ name: '⭐' }))).toBe(true);
|
||||
});
|
||||
|
||||
it('matches custom emoji forms', () => {
|
||||
const emoji = reactionEmoji({ id: '123', name: 'star' });
|
||||
expect(emojiMatches('<:star:123>', emoji)).toBe(true);
|
||||
expect(emojiMatches('star:123', emoji)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('starboard shouldIgnoreMessage', () => {
|
||||
const baseConfig = {
|
||||
id: 'cfg',
|
||||
guildId: 'g1',
|
||||
enabled: true,
|
||||
channelId: 'star-channel',
|
||||
emoji: '⭐',
|
||||
threshold: 3,
|
||||
allowSelfStar: false,
|
||||
ignoredChannelIds: ['ignored'],
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date()
|
||||
};
|
||||
|
||||
it('ignores bot authors', () => {
|
||||
const message = {
|
||||
author: { bot: true },
|
||||
guild: { id: 'g1' },
|
||||
channel: {
|
||||
id: 'c1',
|
||||
isTextBased: () => true,
|
||||
isDMBased: () => false,
|
||||
nsfw: false
|
||||
}
|
||||
} as unknown as import('discord.js').Message;
|
||||
expect(shouldIgnoreMessage(message, baseConfig)).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores the starboard channel itself', () => {
|
||||
const message = {
|
||||
author: { bot: false, id: 'u1' },
|
||||
guild: { id: 'g1' },
|
||||
channel: {
|
||||
id: 'star-channel',
|
||||
isTextBased: () => true,
|
||||
isDMBased: () => false,
|
||||
nsfw: false
|
||||
}
|
||||
} as unknown as import('discord.js').Message;
|
||||
expect(shouldIgnoreMessage(message, baseConfig)).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores listed channels', () => {
|
||||
const message = {
|
||||
author: { bot: false, id: 'u1' },
|
||||
guild: { id: 'g1' },
|
||||
channel: {
|
||||
id: 'ignored',
|
||||
isTextBased: () => true,
|
||||
isDMBased: () => false,
|
||||
nsfw: false
|
||||
}
|
||||
} as unknown as import('discord.js').Message;
|
||||
expect(shouldIgnoreMessage(message, baseConfig)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,17 @@
|
||||
import {
|
||||
ChannelType,
|
||||
EmbedBuilder,
|
||||
PermissionFlagsBits,
|
||||
type Emoji,
|
||||
type GuildBasedChannel,
|
||||
type Message,
|
||||
type PartialMessage,
|
||||
type PartialMessageReaction,
|
||||
type MessageReaction,
|
||||
type TextChannel
|
||||
} from 'discord.js';
|
||||
import type { PrismaClient, StarboardConfig } from '@prisma/client';
|
||||
import { t } from '@nexumi/shared';
|
||||
import type { Locale } from '@nexumi/shared';
|
||||
import { t, type Locale } from '@nexumi/shared';
|
||||
import { ensureGuild } from '../../guild.js';
|
||||
import { logger } from '../../logger.js';
|
||||
import type { BotContext } from '../../types.js';
|
||||
@@ -73,6 +76,27 @@ export function shouldIgnoreMessage(message: Message, config: StarboardConfig):
|
||||
return false;
|
||||
}
|
||||
|
||||
export function botCanPostStarboard(channel: GuildBasedChannel, meId: string): channel is TextChannel {
|
||||
if (!channel.isTextBased() || channel.isDMBased()) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
channel.type !== ChannelType.GuildText &&
|
||||
channel.type !== ChannelType.GuildAnnouncement
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const permissions = channel.permissionsFor(meId);
|
||||
if (!permissions) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
permissions.has(PermissionFlagsBits.ViewChannel) &&
|
||||
permissions.has(PermissionFlagsBits.SendMessages) &&
|
||||
permissions.has(PermissionFlagsBits.EmbedLinks)
|
||||
);
|
||||
}
|
||||
|
||||
export async function countMatchingStars(
|
||||
message: Message,
|
||||
config: StarboardConfig
|
||||
@@ -109,6 +133,10 @@ function resolveImageUrl(message: Message): string | undefined {
|
||||
return embedImage ?? undefined;
|
||||
}
|
||||
|
||||
function authorDisplayName(message: Message): string {
|
||||
return message.member?.displayName || message.author.displayName || message.author.username;
|
||||
}
|
||||
|
||||
export function buildStarboardEmbed(
|
||||
message: Message,
|
||||
starCount: number,
|
||||
@@ -119,7 +147,7 @@ export function buildStarboardEmbed(
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(0x6366f1)
|
||||
.setAuthor({
|
||||
name: message.author.tag,
|
||||
name: authorDisplayName(message),
|
||||
iconURL: message.author.displayAvatarURL()
|
||||
})
|
||||
.setDescription(content.slice(0, 4096))
|
||||
@@ -143,6 +171,17 @@ export function buildStarboardEmbed(
|
||||
return embed;
|
||||
}
|
||||
|
||||
async function fetchStarboardTextChannel(
|
||||
context: BotContext,
|
||||
channelId: string
|
||||
): Promise<TextChannel | null> {
|
||||
const channel = await context.client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel || !channel.isTextBased() || channel.isDMBased()) {
|
||||
return null;
|
||||
}
|
||||
return channel as TextChannel;
|
||||
}
|
||||
|
||||
async function removeStarboardEntry(context: BotContext, entryId: string): Promise<void> {
|
||||
const entry = await context.prisma.starboardEntry.findUnique({ where: { id: entryId } });
|
||||
if (!entry) {
|
||||
@@ -152,9 +191,13 @@ async function removeStarboardEntry(context: BotContext, entryId: string): Promi
|
||||
try {
|
||||
const config = await getStarboardConfig(context.prisma, entry.guildId);
|
||||
if (config.channelId) {
|
||||
const channel = (await context.client.channels.fetch(config.channelId)) as TextChannel;
|
||||
const starboardMessage = await channel.messages.fetch(entry.starboardMessageId).catch(() => null);
|
||||
await starboardMessage?.delete().catch(() => undefined);
|
||||
const channel = await fetchStarboardTextChannel(context, config.channelId);
|
||||
if (channel) {
|
||||
const starboardMessage = await channel.messages
|
||||
.fetch(entry.starboardMessageId)
|
||||
.catch(() => null);
|
||||
await starboardMessage?.delete().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn({ error, entryId }, 'Failed to delete starboard message');
|
||||
@@ -163,6 +206,82 @@ async function removeStarboardEntry(context: BotContext, entryId: string): Promi
|
||||
await context.prisma.starboardEntry.delete({ where: { id: entryId } }).catch(() => undefined);
|
||||
}
|
||||
|
||||
export async function removeStarboardEntryBySource(
|
||||
context: BotContext,
|
||||
guildId: string,
|
||||
sourceMessageId: string
|
||||
): Promise<void> {
|
||||
const entry = await context.prisma.starboardEntry.findUnique({
|
||||
where: {
|
||||
guildId_sourceMessageId: { guildId, sourceMessageId }
|
||||
}
|
||||
});
|
||||
if (entry) {
|
||||
await removeStarboardEntry(context, entry.id);
|
||||
}
|
||||
}
|
||||
|
||||
async function createOrRecreateStarboardPost(
|
||||
context: BotContext,
|
||||
message: Message,
|
||||
config: StarboardConfig,
|
||||
locale: Locale,
|
||||
starCount: number,
|
||||
starboardChannel: TextChannel,
|
||||
existingId?: string
|
||||
): Promise<void> {
|
||||
const embed = buildStarboardEmbed(message, starCount, config, locale);
|
||||
const starboardMessage = await starboardChannel.send({ embeds: [embed] });
|
||||
|
||||
if (existingId) {
|
||||
await context.prisma.starboardEntry.update({
|
||||
where: { id: existingId },
|
||||
data: {
|
||||
starboardMessageId: starboardMessage.id,
|
||||
starCount,
|
||||
sourceChannelId: message.channel.id
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await context.prisma.starboardEntry.create({
|
||||
data: {
|
||||
guildId: message.guild!.id,
|
||||
sourceChannelId: message.channel.id,
|
||||
sourceMessageId: message.id,
|
||||
starboardMessageId: starboardMessage.id,
|
||||
starCount
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
// Race: another reaction created the row first — keep the newer post, drop ours.
|
||||
logger.warn({ error, messageId: message.id }, 'Starboard entry create raced; cleaning up');
|
||||
await starboardMessage.delete().catch(() => undefined);
|
||||
const winner = await context.prisma.starboardEntry.findUnique({
|
||||
where: {
|
||||
guildId_sourceMessageId: {
|
||||
guildId: message.guild!.id,
|
||||
sourceMessageId: message.id
|
||||
}
|
||||
}
|
||||
});
|
||||
if (winner) {
|
||||
await context.prisma.starboardEntry.update({
|
||||
where: { id: winner.id },
|
||||
data: { starCount }
|
||||
});
|
||||
const existingMsg = await starboardChannel.messages
|
||||
.fetch(winner.starboardMessageId)
|
||||
.catch(() => null);
|
||||
if (existingMsg) {
|
||||
await existingMsg.edit({ embeds: [embed] }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function processStarboardMessage(context: BotContext, message: Message): Promise<void> {
|
||||
if (!message.guild) {
|
||||
return;
|
||||
@@ -194,8 +313,13 @@ export async function processStarboardMessage(context: BotContext, message: Mess
|
||||
return;
|
||||
}
|
||||
|
||||
const starboardChannel = await fetchStarboardTextChannel(context, config.channelId);
|
||||
if (!starboardChannel) {
|
||||
logger.warn({ guildId: message.guild.id, channelId: config.channelId }, 'Starboard channel missing');
|
||||
return;
|
||||
}
|
||||
|
||||
const embed = buildStarboardEmbed(message, starCount, config, locale);
|
||||
const starboardChannel = (await context.client.channels.fetch(config.channelId)) as TextChannel;
|
||||
|
||||
if (existing) {
|
||||
try {
|
||||
@@ -206,21 +330,28 @@ export async function processStarboardMessage(context: BotContext, message: Mess
|
||||
data: { starCount }
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn({ error, messageId: message.id }, 'Failed to update starboard message');
|
||||
logger.warn({ error, messageId: message.id }, 'Starboard message missing; recreating');
|
||||
await createOrRecreateStarboardPost(
|
||||
context,
|
||||
message,
|
||||
config,
|
||||
locale,
|
||||
starCount,
|
||||
starboardChannel,
|
||||
existing.id
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const starboardMessage = await starboardChannel.send({ embeds: [embed] });
|
||||
await context.prisma.starboardEntry.create({
|
||||
data: {
|
||||
guildId: message.guild.id,
|
||||
sourceChannelId: message.channel.id,
|
||||
sourceMessageId: message.id,
|
||||
starboardMessageId: starboardMessage.id,
|
||||
starCount
|
||||
}
|
||||
});
|
||||
await createOrRecreateStarboardPost(
|
||||
context,
|
||||
message,
|
||||
config,
|
||||
locale,
|
||||
starCount,
|
||||
starboardChannel
|
||||
);
|
||||
}
|
||||
|
||||
export async function processStarboardReaction(
|
||||
@@ -249,3 +380,41 @@ export async function processStarboardReaction(
|
||||
|
||||
await processStarboardMessage(context, message as Message);
|
||||
}
|
||||
|
||||
export async function processStarboardSourceDelete(
|
||||
context: BotContext,
|
||||
message: Message | PartialMessage
|
||||
): Promise<void> {
|
||||
if (!message.guildId || !message.id) {
|
||||
return;
|
||||
}
|
||||
await removeStarboardEntryBySource(context, message.guildId, message.id);
|
||||
}
|
||||
|
||||
export async function processStarboardSourceUpdate(
|
||||
context: BotContext,
|
||||
message: Message | PartialMessage
|
||||
): Promise<void> {
|
||||
if (!message.guildId || !message.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const entry = await context.prisma.starboardEntry.findUnique({
|
||||
where: {
|
||||
guildId_sourceMessageId: {
|
||||
guildId: message.guildId,
|
||||
sourceMessageId: message.id
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
const full = message.partial ? await message.fetch().catch(() => null) : message;
|
||||
if (!full || !full.guild) {
|
||||
return;
|
||||
}
|
||||
|
||||
await processStarboardMessage(context, full as Message);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user