Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement automatic voice channel joining #32

Merged
merged 10 commits into from
Sep 2, 2023
26 changes: 23 additions & 3 deletions src_modules/voice_commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// extcord module
// requires fastest-levenshtein@^1.0.16 lru-cache@^10.0.1

import { GatewayIntentBits, Guild, VoiceState } from "discord.js";
import { GatewayIntentBits, Guild, VoiceState, VoiceChannel } from "discord.js";
import { VoiceConnection } from "@discordjs/voice";

import { BooleanGuildConfigEntry, Bot, Logger, Module, NumberConfigEntry, SimplePhrase, StringConfigEntry } from "../..";
import { BooleanGuildConfigEntry, Bot, Logger, Module, SimplePhrase, StringConfigEntry, NumberConfigEntry } from "../..";

import { GuildListener } from "./GuildListener";
import { VoiceBackendClient } from "./VoiceBackendClient";
Expand Down Expand Up @@ -139,12 +140,27 @@ export default class VoiceCommandsModule extends Module {
}

private async onVoiceStateUpdate(oldState: VoiceState, newState: VoiceState) {
if (oldState.channel === null && newState.channel !== null && newState.channel instanceof VoiceChannel && !newState.member?.user.bot) {
const channel = newState.channel;

// Someone joined a voice channel
const nonBotUsers = channel.members.filter(member => !member.user.bot);
if (nonBotUsers.size > 0 && this.bot.voice.getConnection(channel.guild) === undefined) {
setTimeout(async () => {
const nonBotUsers = channel.members.filter(member => !member.user.bot);
if (nonBotUsers.size > 0 && this.bot.voice.getConnection(channel.guild) === undefined) {
await this.getConnection(this.bot, channel);
}
}, 5000);
}
}

if (oldState.id !== this.bot.client!.user!.id || newState.id !== this.bot.client!.user!.id) {
return;
}

if (oldState.channel === null && newState.channel !== null) {
// joined a channel
// Bot joined a channel
const listener = await this.getListener(newState.guild);
const connection = this.bot.voice.getConnection(newState.guild);

Expand All @@ -155,6 +171,10 @@ export default class VoiceCommandsModule extends Module {
}
}

private async getConnection(bot: Bot, voiceChannel: VoiceChannel): Promise<VoiceConnection> {
return bot.voice.getOrCreateConnection(voiceChannel);
}

private onReady() {
if (this.voiceStateUpdateHandler !== undefined) {
this.bot.client!.removeListener("voiceStateUpdate", this.voiceStateUpdateHandler);
Expand Down