import { entersState, getVoiceConnection, joinVoiceChannel, VoiceConnectionStatus, type VoiceConnection, } from '@discordjs/voice'; import { ActivityType, ChannelType, Client, GatewayIntentBits, PermissionFlagsBits, type Guild, type VoiceBasedChannel } from 'discord.js'; import type { Config } from './config.js'; import type { Store } from './db.js'; import { pickChannel, type Presence } from './follow.js'; import { Recorder } from './recorder.js'; /** * 동의한 사람을 따라 음성채널에 들어가 그 사람 목소리만 녹음하는 봇. * 서버마다 음성 연결은 하나라서, 한 서버 안에서 동의자가 여러 채널에 흩어져 있으면 한 채널만 따라간다 (follow.ts). */ export class FollowBot { readonly client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); private recorders = new Map(); /** 서버별로 순서대로 처리 (들어가는 중에 또 움직여도 꼬이지 않게) */ private queue = new Map>(); constructor( private cfg: Config, private store: Store, ) { this.client.once('clientReady', () => { console.log(`[bot] 로그인: ${this.client.user?.tag}`); this.updatePresence(); for (const g of this.client.guilds.cache.values()) this.schedule(g); }); this.client.on('voiceStateUpdate', (oldS, newS) => { const me = this.client.user?.id; // 누가 봇을 끊거나 다른 채널로 옮김: 정리하고 다시 판단 (동의자가 있는 채널로 돌아감) const rec = this.recorders.get(newS.guild.id); if (newS.id === me && rec && newS.channelId !== rec.channelId) this.drop(newS.guild.id); if (newS.id === me || this.store.isConsentedIn(newS.id, newS.guild.id) || this.recorders.has(newS.guild.id)) { if (oldS.channelId && oldS.channelId !== newS.channelId) this.recorders.get(oldS.guild.id)?.stopUser(newS.id); this.schedule(newS.guild, newS.id); } }); this.client.on('guildCreate', (g) => this.schedule(g)); } async start(): Promise { await this.client.login(this.cfg.botToken); } async stop(): Promise { for (const gid of [...this.recorders.keys()]) this.drop(gid); for (const g of this.client.guilds.cache.values()) getVoiceConnection(g.id)?.destroy(); await this.client.destroy(); } /** 사이트에서 동의 · 철회 · 녹음할 서버를 바꾼 직후: 그 사람이 있는 서버를 바로 다시 판단 */ consentChanged(userId: string): void { for (const [gid, r] of this.recorders) if (!this.store.isConsentedIn(userId, gid)) r.stopUser(userId); for (const g of this.client.guilds.cache.values()) { if (g.voiceStates.cache.get(userId)?.channelId || this.recorders.has(g.id)) this.schedule(g, userId); } } /** 이 사람의 진행 중인 녹음을 버린다 (구독도 끊음. 다시 말하면 동의 상태대로 새로 녹음) */ discardActive(userId: string): void { for (const r of this.recorders.values()) r.stopUser(userId); } /** 봇이 들어가 있고 이 사람도 들어가 있는 서버 (사이트에서 녹음할 서버로 고를 수 있는 곳) */ async userGuilds(userId: string): Promise<{ id: string; name: string }[]> { const guilds = [...this.client.guilds.cache.values()].filter((g) => this.allowedGuild(g)); const found = await Promise.all( guilds.map((g) => g.members.fetch(userId).then( () => ({ id: g.id, name: g.name }), () => null, // 이 서버에 없는 사람 (Unknown Member) ), ), ); return found.filter((g): g is { id: string; name: string } => !!g).sort((a, b) => a.name.localeCompare(b.name, 'ko')); } /** 이 사람을 지금 녹음 중인 채널 이름 */ recordingNow(userId: string): string | null { for (const [gid, r] of this.recorders) { const g = this.client.guilds.cache.get(gid); if (!this.store.isConsentedIn(userId, gid)) continue; // 이 서버는 녹음하지 않기로 한 사람 (다른 동의자를 녹음 중인 채널에 같이 있어도) if (g?.voiceStates.cache.get(userId)?.channelId === r.channelId) return g.channels.cache.get(r.channelId)?.name ?? '음성채널'; } return null; } private schedule(guild: Guild, preferUserId?: string): void { const prev = this.queue.get(guild.id) ?? Promise.resolve(); const next = prev.then(() => this.reconcile(guild, preferUserId)).catch((e) => console.error(`[bot] ${guild.name} 처리 오류`, e)); this.queue.set(guild.id, next); } /** .env 의 ALLOWED_GUILD_IDS 안에 있고, 운영자가 앱에서 끄지 않은 서버 */ private allowedGuild(guild: Guild): boolean { return (!this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id)) && this.store.guildEnabled(guild.id); } /** 운영자가 켜고 끌 수 있는 서버 (봇이 들어가 있고 ALLOWED_GUILD_IDS 안에 있는 곳) */ adminGuilds(): { id: string; name: string; enabled: boolean }[] { return [...this.client.guilds.cache.values()] .filter((g) => !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(g.id)) .map((g) => ({ id: g.id, name: g.name, enabled: this.store.guildEnabled(g.id) })) .sort((a, b) => a.name.localeCompare(b.name, 'ko')); } /** 운영자가 서버를 켜고 끈 직후: 끈 서버에서는 바로 나가고, 켠 서버에는 동의자가 있으면 따라 들어간다 */ guildSettingsChanged(): void { for (const g of this.client.guilds.cache.values()) this.schedule(g); } private canJoin(ch: VoiceBasedChannel): boolean { const me = ch.guild.members.me; if (!me || ch.type === ChannelType.GuildStageVoice) return false; const p = ch.permissionsFor(me); return !!p?.has(PermissionFlagsBits.ViewChannel) && p.has(PermissionFlagsBits.Connect) && ch.joinable; } /** * 동의자가 있는 채널 목록. 봇이 이미 들어가 있는 채널은 입장 가능 여부를 다시 보지 않는다 * (봇이 들어가 정원이 차면 joinable 이 false 가 되어 나갔다 들어오기를 반복하던 것) */ consentedPresence(guild: Guild): Presence[] { const current = this.recorders.get(guild.id)?.channelId ?? null; const out: Presence[] = []; for (const vs of guild.voiceStates.cache.values()) { if (!vs.channelId || vs.id === this.client.user?.id || vs.member?.user.bot) continue; if (!this.store.isConsentedIn(vs.id, guild.id)) continue; const ch = vs.channel; if (ch && (ch.id === current || this.canJoin(ch))) out.push({ userId: vs.id, channelId: vs.channelId }); } return out; } private async reconcile(guild: Guild, preferUserId?: string): Promise { const current = this.recorders.get(guild.id)?.channelId ?? null; const want = this.allowedGuild(guild) ? pickChannel(current, this.consentedPresence(guild), preferUserId) : null; if (want === current) return; this.drop(guild.id); if (!want) { console.log(`[bot] ${guild.name}: 동의한 사람이 없어 나감`); this.updatePresence(); return; } const ch = guild.channels.cache.get(want) as VoiceBasedChannel | undefined; if (!ch) return; console.log(`[bot] ${guild.name}: "${ch.name}" 채널로 따라 들어감`); const conn = joinVoiceChannel({ channelId: ch.id, guildId: guild.id, adapterCreator: guild.voiceAdapterCreator, selfDeaf: false, // 들어야 녹음할 수 있다 selfMute: true, daveEncryption: true, }); try { await entersState(conn, VoiceConnectionStatus.Ready, 20_000); } catch (e) { console.error(`[bot] ${guild.name}: 음성채널 연결 실패`, e); conn.destroy(); return; } this.watch(guild, conn); const rec = new Recorder(this.store, this.cfg.dataDir, conn, guild.id, ch.id, (uid) => { return guild.voiceStates.cache.get(uid)?.channelId === ch.id && this.store.isConsentedIn(uid, guild.id); }); this.recorders.set(guild.id, rec); this.updatePresence(); if (this.cfg.channelNotice) await this.notice(ch); } private watch(guild: Guild, conn: VoiceConnection): void { conn.on('error', (e) => console.error('[bot] 음성 연결 오류', e)); conn.on(VoiceConnectionStatus.Disconnected, async () => { try { await Promise.race([ entersState(conn, VoiceConnectionStatus.Signalling, 5_000), entersState(conn, VoiceConnectionStatus.Connecting, 5_000), ]); } catch { // 강퇴 · 채널 삭제 등: 정리하고 다시 판단 (동의자가 남아 있으면 다시 따라감) if (getVoiceConnection(guild.id) === conn) conn.destroy(); this.drop(guild.id); this.schedule(guild); } }); } /** 음성채널 채팅에 녹음 안내 (권한이 없으면 건너뜀) */ private async notice(ch: VoiceBasedChannel): Promise { const ids = this.consentedPresence(ch.guild).filter((p) => p.channelId === ch.id).map((p) => `<@${p.userId}>`); const text = `🔴 **녹음 안내** — 이 채널에서 녹음에 동의한 사람(${ids.join(', ') || '동의자'})의 목소리만 따로 녹음합니다. ` + `다른 분의 목소리는 녹음하지 않습니다. 동의 확인 · 철회: ${this.cfg.publicUrl}`; try { if ('send' in ch && typeof ch.send === 'function') await ch.send({ content: text, allowedMentions: { parse: [] } }); } catch (e: any) { console.warn(`[bot] 녹음 안내를 남기지 못함 (${ch.name}): ${e?.message ?? e}`); } } private drop(guildId: string): void { const r = this.recorders.get(guildId); if (!r) return; r.close(); this.recorders.delete(guildId); getVoiceConnection(guildId)?.destroy(); } private updatePresence(): void { const recording = this.recorders.size > 0; this.client.user?.setPresence({ status: recording ? 'dnd' : 'online', activities: [{ type: ActivityType.Custom, name: recording ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중', state: recording ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중' }], }); } }