clove/inviteTracker
src/commands/invite.ts
/* src/commands/invite.ts */
import {
ChannelType,
type ChatInputCommandInteraction,
type Guild,
PermissionFlagsBits,
SlashCommandBuilder,
} from "discord.js";
import { logInvite } from "../utils/logging.ts";
import { type InviteRecord, saveInvite } from "../utils/storage.ts";
export const inviteCommand = new SlashCommandBuilder()
.setName("invite")
.setDescription("Create a one-use invite to a server channel")
.setDefaultMemberPermissions(PermissionFlagsBits.CreateInstantInvite)
.addChannelOption((option) =>
option.setName("channel")
.setDescription("The channel the invite opens")
.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)
);
export async function issueInvite(
interaction: ChatInputCommandInteraction,
guild: Guild,
records: Map<string, InviteRecord>,
logChannelId: string,
rememberInvite: (code: string) => void,
) {
const channelId = interaction.options.getChannel("channel")?.id ??
interaction.channelId;
const channel = await guild.channels.fetch(channelId);
const requester = await guild.members.fetch(interaction.user.id);
if (
!channel ||
(channel.type !== ChannelType.GuildText &&
channel.type !== ChannelType.GuildAnnouncement) ||
!channel.permissionsFor(requester).has([
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.CreateInstantInvite,
])
) {
await interaction.editReply(
"Choose a text channel where you can view the channel and create invites.",
);
return;
}
const invite = await guild.invites.create(channel, {
maxUses: 1,
maxAge: 0,
unique: true,
reason: `One-use invite requested by ${requester.id}`,
});
try {
await saveInvite(records, invite.code, {
created_by: requester.id,
used_by: "",
});
} catch (error) {
await invite.delete("Could not persist the invite").catch(console.error);
throw error;
}
rememberInvite(invite.code);
const logged = await logInvite(
guild,
logChannelId,
`One-use invite \`${invite.code}\` created by <@${requester.id}> for <#${channel.id}>.`,
).then(() => true).catch((error) => {
console.error(error);
return false;
});
const reply = `One-use invite: ${invite.url}`;
await interaction.editReply(
logged
? reply
: `${reply}\nThe invite was saved, but the Discord log could not be posted.`,
);
}