clove/inviteTracker
src/main.ts
/* src/main.ts */
import {
Client,
Events,
GatewayIntentBits,
MessageFlags,
Routes,
} from "discord.js";
import { infoCommand, replyWithInfo } from "./commands/info.ts";
import { inviteCommand, issueInvite } from "./commands/invite.ts";
import { pingCommand, replyToPing } from "./commands/ping.ts";
import { logInvite } from "./utils/logging.ts";
import { loadInvites, saveInvite } from "./utils/storage.ts";
function requiredEnv(name: string): string {
const value = Deno.env.get(name)?.trim();
if (!value) throw new Error(`Set ${name} in .env`);
return value;
}
const token = requiredEnv("DISCORD_TOKEN");
const applicationId = requiredEnv("DISCORD_CLIENT_ID");
const guildId = requiredEnv("GUILD_ID");
const logChannelId = requiredEnv("LOGGING_CHANNEL_ID");
const records = await loadInvites();
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
});
const guild = () => client.guilds.fetch(guildId);
async function snapshotInvites() {
const server = await guild();
const invites = await server.invites.fetch();
const counts = new Map(
invites.map((invite) => [invite.code, invite.uses ?? 0]),
);
if (server.vanityURLCode) {
const vanity = await server.fetchVanityData();
if (vanity.code) counts.set(vanity.code, vanity.uses);
}
return counts;
}
let previousInvites: Map<string, number> | undefined;
let pending = Promise.resolve();
function enqueue(operation: () => Promise<void>) {
pending = pending.then(operation).catch(console.error);
}
client.on(Events.Error, console.error);
client.once(Events.ClientReady, () => {
enqueue(async () => {
for (const command of [inviteCommand, pingCommand, infoCommand]) {
await client.rest.post(
Routes.applicationGuildCommands(applicationId, guildId),
{ body: command.toJSON() },
);
}
previousInvites = await snapshotInvites();
console.log(`Invite tracker ready for guild ${guildId}`);
});
});
client.on(Events.ShardResume, () => {
enqueue(async () => {
previousInvites = undefined;
previousInvites = await snapshotInvites();
});
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.guildId !== guildId) {
return;
}
try {
switch (interaction.commandName) {
case pingCommand.name:
await replyToPing(interaction);
return;
case infoCommand.name:
await replyWithInfo(interaction, records.size);
return;
case inviteCommand.name:
break;
default:
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
} catch (error) {
console.error(error);
return;
}
enqueue(async () => {
try {
await issueInvite(
interaction,
await guild(),
records,
logChannelId,
(code) => previousInvites?.set(code, 0),
);
} catch (error) {
console.error(error);
if (!interaction.replied) {
await interaction.editReply("Could not create a tracked invite.");
}
}
});
});
const joiningMembers = new Set<string>();
let joinTimer: ReturnType<typeof setTimeout> | undefined;
client.on(Events.GuildMemberAdd, (member) => {
if (member.guild.id !== guildId || member.user.bot) return;
joiningMembers.add(member.id);
if (joinTimer !== undefined) return;
joinTimer = setTimeout(() => {
joinTimer = undefined;
enqueue(async () => {
const currentInvites = await snapshotInvites().catch((error) => {
previousInvites = undefined;
joiningMembers.clear();
throw error;
});
// Include joins received while the invite counts were being fetched.
const members = [...joiningMembers];
joiningMembers.clear();
const before = previousInvites;
previousInvites = currentInvites;
if (members.length === 0 || !before) return;
const changedCodes = new Set<string>();
for (const [code, uses] of currentInvites) {
if (uses > (before.get(code) ?? 0)) changedCodes.add(code);
}
// Discord can remove an exhausted one-use invite from the listing.
for (const code of before.keys()) {
if (!currentInvites.has(code)) changedCodes.add(code);
}
const [code] = changedCodes;
const record = records.get(code);
if (
members.length !== 1 || changedCodes.size !== 1 ||
!record || record.used_by
) {
if (
[...changedCodes].some((code) => records.get(code)?.used_by === "")
) {
await logInvite(
member.guild,
logChannelId,
"A tracked invite changed during a join, but its user could not be determined.",
);
}
return;
}
const [joinedUserId] = members;
await saveInvite(records, code, {
created_by: record.created_by,
used_by: joinedUserId,
});
await logInvite(
member.guild,
logChannelId,
`<@${joinedUserId}> joined with one-use invite \`${code}\` created by <@${record.created_by}>.`,
);
});
}, 750);
});
await client.login(token);