앱 v1.2.1: 겜녹이 봇 토큰을 앱에 보내지 않고 사이트 서버가 봇을 대신 연결

- 사이트 서버: discord.js 로 디스코드 게이트웨이에 한 번 붙고(discord-source.ts), 로그인한 앱에 WS /app/bot/ws 로 중계(bot-broker.ts)
  · 앱이 보낸 op 4 는 지켜보는 서버의 음성채널 참여 · 나가기만 허용하고 필드를 다시 만들어 보낸다
  · 디스코드가 준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)는 음성을 가진 앱에만 넘긴다. 음성은 앱 ↔ 디스코드로 바로
  · 한 서버의 봇 음성은 마지막으로 요청한 앱이 가져가고 이전 앱은 taken. 이전 앱의 늦은 나가기 무시, 음성 가진 앱이 끊기면 봇을 뺀다
  · 슬래시 명령은 서버가 받아 defer 후 그 서버를 지켜보는 앱으로 보낸다
  · 등록 해제 · 로그아웃하면 그 유저의 중계 연결을 바로 끊는다 (4401), 30초마다 다시 확인
- /app/me 에서 botToken 제거. 앱은 v1.2.0 이 저장해 둔 봇 토큰을 시작할 때 지운다
- 앱: BotGateway 로 디스코드 연결을 분리 (RemoteGateway = 겜녹이 봇 서버 중계, LocalGateway = 다른 봇 토큰 직접 연결)
  Bot 은 discord.js 객체 대신 이 인터페이스만 쓴다. 중계가 로그인 만료를 알리면 바로 다시 확인해서 잠근다
- 로그인 확인: 잠그라는 응답(401 · 403)은 겹친 확인 때문에 늦게 와도 같은 토큰이면 따른다
  (겹친 두 번째 확인이 401 을 받아 "등록되지 않은 아이디" 대신 "로그인 만료"로 잠기던 문제). 미등록 화면은 다시 확인해도 유지
- 테스트: 봇 중계 4건(토큰 미노출 · 음성 정보 전달 · 다른 PC 인계 · 명령 라우팅 · 해제 시 끊김), 겹친 확인 1건
  실제 디스코드: voice-e2e GVR_E2E_RELAY=1 (서버 중계로 따라 들어가 녹음 · STT · 녹음 제외), login-e2e 19/19

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-15 10:30:14 +09:00
parent a2487e6241
commit 6a03c67b54
27 changed files with 1786 additions and 201 deletions

View File

@@ -3,7 +3,8 @@
// 2) 브라우저: GET /auth/app/start/:id → 디스코드 OAuth → /auth/discord/callback (사이트 로그인과 같은 콜백, state 가 "app." 으로 시작)
// 3) 콜백: 등록된 아이디면 앱 토큰 발급, 아니면 "등록되지 않은 아이디" 결과를 남긴다
// 4) 앱: POST /auth/app/poll {id, secret} 로 결과를 받아 간다 (한 번만)
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다. 겜녹이 봇 토큰은 여기서만 내려준다
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다
// 겜녹이 봇 토큰은 앱에 보내지 않는다. 봇은 서버가 연결하고 앱은 /app/bot/ws 로 중계받는다 (bot-broker.ts)
import crypto from 'node:crypto';
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import type { AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
@@ -24,8 +25,12 @@ interface Pending {
const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean }) {
export function registerAppAuth(
app: FastifyInstance,
deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean; onRevoke?: (by: { userId?: string; token?: string }) => void },
) {
const { cfg, store, discord, secure } = deps;
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
const pending = new Map<string, Pending>();
const roleOf = (id: string): AppRole | null => (cfg.superAdmins.includes(id) ? 'superadmin' : (store.appUser(id)?.role ?? null));
@@ -114,6 +119,7 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
const role = roleOf(s.userId);
if (!role) {
store.deleteAppSession(token);
revoke({ token });
reply.code(403).send({ error: 'not_registered', message: '등록되지 않은 아이디입니다', user: userInfo(s.userId) });
return null;
}
@@ -126,12 +132,15 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
const user = userInfo(a.id);
const ver = String(req.headers['x-gvr-version'] || '').slice(0, 20) || null;
store.touchAppUser(a.id, { version: ver, name: user.name, avatar: user.avatar });
return { user, role: a.role, botToken: cfg.botToken || null, serverTime: Date.now() } satisfies AppMe;
return { user, role: a.role, serverTime: Date.now() } satisfies AppMe;
});
app.post('/auth/app/logout', async (req) => {
const t = bearer(req);
if (t) store.deleteAppSession(t);
if (t) {
store.deleteAppSession(t);
revoke({ token: t });
}
return { ok: true };
});
@@ -203,11 +212,19 @@ export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store
if (!a) return;
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
revoke({ userId: req.params.id });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
return { completeLogin };
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
const s = store.appSession(token);
const r = s ? roleOf(s.userId) : null;
return s && r ? { userId: s.userId, role: r } : null;
};
return { completeLogin, verifyToken };
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

View File

@@ -6,6 +6,7 @@ import fs from 'node:fs';
import path from 'node:path';
import type { Config } from './config.js';
import { registerAppAuth } from './app-auth.js';
import { BotBroker, type BotSource } from './bot-broker.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { RelayHub } from './relay.js';
import { ServerStore, type Session } from './store.js';
@@ -13,14 +14,17 @@ import { ServerStore, type Session } from './store.js';
const SID = 'gvr_sid';
const RECHECK_MS = 10 * 60000;
export async function buildServer(cfg: Config) {
/** botSource: 겜녹이 봇 디스코드 연결 (main.ts 가 discord.js 로 만든다. 없으면 /app/bot/ws 는 503) */
export async function buildServer(cfg: Config, opts: { botSource?: BotSource } = {}) {
const app = Fastify({ logger: { level: process.env.LOG_LEVEL || 'info' }, trustProxy: true, bodyLimit: 1024 * 1024, forceCloseConnections: true });
const store = new ServerStore(cfg.dataDir);
const hub = new RelayHub(store);
const discord = new DiscordApi(cfg);
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
const appAuth = registerAppAuth(app, { cfg, store, discord, secure });
let broker: BotBroker | null = null;
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log);
const allowedGuilds = (): string[] => {
const g = new Set(cfg.allowedGuilds);
@@ -197,6 +201,20 @@ export async function buildServer(cfg: Config) {
hub.deviceWss.handleUpgrade(req, socket, head, (ws) => hub.attachDevice(ws, d.id));
return;
}
if (url.pathname === '/app/bot/ws') {
if (!broker) {
socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n');
return socket.destroy();
}
const a = broker.authenticate(req);
if (!a) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
return socket.destroy();
}
const b = broker;
b.wss.handleUpgrade(req, socket, head, (ws) => b.attach(ws, a));
return;
}
if (url.pathname === '/ws') {
const fakeReq: any = { cookies: parseCookies(String(req.headers.cookie || '')), unsignCookie: (v: string) => app.unsignCookie(v), log: app.log };
const s = await getSession(fakeReq);
@@ -213,12 +231,13 @@ export async function buildServer(cfg: Config) {
// 서버를 닫기 전에 WebSocket 을 먼저 끊는다 (안 끊으면 close 가 연결이 끝나길 기다리며 멈춘다)
app.addHook('preClose', async () => {
hub.close();
broker?.close();
});
app.addHook('onClose', async () => {
store.flush();
});
return { app, store, hub };
return { app, store, hub, broker };
}
function parseCookies(h: string): Record<string, string> {

View File

@@ -0,0 +1,240 @@
// 겜녹이 봇 중계. 봇 토큰은 이 서버에만 있고, 앱(exe)에는 절대 보내지 않는다.
// - 서버가 디스코드 게이트웨이에 한 번 붙는다 (BotSource). 앱은 /app/bot/ws 로 붙어 필요한 정보만 받는다
// - 음성채널 참여: 앱의 @discordjs/voice 어댑터가 보낸 op 4 를 검사해서 서버가 대신 보내고,
// 디스코드가 돌려준 일회용 음성 접속 정보(VOICE_STATE/SERVER_UPDATE)를 그 앱에만 넘긴다.
// 음성 데이터는 앱 ↔ 디스코드 음성 서버로 바로 오간다 (이 서버를 거치지 않음)
// - 한 디스코드 서버에서 봇은 음성채널 하나에만 있을 수 있다 → 마지막으로 참여를 요청한 앱이 가져가고, 이전 앱에는 taken
import crypto from 'node:crypto';
import { EventEmitter } from 'node:events';
import type { IncomingMessage } from 'node:http';
import { WebSocket, WebSocketServer } from 'ws';
import type { AppRole, BotGwChannel, BotGwFromApp, BotGwGuild, BotGwMember, BotGwToApp } from '@gvr/shared';
export interface BotVoiceEvent {
guildId: string;
member: BotGwMember;
oldChannelId: string | null;
newChannelId: string | null;
channel: BotGwChannel | null;
}
export interface BotCommand {
name: string;
guildId: string;
user: BotGwMember;
voiceChannel: BotGwChannel | null;
}
/**
* 디스코드 게이트웨이 쪽 (실서버: discord-source.ts 의 discord.js, 테스트: 가짜).
* 이벤트: 'ready', 'guilds', 'voiceState' (BotVoiceEvent), 'command' (BotCommand, respond(content))
*/
export interface BotSource extends EventEmitter {
me(): BotGwMember | null;
guilds(): BotGwGuild[];
/** 음성채널 목록과 음성채널에 있는 사람 */
snapshot(guildId: string): { guild: BotGwGuild; channels: BotGwChannel[]; voice: { member: BotGwMember; channelId: string }[] } | null;
isVoiceChannel(guildId: string, channelId: string): boolean;
members(guildId: string): Promise<BotGwMember[]>;
registerCommands(guildId: string): Promise<void>;
/** 서버마다 하나. 디스코드가 보낸 봇 자신의 음성 접속 정보를 handlers 로 넘기고, send 로 op 4 를 보낸다 */
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }): { send: (payload: any) => boolean };
}
interface Conn {
id: string;
ws: WebSocket;
token: string;
userId: string;
guildId: string | null;
at: number;
}
const CMD_TIMEOUT_MS = 25000;
const SNOWFLAKE = /^\d{17,20}$/;
export class BotBroker {
readonly wss = new WebSocketServer({ noServer: true, maxPayload: 256 * 1024 });
private conns = new Set<Conn>();
/** 서버별로 지금 봇 음성 연결을 가진 앱 */
private owners = new Map<string, Conn>();
private adapters = new Map<string, { send: (payload: any) => boolean }>();
private commandsDone = new Set<string>();
private cmds = new Map<string, (content: string | null) => void>();
private timer: NodeJS.Timeout;
constructor(
private source: BotSource,
/** 앱 토큰 확인 (등록 해제 · 로그아웃이면 null) */
private verify: (token: string) => { userId: string; role: AppRole } | null,
private log: { info: (o: any, m?: string) => void; warn: (o: any, m?: string) => void },
) {
source.on('ready', () => {
const me = source.me();
if (me) for (const c of this.conns) this.send(c, { t: 'ready', me, guilds: source.guilds() });
});
source.on('guilds', () => this.broadcast({ t: 'guilds', guilds: source.guilds() }));
source.on('voiceState', (e: BotVoiceEvent) => {
for (const c of this.conns) if (c.guildId === e.guildId) this.send(c, { t: 'voiceState', ...e });
});
source.on('command', (cmd: BotCommand, respond: (content: string) => void) => void this.onCommand(cmd).then(respond));
// 등록 해제 · 로그아웃된 연결은 30초 안에 끊는다 (해제 · 로그아웃 API 는 kick 으로 바로 끊는다)
this.timer = setInterval(() => {
for (const c of this.conns) if (!this.verify(c.token)) c.ws.close(4401, 'unauthorized');
for (const c of this.conns) if (c.ws.readyState === WebSocket.OPEN) c.ws.ping();
}, 30000);
}
close(): void {
clearInterval(this.timer);
for (const c of this.conns) c.ws.terminate();
}
/** 이 유저(또는 이 토큰)의 연결을 바로 끊는다 */
kick(by: { userId?: string; token?: string }): void {
for (const c of this.conns) if ((by.userId && c.userId === by.userId) || (by.token && c.token === by.token)) c.ws.close(4401, 'unauthorized');
}
authenticate(req: IncomingMessage): { token: string; userId: string } | null {
const token = /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization || ''))?.[1] ?? '';
const a = token ? this.verify(token) : null;
return a ? { token, userId: a.userId } : null;
}
attach(ws: WebSocket, a: { token: string; userId: string }): void {
const c: Conn = { id: crypto.randomBytes(6).toString('hex'), ws, token: a.token, userId: a.userId, guildId: null, at: Date.now() };
this.conns.add(c);
this.log.info({ user: a.userId, conn: c.id }, '겜녹이 봇 중계 연결');
const me = this.source.me();
if (me) this.send(c, { t: 'ready', me, guilds: this.source.guilds() });
ws.on('message', (data, isBinary) => {
if (isBinary || !this.conns.has(c)) return;
let m: BotGwFromApp;
try {
m = JSON.parse(String(data));
} catch {
return;
}
try {
this.onMessage(c, m);
} catch (e) {
this.log.warn(e, '봇 중계 메시지 처리 실패');
}
});
const drop = () => this.drop(c);
ws.on('close', drop);
ws.on('error', drop);
}
private drop(c: Conn): void {
if (!this.conns.delete(c)) return;
this.log.info({ user: c.userId, conn: c.id }, '겜녹이 봇 중계 끊김');
// 앱이 꺼지거나 끊기면 봇을 음성채널에서 뺀다 (서버 연결은 계속 살아 있어서 그냥 두면 계속 남는다)
for (const [g, o] of this.owners) {
if (o !== c) continue;
this.owners.delete(g);
this.adapters.get(g)?.send({ op: 4, d: { guild_id: g, channel_id: null, self_mute: false, self_deaf: false } });
}
}
private send(c: Conn, m: BotGwToApp): void {
if (c.ws.readyState === WebSocket.OPEN) c.ws.send(JSON.stringify(m));
}
private broadcast(m: BotGwToApp): void {
for (const c of this.conns) this.send(c, m);
}
private adapter(guildId: string) {
let a = this.adapters.get(guildId);
if (!a) {
a = this.source.voiceAdapter(guildId, {
server: (d) => {
const o = this.owners.get(guildId);
if (o) this.send(o, { t: 'vserver', guildId, data: d });
},
state: (d) => {
const o = this.owners.get(guildId);
if (o) this.send(o, { t: 'vstate', guildId, data: d });
},
});
this.adapters.set(guildId, a);
}
return a;
}
private onMessage(c: Conn, m: BotGwFromApp): void {
switch (m.t) {
case 'watch': {
const snap = SNOWFLAKE.test(String(m.guildId)) ? this.source.snapshot(m.guildId) : null;
if (!snap) return;
c.guildId = m.guildId;
c.at = Date.now();
this.send(c, { t: 'guild', ...snap });
if (m.commands && !this.commandsDone.has(m.guildId)) {
this.commandsDone.add(m.guildId);
this.source.registerCommands(m.guildId).catch((e) => {
this.commandsDone.delete(m.guildId);
this.log.warn(e, '슬래시 명령 등록 실패');
});
}
return;
}
case 'voice': {
// 앱이 보낼 수 있는 건 "지켜보는 서버의 음성채널 참여 · 나가기" 뿐이다
const g = c.guildId;
const d = m.payload?.d;
if (!g || m.guildId !== g || m.payload?.op !== 4 || d?.guild_id !== g) return;
const ch = d.channel_id === null ? null : String(d.channel_id);
if (ch !== null && !this.source.isVoiceChannel(g, ch)) return;
const owner = this.owners.get(g);
if (ch === null) {
// 이미 다른 PC 가 가져간 봇을 이전 PC 가 빼지 못하게
if (owner !== c) return;
this.owners.delete(g);
} else if (owner !== c) {
if (owner) this.send(owner, { t: 'taken', guildId: g });
this.owners.set(g, c);
}
this.adapter(g).send({ op: 4, d: { guild_id: g, channel_id: ch, self_mute: !!d.self_mute, self_deaf: !!d.self_deaf } });
return;
}
case 'cmd_res': {
// 여러 PC 로 보낸 명령은 첫 응답만 쓴다
this.cmds.get(m.id)?.(String(m.content ?? '').slice(0, 1800));
return;
}
case 'req': {
if (m.op !== 'members' || m.guildId !== c.guildId) return this.send(c, { t: 'res', id: m.id, ok: false, error: 'forbidden' });
this.source.members(m.guildId).then(
(data) => this.send(c, { t: 'res', id: m.id, ok: true, data }),
(e) => this.send(c, { t: 'res', id: m.id, ok: false, error: String(e?.message ?? e) }),
);
return;
}
}
}
/** 슬래시 명령을 맞는 앱으로 보내고 첫 응답을 돌려준다 */
private async onCommand(cmd: BotCommand): Promise<string> {
const here = [...this.conns].filter((c) => c.guildId === cmd.guildId).sort((a, b) => b.at - a.at);
if (!here.length) return '지금 이 서버에서 켜져 있는 겜녹이 앱이 없습니다.';
const owner = this.owners.get(cmd.guildId);
const mine = here.find((c) => c.userId === cmd.user.id);
let targets: Conn[];
if (cmd.name === '녹음제외' || cmd.name === '녹음참여') targets = here; // 각 PC 기록에 모두 남긴다
else if (cmd.name === '녹음종료') targets = owner && here.includes(owner) ? [owner] : [];
else targets = [mine ?? (owner && here.includes(owner) ? owner : here[0])];
if (!targets.length) return '지금은 녹음 중이 아닙니다.';
const id = crypto.randomBytes(8).toString('hex');
const content = await new Promise<string | null>((resolve) => {
const t = setTimeout(() => resolve(null), CMD_TIMEOUT_MS);
this.cmds.set(id, (v) => {
clearTimeout(t);
this.cmds.delete(id);
resolve(v);
});
for (const c of targets) this.send(c, { t: 'cmd', id, ...cmd });
});
this.cmds.delete(id);
return content ?? '겜녹이 앱이 응답하지 않습니다. 잠시 뒤 다시 시도해 주세요.';
}
}

View File

@@ -0,0 +1,114 @@
// 서버의 겜녹이 봇 디스코드 연결 (discord.js). bot-broker.ts 의 BotSource 구현
import { EventEmitter } from 'node:events';
import { ChannelType, Client, Events, GatewayIntentBits, MessageFlags, type Guild, type GuildMember, type VoiceBasedChannel } from 'discord.js';
import type { BotGwChannel, BotGwGuild, BotGwMember } from '@gvr/shared';
import type { BotCommand, BotSource, BotVoiceEvent } from './bot-broker.js';
/** 앱과 같은 슬래시 명령 (app/src/core/discord/bot.ts COMMANDS) */
export const COMMANDS = [
{ name: '녹음시작', description: '겜녹이를 내가 있는 음성채널로 불러 녹음을 시작합니다' },
{ name: '녹음종료', description: '겜녹이가 음성채널에서 나가고 녹음을 끝냅니다' },
{ name: '녹음제외', description: '내 목소리를 녹음하지 않습니다 (다음 세션에도 유지)' },
{ name: '녹음참여', description: '녹음 제외를 풀고 다시 녹음에 참여합니다' },
];
const member = (m: GuildMember): BotGwMember => ({ id: m.id, name: m.displayName, avatar: m.displayAvatarURL({ size: 128 }), bot: m.user.bot });
const guild = (g: Guild): BotGwGuild => ({ id: g.id, name: g.name, icon: g.iconURL({ size: 128 }) });
const isVoice = (c: { type: ChannelType } | null | undefined): c is VoiceBasedChannel => !!c && (c.type === ChannelType.GuildVoice || c.type === ChannelType.GuildStageVoice);
export class DiscordSource extends EventEmitter implements BotSource {
readonly client: Client;
constructor(private log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void }) {
super();
const c = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMembers] });
this.client = c;
c.on(Events.ClientReady, () => {
log.info({ bot: c.user?.tag, guilds: c.guilds.cache.size }, '겜녹이 봇 디스코드 연결');
this.emit('ready');
});
c.on(Events.GuildCreate, () => this.emit('guilds'));
c.on(Events.GuildDelete, () => this.emit('guilds'));
c.on(Events.Error, (e) => log.error(e, '디스코드 오류'));
c.on(Events.VoiceStateUpdate, (o, n) => {
const m = n.member ?? o.member;
if (!m) return;
const ch = n.channel;
const e: BotVoiceEvent = { guildId: n.guild.id, member: member(m), oldChannelId: o.channelId, newChannelId: n.channelId, channel: ch ? { id: ch.id, name: ch.name } : null };
this.emit('voiceState', e);
});
c.on(Events.InteractionCreate, async (i) => {
if (!i.isChatInputCommand() || !i.guildId || !COMMANDS.some((x) => x.name === i.commandName)) return;
try {
await i.deferReply({ flags: MessageFlags.Ephemeral });
} catch (e) {
log.error(e, '명령 응답 실패');
return;
}
const m = i.guild?.members.cache.get(i.user.id) ?? (await i.guild?.members.fetch(i.user.id).catch(() => null)) ?? null;
const vc = m?.voice.channel ?? null;
const cmd: BotCommand = {
name: i.commandName,
guildId: i.guildId,
user: m ? member(m) : { id: i.user.id, name: i.user.globalName || i.user.username, avatar: i.user.displayAvatarURL({ size: 128 }), bot: i.user.bot },
voiceChannel: vc ? { id: vc.id, name: vc.name } : null,
};
this.emit('command', cmd, (content: string) => void i.editReply(content).catch((e) => log.error(e, '명령 응답 실패')));
});
}
login(token: string): Promise<string> {
return this.client.login(token);
}
async destroy(): Promise<void> {
await this.client.destroy();
}
me(): BotGwMember | null {
const u = this.client.isReady() ? this.client.user : null;
return u ? { id: u.id, name: u.username, avatar: u.displayAvatarURL({ size: 128 }), bot: true } : null;
}
guilds(): BotGwGuild[] {
return [...this.client.guilds.cache.values()].map(guild);
}
snapshot(guildId: string) {
const g = this.client.guilds.cache.get(guildId);
if (!g) return null;
const channels: BotGwChannel[] = [];
const voice: { member: BotGwMember; channelId: string }[] = [];
for (const ch of g.channels.cache.values()) {
if (!isVoice(ch)) continue;
channels.push({ id: ch.id, name: ch.name });
for (const m of ch.members.values()) voice.push({ member: member(m), channelId: ch.id });
}
return { guild: guild(g), channels, voice };
}
isVoiceChannel(guildId: string, channelId: string): boolean {
const ch = this.client.guilds.cache.get(guildId)?.channels.cache.get(channelId);
return isVoice(ch);
}
async members(guildId: string): Promise<BotGwMember[]> {
const g = this.client.guilds.cache.get(guildId);
if (!g) return [];
const ms = await g.members.fetch().catch(() => g.members.cache);
return [...ms.values()].map(member);
}
async registerCommands(guildId: string): Promise<void> {
const g = this.client.guilds.cache.get(guildId);
if (!g) return;
await g.commands.set(COMMANDS);
this.log.info({ guild: guildId }, '슬래시 명령 등록');
}
voiceAdapter(guildId: string, handlers: { server: (d: any) => void; state: (d: any) => void }) {
// discord.js 가 @discordjs/voice 용으로 주는 어댑터를 그대로 쓴다. 봇 자신의 음성 정보만 handlers 로 온다
this.client.voice.adapters.set(guildId, { onVoiceServerUpdate: handlers.server, onVoiceStateUpdate: handlers.state, destroy: () => undefined });
return {
send: (payload: any) => {
const g = this.client.guilds.cache.get(guildId);
if (!g) return false;
g.shard.send(payload);
return true;
},
};
}
}

View File

@@ -1,11 +1,21 @@
import { buildServer } from './app.js';
import { loadConfig } from './config.js';
import { DiscordSource } from './discord-source.js';
const cfg = loadConfig();
const { app } = await buildServer(cfg);
// 겜녹이 봇은 이 서버만 디스코드에 연결한다 (봇 토큰은 앱에 보내지 않는다). BOT_GATEWAY=0 이면 끈다
let log: { info: (o: any, m?: string) => void; error: (o: any, m?: string) => void } = { info: () => undefined, error: (o, m) => console.error(m, o) };
const botSource = process.env.BOT_GATEWAY === '0' ? undefined : new DiscordSource({ info: (o, m) => log.info(o, m), error: (o, m) => log.error(o, m) });
const { app } = await buildServer(cfg, { botSource });
log = app.log;
await app.listen({ host: cfg.host, port: cfg.port });
if (botSource) {
// 디스코드에 못 붙어도 사이트는 계속 돈다 (discord.js 가 알아서 다시 연결)
botSource.login(cfg.botToken).catch((e) => app.log.error(e, '겜녹이 봇 디스코드 연결 실패'));
}
const stop = async () => {
await app.close();
await botSource?.destroy();
process.exit(0);
};
process.on('SIGTERM', stop);