Add consent site + consent-only follow recorder bot
Discord OAuth login -> explicit consent (3 checkboxes, versioned text) -> bot follows consenting users into voice channels and records only their per-user streams. Revoke stops recording immediately and optionally deletes files; consent log kept; export to training wav only for active consents. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
183
consent-recorder/src/bot.ts
Normal file
183
consent-recorder/src/bot.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
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<string, Recorder>();
|
||||
/** 서버별로 순서대로 처리 (들어가는 중에 또 움직여도 꼬이지 않게) */
|
||||
private queue = new Map<string, Promise<void>>();
|
||||
|
||||
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.isConsented(newS.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<void> {
|
||||
await this.client.login(this.cfg.botToken);
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
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 r of this.recorders.values()) if (!this.store.isConsented(userId)) 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);
|
||||
}
|
||||
}
|
||||
|
||||
/** 이 사람을 지금 녹음 중인 채널 이름 */
|
||||
recordingNow(userId: string): string | null {
|
||||
for (const [gid, r] of this.recorders) {
|
||||
const g = this.client.guilds.cache.get(gid);
|
||||
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);
|
||||
}
|
||||
|
||||
private allowedGuild(guild: Guild): boolean {
|
||||
return !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private consentedPresence(guild: Guild): Presence[] {
|
||||
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.isConsented(vs.id)) continue;
|
||||
const ch = vs.channel;
|
||||
if (ch && this.canJoin(ch)) out.push({ userId: vs.id, channelId: vs.channelId });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private async reconcile(guild: Guild, preferUserId?: string): Promise<void> {
|
||||
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.isConsented(uid);
|
||||
});
|
||||
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<void> {
|
||||
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 ? '🔴 동의한 사람 녹음 중' : '🎙️ 대기 중' }],
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user