fix(tts): follow user across voice channels without dropping session; remove Chzzk cookies

- VoiceSession.moveTo: destroy(false) + join instead of disconnect()/destroy().
  The old path sent a leave payload first, so Discord emitted
  voiceStateUpdate(channel=null) and endSession() killed the session
  while moving.
- voiceStateUpdate: when the bot itself is moved, only sync the channel.
- getVoiceChannel: user's channel first, then the session's channel,
  then the bot's cached voice channel.
- Remove CHZZK_NID_AUT/SES and token fetch; Chzzk TTS works without them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claude Owner
2026-11-11 08:35:26 +09:00
parent 2d8b929b90
commit 26b4525316
7 changed files with 37 additions and 64 deletions

View File

@@ -14,10 +14,6 @@ DBPATH=./db/tts.db
# `npm run prod` 실행 시 DEV=true 면 이 길드의 기존 슬래시 명령을 먼저 wipe 한 뒤 전역 등록
GUILDID=
# 치지직(Chzzk) 인증 쿠키
CHZZK_NID_AUT=
CHZZK_NID_SES=
# 시그니처 서버 host:port (선택, 미설정 시 192.168.10.5:2967)
SIGNATURE_HOST=

View File

@@ -67,8 +67,6 @@ db/
| `TOKEN` | ✅ | 봇 토큰 |
| `PREFIX` | ✅ | 메시지 명령어 prefix (예: `!`) |
| `DBPATH` | ✅ | SQLite 파일 경로 (예: `./db/data.db`) |
| `CHZZK_NID_AUT` | ✅ | 네이버 NID_AUT 쿠키 (치지직 TTS 인증) |
| `CHZZK_NID_SES` | ✅ | 네이버 NID_SES 쿠키 |
| `GUILDID` | △ | `DEV=true`일 때만 사용 (DEV 길드 한정 슬래시 등록 대상). 그 외에는 미설정이어도 무방 |
| `DEV` | 선택 | `true`면 글로벌 대신 `GUILDID`에만 슬래시 등록 |
| `DEBUG` | 선택 | `true`면 명령어 오류 스택 로깅 |
@@ -108,7 +106,7 @@ Dockerfile은 `node:22-bookworm-slim` 기반이며 `ffmpeg`을 설치한다. (
2. 텍스트 전처리(URL/멘션/이모지 치환) → 시그니처 키워드 분할
3. 각 조각을 Chzzk TTS로 합성 또는 캐시된 시그니처 mp3 사용
4. mp3 Buffer 결합 → `Transcode`에서 PCM 변환 → `VoiceSession.player.play()`
5. 일정 시간 idle 시 세션 자동 종료, 사용자 채널 이동 시 따라감
5. 일정 시간 idle 시 세션 자동 종료. 채팅한 유저가 음성채널에 있으면 그 채널로 이동해 재생하고, 음성채널에 없으면 봇이 있는 채널에서 재생
## 참고

View File

@@ -1,5 +1,5 @@
import { client, signature } from "../index";
import { ChannelType, Guild, GuildMember, TextChannel, VoiceBasedChannel, VoiceChannel } from "discord.js";
import { ChannelType, Guild, GuildMember, TextChannel, VoiceBasedChannel } from "discord.js";
import { Config } from "../utils/Config";
import { DB } from "../utils/Database";
import { Logger } from "../utils/Logger";
@@ -43,8 +43,16 @@ export class TTSClient {
return this.map.get(guildId);
}
public getVoiceChannel(member: GuildMember): VoiceChannel | null {
/**
* TTS를 재생할 음성채널.
* 1) 채팅한 유저가 음성채널에 있으면 그 채널 (봇이 다른 채널에 있으면 이동)
* 2) 유저가 음성채널에 없으면 봇이 지금 있는 채널
*/
public getVoiceChannel(member: GuildMember): VoiceBasedChannel | null {
if (member.voice.channel?.type === ChannelType.GuildVoice) return member.voice.channel;
const sessionChannelId = this.map.get(member.guild.id)?.channelId;
const sessionChannel = sessionChannelId ? member.guild.channels.cache.get(sessionChannelId) : null;
if (sessionChannel?.type === ChannelType.GuildVoice) return sessionChannel;
if (member.guild.members.me?.voice.channel?.type === ChannelType.GuildVoice) return member.guild.members.me.voice.channel;
return null;
}

View File

@@ -116,13 +116,27 @@ export class VoiceSession {
try { this.player.play(res); } catch {};
}
public get channelId() {
return this.channel.id;
}
/**
* 유저가 있는 음성채널로 옮긴다.
* 기존 연결에 disconnect()/destroy()를 호출하면 디스코드에 "퇴장" 페이로드가
* 나가고, 그 결과 오는 voiceStateUpdate(channel=null) 때문에 세션 자체가
* 종료돼 봇이 따라오지 못했다. 그래서 퇴장 페이로드 없이 기존 연결만
* 정리(destroy(false))하고 새 채널로 바로 join 한다. 디스코드는 이를
* 이전 채널 → 새 채널 "이동" 한 번으로 처리한다.
* 연결이 준비되기 전에 play()된 음성은 player가 AutoPaused 상태로 들고
* 있다가 Ready가 되면 재생한다.
*/
async moveTo(newChannel: VoiceBasedChannel) {
if (this.isSessionEnd) return;
if (this.channel.id === newChannel.id) return;
Logger.info(`${this.tag} move ${this.channel.id} -> ${newChannel.id}`);
this.channel = newChannel;
this.startEndTimer();
try { this.connection.disconnect(); } catch {};
try { this.connection.destroy(); } catch {};
try { this.connection.destroy(false); } catch {};
this.connection = joinVoiceChannel({
guildId: this.guild.id,
channelId: this.channel.id,
@@ -135,6 +149,13 @@ export class VoiceSession {
await entersState(this.connection, VoiceConnectionStatus.Ready, 20_000).catch(() => {});
}
// 관리자가 봇을 다른 채널로 직접 옮긴 경우: 연결은 디스코드가 이미 옮겼으므로
// 재접속하지 않고 현재 채널 정보만 맞춘다.
syncChannel(channel: VoiceBasedChannel) {
if (this.isSessionEnd) return;
this.channel = channel;
}
sessionEnd() {
if (this.isSessionEnd) return;
this.isSessionEnd = true;

View File

@@ -5,5 +5,5 @@ export const voiceStateUpdate = async (oldState: VoiceState, newState: VoiceStat
// if (oldState) leave(oldState);
// if (newState) join(newState);
if (oldState.member?.id === client.user?.id && oldState.channel && !newState.channel) return tts.endSession(oldState.guild.id);
if (oldState.member?.id === client.user?.id && oldState.channel && newState.channel) return tts.findSession(oldState.guild.id)?.moveTo(newState.channel);
if (oldState.member?.id === client.user?.id && oldState.channel && newState.channel) return tts.findSession(oldState.guild.id)?.syncChannel(newState.channel);
}

View File

@@ -8,10 +8,6 @@ export const Config = {
_prefix: process.env.PREFIX?.trim(),
_dbPath: process.env.DBPATH?.trim(),
_guildId: process.env.GUILDID?.trim(),
_chzzk: {
nid_aut: process.env.CHZZK_NID_AUT?.trim(),
nid_ses: process.env.CHZZK_NID_SES?.trim(),
},
_ttsPath: process.env.TTSPATH?.trim(),
_signatureHost: process.env.SIGNATURE_HOST?.trim() || "192.168.10.5:2967",
debug: process.env.DEBUG?.trim()?.toLocaleLowerCase() === "true",
@@ -38,14 +34,6 @@ export const Config = {
if (!this._guildId) throw new ReferenceError("GUILDID is missing");
return this._guildId;
},
get chzzk() {
if (!this._chzzk.nid_aut) throw new ReferenceError("CHZZK_NID_AUT is missing");
if (!this._chzzk.nid_ses) throw new ReferenceError("CHZZK_NID_SES is missing");
return {
nid_aut: this._chzzk.nid_aut,
nid_ses: this._chzzk.nid_ses,
};
},
get ttsPath() {
if (!this._ttsPath) throw new ReferenceError("TTSPATH is missing");
return this._ttsPath;

View File

@@ -1,6 +1,4 @@
import axios from "axios";
import { Config } from "../Config";
import { Logger } from "../Logger";
export enum VoiceType {
// 현재(25.08.27)
@@ -18,61 +16,25 @@ export enum VoiceType {
하준 = "hajun",
};
// 치지직 TTS는 로그인 쿠키·토큰 없이도 음성을 돌려준다(2026-11-11 확인).
// 그래서 네이버 쿠키(NID_AUT/NID_SES)와 토큰 발급 요청은 쓰지 않는다.
const defHeaders = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
"Cookie": Object.entries(Config.chzzk).map(([key, value]) => key+'='+value).join(';'),
};
// 치지직이 응답하지 않을 때 봇이 무한정 기다리지 않도록 요청마다 타임아웃을 둔다.
const TOKEN_TIMEOUT_MS = 3_000;
const TTS_TIMEOUT_MS = 8_000;
// 토큰 발급 결과 캐시. 성공하면 잠시 재사용하고, 실패(쿠키 만료 등)하면
// 한동안 발급 요청 자체를 건너뛴다. 토큰 없이도 TTS 요청은 동작하므로
// 실패 시에는 기존과 같이 "undefined" 토큰으로 보낸다.
const TOKEN_OK_TTL_MS = 5 * 60_000;
const TOKEN_FAIL_TTL_MS = 10 * 60_000;
const NO_TOKEN = "undefined";
let tokenCache: { token: string; expiresAt: number } | null = null;
let tokenInflight: Promise<string> | null = null;
const errMessage = (err: any): string => {
const status = err?.response?.status;
const code = err?.code;
return [status && `status=${status}`, code && `code=${code}`, err?.message].filter(Boolean).join(" ") || "오류";
};
const fetchToken = async (): Promise<string> => {
try {
const val = await axios.get("https://api.chzzk.naver.com/service/v1/alerts/token", {
headers: defHeaders,
responseType: "json",
timeout: TOKEN_TIMEOUT_MS,
});
const token = val.data?.content?.token;
if (!token) throw new Error(val.data?.message || "토큰 없음");
tokenCache = { token, expiresAt: Date.now() + TOKEN_OK_TTL_MS };
return token;
} catch (err) {
Logger.warn(`[Chzzk] 토큰 발급 실패(${errMessage(err)}), ${TOKEN_FAIL_TTL_MS / 60_000}분간 토큰 없이 요청`);
tokenCache = { token: NO_TOKEN, expiresAt: Date.now() + TOKEN_FAIL_TTL_MS };
return NO_TOKEN;
}
};
const getToken = (): Promise<string> => {
if (tokenCache && tokenCache.expiresAt > Date.now()) return Promise.resolve(tokenCache.token);
// 동시에 여러 채팅이 와도 발급 요청은 한 번만 보낸다.
if (!tokenInflight) tokenInflight = fetchToken().finally(() => { tokenInflight = null; });
return tokenInflight;
};
export const textToSpeech = async (text: string, voice: VoiceType): Promise<Buffer> => {
const token = await getToken();
try {
const val = await axios.post("https://api.chzzk.naver.com/service/v1/alerts/tts", {
message: text,
token,
type: "n"+voice
}, {
headers: defHeaders,