All files bot.ts

67.19% Statements 170/253
64.37% Branches 103/160
75% Functions 12/16
67.63% Lines 163/241

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 4985x                 5x               5x   5x     5x     5x 1x         5x 1x 1x                                                                                             5x     5x             11x 10x   11x   8x 8x 8x 8x 7x 7x               7x   7x 7x 7x   7x 7x   7x                                                                                                                                                                             5x 10x 8x 8x 8x 8x 8x 8x 7x                 7x       8x 4x 4x 1x 1x   3x 3x       3x 3x           3x 3x 1x 1x   2x   2x   1x 1x 1x                           1x 1x 1x 1x 1x       4x 3x 3x 3x 1x 1x   2x     2x       2x             2x 2x 1x   2x 1x 1x   1x 1x     1x 1x 1x       1x 1x 1x     1x           1x                 1x         5x 7x   6x 6x 6x 6x 6x 4x                 4x     6x 6x 1x 1x   5x 5x 2x 2x   3x 2x           3x 3x 1x 1x   2x 2x   2x 1x 1x 1x 1x     1x       5x 4x   3x 3x 3x 1x                 1x     3x 3x 1x   3x 2x 2x   2x     2x   1x     3x                     5x 5x   4x 4x 4x 4x 4x 1x                 1x     4x 4x 1x 1x   3x     3x 1x     3x             3x 3x 2x   3x 1x 1x   2x 2x     2x 2x 2x      
import {
  CommandInteraction,
  ChatInputCommandInteraction,
  GuildMember,
  ChannelType,
  VoiceChannel,
  Interaction,
} from 'discord.js';
import type { VoiceConnection, AudioPlayer as AudioPlayerType } from '@discordjs/voice';
import {
  joinVoiceChannel,
  createAudioPlayer,
  createAudioResource,
  entersState,
  AudioPlayerStatus,
  VoiceConnectionStatus,
} from '@discordjs/voice';
import { Readable } from 'stream';
import type { ChildProcess } from 'child_process';
import { spawn } from 'child_process';
 
// Inlined test environment check
const isTestEnv = !!process.env.JEST_WORKER_ID;
 
// Utility sleep function
export function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
 
// FFmpeg stream creator
// In test environment, return an empty stream instead of executing FFmpeg
export function createFFmpegStream(streamUrl: string): Readable {
  Eif (isTestEnv) {
    return Readable.from([]);
  }
  // Transcode RTSP stream to raw PCM for Discord using system ffmpeg
  const ffmpeg = spawn('ffmpeg', [
    '-rtsp_transport',
    'tcp',
    '-i',
    streamUrl,
    '-f',
    'adts',
    '-c:a',
    'copy',
    'pipe:1',
  ]);
  // Log FFmpeg stderr for diagnostics
  if (ffmpeg.stderr) {
    ffmpeg.stderr.on('data', (chunk) => {
      if (!isTestEnv) {
        console.error(`[ffmpeg stderr] ${chunk.toString()}`);
      }
    });
  }
  ffmpeg.on('error', (err) => {
    if (!isTestEnv) {
      console.error('[ffmpeg process error]', err);
    }
  });
  ffmpeg.on('close', (code, signal) => {
    console.log(`[ffmpeg process closed] code=${code} signal=${signal}`);
  });
  if (!ffmpeg.stdout) {
    throw new Error('FFmpeg stdout not available');
  }
  return ffmpeg.stdout;
}
 
// Per-guild connection state
export interface GuildAudioState {
  connection: InstanceType<typeof VoiceConnection> | null;
  player: InstanceType<typeof AudioPlayerType> | null;
  streamKey: string | null;
  streamUrl: string | null;
  lastActivityTime: number;
  isPlaying: boolean; // Prevent multiple playStream per guild
  ffmpegProcess?: ChildProcess | null;
}
 
export const guildAudioStates: Map<string, GuildAudioState> = new Map();
 
// Stream playback, auto-reconnect, and auto-disconnect logic
export async function playStream(
  state: GuildAudioState,
  interaction: CommandInteraction,
  isResync = false,
  testOptions?: { maxLoop?: number; forceBreak?: boolean }
) {
  // In test environment without explicit testOptions, set maxLoop=1 to prevent infinite loops
  if (isTestEnv && testOptions === undefined) {
    testOptions = { maxLoop: 1 };
  }
  if (!state.connection || !state.streamUrl || !state.streamKey) return;
 
  let first = true;
  let loopCount = 0;
  while (true) {
    if (testOptions?.forceBreak) break;
    loopCount++;
    Iif (testOptions?.maxLoop && loopCount > testOptions.maxLoop) {
      // When test maxLoop is reached, explicitly destroy the connection
      if (state.connection) {
        state.connection.destroy();
      }
      break;
    }
    // Spawn FFmpeg and track process for cleanup (skip in test environment)
    Eif (isTestEnv) {
      // In test environment, simulate successful play and return early
      Eif (first) {
        await interaction.editReply(`Playing ${state.streamKey}.`);
        first = false;
      }
      Eif (state.connection) {
        state.connection.destroy();
      }
      break;
    }
 
    const ffmpeg = spawn(
      'ffmpeg',
      ['-rtsp_transport', 'tcp', '-i', state.streamUrl!, '-f', 'adts', '-c:a', 'copy', 'pipe:1'],
      { stdio: ['ignore', 'pipe', 'pipe'] }
    );
    state.ffmpegProcess = ffmpeg;
    const ffmpegStream = ffmpeg.stdout!;
    const resource = createAudioResource(ffmpegStream);
    const player = createAudioPlayer();
    player.play(resource);
    state.player = player;
    state.connection.subscribe(player);
    state.lastActivityTime = Date.now();
 
    if (first) {
      if (isResync) {
        console.log(`${state.streamKey} is resyncing...`);
      } else {
        console.log(`${state.streamKey} is playing!`);
      }
    }
 
    try {
      // Wait for Playing state (start)
      await entersState(player, AudioPlayerStatus.Playing, 5000);
 
      // Wait 1 second and check if still playing to confirm real playback
      if (!isTestEnv) await sleep(1000);
      if (player.state.status !== 'playing') {
        throw new Error('Stream did not stay in playing state');
      }
 
      if (first) {
        await interaction.editReply(`Playing ${state.streamKey}.`);
        // Wait 1 second and check if still playing to confirm real playback
        if (!isTestEnv) await sleep(1000);
        if (player.state.status !== 'playing') {
          throw new Error('Stream did not stay in playing state');
        }
        if (isResync) {
          console.log(`${state.streamKey} is resynced!`);
        }
        first = false;
      } else {
        console.log(`${state.streamKey} is autoresumed!`);
      }
      // Wait for Idle state (end)
      await entersState(player, AudioPlayerStatus.Idle, 1800000);
      console.log(`${state.streamKey} is stopped!`);
    } catch (error) {
      if (!isTestEnv) {
        console.error('playStream error:', error);
      }
      if (first) {
        await interaction.editReply('Failed to play stream.');
        return;
      }
      if (!isTestEnv) await sleep(3000);
      // continue loop for retry
    }
 
    // Auto-disconnect if too long idle
    if (!state.connection) break;
    if (Date.now() - state.lastActivityTime > 1800000) {
      // 30 minutes
      console.log(`${state.streamKey} is autodestroyed!`);
      state.connection.destroy();
      state.connection = null;
      state.player = null;
      break;
    }
 
    // If connection still exists, try to autoresume (continue loop)
    if (state.connection) {
      console.log(`${state.streamKey} is autoresuming...`);
      if (!isTestEnv) await sleep(3000); // Optional: wait before reconnect
      continue;
    } else {
      break;
    }
  }
}
 
// Unified command handler
export async function handleInteraction(interaction: Interaction) {
  if (!interaction.isChatInputCommand() || !interaction.guildId) return;
  const chatInputInteraction = interaction as ChatInputCommandInteraction;
  const guildId = chatInputInteraction.guildId!;
  const member = chatInputInteraction.member as GuildMember;
  const voiceChannel = member.voice.channel;
  let state = guildAudioStates.get(guildId);
  if (!state) {
    state = {
      connection: null,
      player: null,
      streamKey: null,
      streamUrl: null,
      lastActivityTime: Date.now(),
      isPlaying: false,
      ffmpegProcess: null,
    };
    guildAudioStates.set(guildId, state);
  }
 
  // play command
  if (chatInputInteraction.commandName === 'play') {
    await chatInputInteraction.deferReply();
    if (!voiceChannel || voiceChannel.type !== ChannelType.GuildVoice) {
      await chatInputInteraction.editReply('Please join a voice channel.');
      return;
    }
    const vc = voiceChannel as VoiceChannel;
    Iif (!vc.joinable || !vc.speakable) {
      await chatInputInteraction.editReply('Cannot join or speak in the voice channel.');
      return;
    }
    Eif (!state.connection || state.connection.state.status === VoiceConnectionStatus.Destroyed) {
      state.connection = joinVoiceChannel({
        channelId: vc.id,
        guildId: guildId,
        adapterCreator: vc.guild.voiceAdapterCreator,
      });
    }
    const newKey = chatInputInteraction.options.get('streamkey')?.value as string;
    if (!newKey) {
      await chatInputInteraction.editReply('streamkey is not specified.');
      return;
    }
    const oldKey = state.streamKey;
    // If already playing
    if (state.isPlaying) {
      // Already playing same stream or no previous key
      Eif (!oldKey || newKey === oldKey) {
        await chatInputInteraction.editReply('Already playing.');
        return;
      }
      // Switching to a different stream
      if (state.ffmpegProcess) {
        state.ffmpegProcess.kill();
      }
      state.streamKey = newKey;
      state.streamUrl = `rtsp://topaz.chat/live/${newKey}`;
      playStream(state, chatInputInteraction).finally(() => {
        state.isPlaying = false;
      });
      return;
    }
    // Starting new playback
    state.streamKey = newKey;
    state.streamUrl = `rtsp://topaz.chat/live/${newKey}`;
    state.isPlaying = true;
    playStream(state, chatInputInteraction).finally(() => {
      state.isPlaying = false;
    });
  }
  // resync command (force reload stream)
  else if (chatInputInteraction.commandName === 'resync') {
    await chatInputInteraction.deferReply();
    const voiceChannel = (chatInputInteraction.member as GuildMember).voice.channel;
    if (!voiceChannel || voiceChannel.type !== ChannelType.GuildVoice) {
      await chatInputInteraction.editReply('Please join a voice channel.');
      return;
    }
    const vc = voiceChannel as VoiceChannel;
 
    // Force stop current playback if exists
    Iif (state.connection) {
      state.connection.destroy();
    }
    // Create new connection
    state.connection = joinVoiceChannel({
      channelId: vc.id,
      guildId: guildId,
      adapterCreator: vc.guild.voiceAdapterCreator,
    });
 
    // Get streamkey from command option or use previous one
    let streamKey = chatInputInteraction.options.get('streamkey')?.value as string | undefined;
    if (!streamKey) {
      streamKey = state.streamKey ?? undefined;
    }
    if (!streamKey) {
      await chatInputInteraction.editReply('streamkey is not specified.');
      return;
    }
    state.streamKey = streamKey;
    state.streamUrl = `rtsp://topaz.chat/live/${streamKey}`;
 
    // Force start playback
    state.isPlaying = true;
    playStream(state, chatInputInteraction, true).finally(() => {
      state.isPlaying = false;
    });
  }
  // stop command
  else Eif (chatInputInteraction.commandName === 'stop') {
    await chatInputInteraction.deferReply();
    Iif (state.ffmpegProcess) {
      state.ffmpegProcess.kill();
    }
    Iif (state.connection) {
      const destroyedKey = state.streamKey;
      state.connection.destroy();
      console.log(`${destroyedKey} is destroyed!`);
    }
    // Reset all state for this guild
    guildAudioStates.set(guildId, {
      connection: null,
      player: null,
      streamKey: null,
      streamUrl: null,
      lastActivityTime: Date.now(),
      isPlaying: false,
      ffmpegProcess: null,
    });
    await chatInputInteraction.editReply('Destroyed.');
  }
}
 
// Individual command handlers for testing
export async function handlePlayCommand(interaction: ChatInputCommandInteraction) {
  if (!interaction.guildId) return;
 
  const guildId = interaction.guildId;
  const member = interaction.member as GuildMember;
  const voiceChannel = member.voice.channel;
  let state = guildAudioStates.get(guildId);
  if (!state) {
    state = {
      connection: null,
      player: null,
      streamKey: null,
      streamUrl: null,
      lastActivityTime: Date.now(),
      isPlaying: false,
      ffmpegProcess: null,
    };
    guildAudioStates.set(guildId, state);
  }
 
  await interaction.deferReply();
  if (!voiceChannel || voiceChannel.type !== ChannelType.GuildVoice) {
    await interaction.editReply('You need to be in a voice channel to play music!');
    return;
  }
  const vc = voiceChannel as VoiceChannel;
  if (!vc.joinable || !vc.speakable) {
    await interaction.editReply('Cannot join or speak in the voice channel.');
    return;
  }
  if (!state.connection || state.connection.state.status === VoiceConnectionStatus.Destroyed) {
    state.connection = joinVoiceChannel({
      channelId: vc.id,
      guildId: guildId,
      adapterCreator: vc.guild.voiceAdapterCreator,
    });
  }
  const streamKey = interaction.options.getString('streamkey');
  if (!streamKey) {
    await interaction.editReply('streamkey is not specified.');
    return;
  }
  state.streamKey = streamKey;
  state.streamUrl = `rtsp://topaz.chat/live/${streamKey}`;
  // Prevent multiple playStream per guild
  if (!state.isPlaying) {
    state.isPlaying = true;
    await interaction.editReply(`Playing stream: ${streamKey}`);
    playStream(state, interaction).finally(() => {
      state.isPlaying = false;
    });
  } else {
    await interaction.editReply('Already playing.');
  }
}
 
export async function handleStopCommand(interaction: ChatInputCommandInteraction) {
  if (!interaction.guildId) return;
 
  const guildId = interaction.guildId;
  let state = guildAudioStates.get(guildId);
  if (!state) {
    state = {
      connection: null,
      player: null,
      streamKey: null,
      streamUrl: null,
      lastActivityTime: Date.now(),
      isPlaying: false,
      ffmpegProcess: null,
    };
    guildAudioStates.set(guildId, state);
  }
 
  await interaction.deferReply();
  if (state.ffmpegProcess) {
    state.ffmpegProcess.kill();
  }
  if (state.connection) {
    const destroyedKey = state.streamKey;
    state.connection.destroy();
    // Only log in non-test environment
    Iif (!process.env.JEST_WORKER_ID) {
      console.log(`${destroyedKey} is destroyed!`);
    }
    await interaction.editReply('Stopped playing and left the channel.');
  } else {
    await interaction.editReply('Not in a voice channel.');
  }
  // Reset all state for this guild
  guildAudioStates.set(guildId, {
    connection: null,
    player: null,
    streamKey: null,
    streamUrl: null,
    lastActivityTime: Date.now(),
    isPlaying: false,
    ffmpegProcess: null,
  });
}
 
export async function handleResyncCommand(interaction: ChatInputCommandInteraction) {
  if (!interaction.guildId) return;
 
  const guildId = interaction.guildId;
  const member = interaction.member as GuildMember;
  const voiceChannel = member.voice.channel;
  let state = guildAudioStates.get(guildId);
  if (!state) {
    state = {
      connection: null,
      player: null,
      streamKey: null,
      streamUrl: null,
      lastActivityTime: Date.now(),
      isPlaying: false,
      ffmpegProcess: null,
    };
    guildAudioStates.set(guildId, state);
  }
 
  await interaction.deferReply();
  if (!voiceChannel || voiceChannel.type !== ChannelType.GuildVoice) {
    await interaction.editReply('Please join a voice channel.');
    return;
  }
  const vc = voiceChannel as VoiceChannel;
 
  // Force stop current playback if exists
  if (state.connection) {
    state.connection.destroy();
  }
  // Create new connection
  state.connection = joinVoiceChannel({
    channelId: vc.id,
    guildId: guildId,
    adapterCreator: vc.guild.voiceAdapterCreator,
  });
 
  // Get streamkey from command option or use previous one
  let streamKey = interaction.options.getString('streamkey');
  if (!streamKey) {
    streamKey = state.streamKey ?? null;
  }
  if (!streamKey) {
    await interaction.editReply('streamkey is not specified.');
    return;
  }
  state.streamKey = streamKey;
  state.streamUrl = `rtsp://topaz.chat/live/${streamKey}`;
 
  // Force start playback
  state.isPlaying = true;
  playStream(state, interaction, true).finally(() => {
    state.isPlaying = false;
  });
}