DiscordJS-Example/events/channels/voiceStateUpdate.js

87 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-02-07 23:21:53 +00:00
import { ChannelType, Events, PermissionFlagsBits } from 'discord.js';
2024-02-07 18:38:51 +00:00
import { VoiceChannel } from '../../database.js';
2024-02-07 23:21:53 +00:00
const vcPermissionOverwrites = [
PermissionFlagsBits.ManageRoles,
PermissionFlagsBits.ManageChannels,
PermissionFlagsBits.ViewChannel,
PermissionFlagsBits.ModerateMembers,
PermissionFlagsBits.SendMessages,
PermissionFlagsBits.SendMessagesInThreads,
PermissionFlagsBits.ManageMessages,
PermissionFlagsBits.ReadMessageHistory,
PermissionFlagsBits.AddReactions,
PermissionFlagsBits.Connect,
PermissionFlagsBits.Speak,
PermissionFlagsBits.MuteMembers,
PermissionFlagsBits.DeafenMembers,
PermissionFlagsBits.MoveMembers,
PermissionFlagsBits.UseVAD
];
2024-02-08 16:50:32 +00:00
const getChannel = async (member, channels) => {
2024-02-07 19:04:16 +00:00
// Check database for existing channel
const ownCh = await VoiceChannel.findOne({
where: {
owner: member.user.id
}
});
if (ownCh !== null) {
return await channels.fetch(ownCh.id);
}
// Create private channel with all permissions
const name = member.user.username;
const chName = `${name}${name.toLowerCase().endsWith('s') ? "'" : "'s"} channel`;
2024-02-07 19:04:16 +00:00
const privCh = await channels.create({
name: chName,
type: ChannelType.GuildVoice,
permissionOverwrites: [
{
id: member.id,
2024-02-07 23:21:53 +00:00
allow: vcPermissionOverwrites
2024-02-07 19:04:16 +00:00
}
]
});
// Save newly created channel
await VoiceChannel.create({
id: privCh.id,
owner: member.user.id
})
return privCh;
};
export const name = Events.VoiceStateUpdate;
2024-02-07 16:36:00 +00:00
export async function execute(_, state) {
if (!state.channel) return;
2024-02-07 18:38:51 +00:00
// Find channel by id, return if not registered for customs
2024-02-07 19:04:16 +00:00
const createCh = await VoiceChannel.findOne({
2024-02-07 18:38:51 +00:00
where: {
2024-02-07 19:04:16 +00:00
id: state.channel.id,
create: true,
2024-02-07 18:38:51 +00:00
}
});
2024-02-07 19:04:16 +00:00
if (createCh === null) return;
2024-02-07 18:38:51 +00:00
2024-02-07 16:40:29 +00:00
// Extract user data
2024-02-07 16:36:00 +00:00
const member = state.member;
2024-02-07 16:40:29 +00:00
// Extract channel data
2024-02-07 16:36:00 +00:00
const channels = state.guild.channels;
2024-02-07 19:04:16 +00:00
let step = 'create';
2024-02-07 16:40:29 +00:00
try {
2024-02-08 16:50:32 +00:00
const privCh = await getChannel(member, channels);
2024-02-07 19:04:16 +00:00
step = 'move to';
2024-02-07 16:40:29 +00:00
// Move user to private channel
await state.setChannel(privCh);
console.info(`[INFO] User '${name}' created private channel with ID ${privCh.id}.`);
} catch (error) {
console.error(error);
2024-02-07 19:04:16 +00:00
await member.send(`Failed to ${step} channel! Please contact server staff.`);
2024-02-07 16:40:29 +00:00
}
}