DiscordJS-Example/events/channels/voiceStateUpdate.js

71 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-02-07 16:40:29 +00:00
import { ChannelType, Events, PermissionsBitField } from 'discord.js';
2024-02-07 18:38:51 +00:00
import { VoiceChannel } from '../../database.js';
2024-02-07 19:04:16 +00:00
const getchannel = async (member, channels) => {
// 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.endsWith('s') ? "'" : "'s"} channel`;
const privCh = await channels.create({
name: chName,
type: ChannelType.GuildVoice,
permissionOverwrites: [
{
id: member.id,
allow: [
PermissionsBitField.All
]
}
]
});
// 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-07 19:04:16 +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
}
}