kxs.rip
v1.7.5
Published
Class-based TypeScript module for interacting with the KxsNetwork
Downloads
37
Maintainers
Readme
kxs.rip
Class-oriented TypeScript module for interacting with the KxsNetwork. This module provides a comprehensive interface for all network functionalities: WebSocket, REST API, player management, voice chat, administration, etc.
Installation
npm install kxs.rip
# or
bun install kxs.ripBasic Usage
import { KxsNetwork } from 'kxs.rip';
// Create an instance
const kxs = new KxsNetwork({
wsUrl: 'ws://localhost:3000',
apiUrl: 'http://localhost:3000',
username: 'MyUsername',
enableVoiceChat: true
});
// Connect
await kxs.connect();
// Identify
kxs.identify();
// Join a game
kxs.joinGame('game123');Configuration
Configuration Options
interface KxsNetworkOptions {
wsUrl?: string; // WebSocket server URL (default: ws://localhost:3000)
apiUrl?: string; // API base URL (default: http://localhost:3000)
username?: string; // Default username (default: Player)
enableVoiceChat?: boolean; // Enable voice chat (default: false)
heartbeatInterval?: number; // Heartbeat interval in ms (default: 3000)
maxReconnectAttempts?: number; // Reconnection attempts (default: 5)
reconnectDelay?: number; // Delay between reconnections in ms (default: 5000)
}WebSocket Events
Listening to Events
// Connection established
kxs.on('connected', () => {
console.log('Connected to server!');
});
// Disconnection
kxs.on('disconnected', () => {
console.log('Disconnected from server');
});
// Heartbeat received
kxs.on('heartbeat', (data) => {
console.log(`${data.count} players online:`, data.players);
});
// Successful identification
kxs.on('identified', (data) => {
console.log('Session UUID:', data.uuid);
});
// Game started
kxs.on('gameStarted', (data) => {
console.log('Game started with players:', data.players);
});
// Game ended
kxs.on('gameEnded', (data) => {
if ('left' in data) {
console.log(`${data.left} left the game`);
} else {
console.log('Game ended');
}
});
// Kill event
kxs.on('killEvent', (data) => {
console.log(`${data.killer} killed ${data.killed}`);
});
// Chat message
kxs.on('chatMessage', (data) => {
if ('user' in data && 'text' in data) {
console.log(`[${data.user}]: ${data.text}`);
}
});
// Voice chat update
kxs.on('voiceChatUpdate', (data) => {
if ('user' in data) {
console.log(`${data.user} ${data.isVoiceChat ? 'enabled' : 'disabled'} voice chat`);
}
});
// Voice data received
kxs.on('voiceData', (data, username) => {
console.log(`Voice data received from ${username}`);
// Process audio data...
});
// Errors
kxs.on('error', (data) => {
console.error('Error:', data.error);
});WebSocket Actions
Connection Management
// Connect
await kxs.connect();
// Disconnect
kxs.disconnect();
// Check connection status
if (kxs.connected) {
console.log('Connected!');
}Identification and Profile Management
// Identify with default username
kxs.identify();
// Identify with a specific name
kxs.identify('NewUsername', true); // with voice chat enabled
// Change username
kxs.setUsername('AnotherUsername');
// Get current name
console.log('Current name:', kxs.currentUsername);
// Get session UUID
console.log('UUID:', kxs.sessionUuid);Game Management
// Join a game
kxs.joinGame('game123');
// Join with a specific name
kxs.joinGame('game123', 'MyGameUsername');
// Leave current game
kxs.leaveGame();
// Get current game ID
console.log('Current game:', kxs.gameId);
// Report a kill
kxs.reportKill('Killer', 'Victim');Chat and Communication
// Send a chat message
kxs.sendChatMessage('Hello everyone!');
// Enable/disable voice chat
kxs.updateVoiceChat(true);
// Check if voice chat is enabled
if (kxs.voiceChatEnabled) {
console.log('Voice chat enabled');
}
// Send raw voice data
kxs.sendVoiceData(audioData);
// Mute a user
kxs.muteUser('AnnoyingUser');
// Unmute a user
kxs.unmuteUser('AnnoyingUser');
// Get list of muted users
console.log('Muted users:', kxs.mutedUsersList);Audio File Streaming (NodeJS)
The module allows reading and streaming audio files via WebSocket using FFmpeg for quality audio decoding:
Prerequisites
Make sure you have FFmpeg installed on your system:
# On macOS with Homebrew
brew install ffmpeg
# On Ubuntu/Debian
sudo apt update && sudo apt install ffmpeg
# On Windows
# Download FFmpeg from https://ffmpeg.org/download.htmlPlaying an Audio File
// Send an audio file with advanced options
await kxs.sendAudioFile('./audio/music.mp3', {
sampleRate: 48000, // Sample rate (default: 48000)
channels: 1, // Number of channels (default: 1 = mono)
volume: 0.8, // Volume (0.0 to 1.0, default: 1.0)
delayBetweenChunks: 20, // Delay between chunks in ms (default: 20)
onProgress: (progress) => {
console.log(`Sending: ${Math.round(progress * 100)}%`);
},
onEnd: () => {
console.log('Sending completed');
}
});
// Send from a 16-bit PCM Buffer
const fs = require('fs');
const pcmBuffer = fs.readFileSync('./audio/sound.pcm'); // Raw PCM data
await kxs.sendAudioBuffer(pcmBuffer, {
sampleRate: 44100,
channels: 2, // Stereo
volume: 1.0,
delayBetweenChunks: 20
});
// Stop current audio sending (kills FFmpeg process)
kxs.stopAudioSending();Supported Audio Formats
Thanks to FFmpeg, all common audio formats are supported:
- MP3, WAV, FLAC, OGG, AAC
- M4A, WMA, AIFF, AU
- And many more...
Error Handling
try {
await kxs.sendAudioFile('./audio/music.mp3');
} catch (error) {
if (error.message.includes('FFmpeg')) {
console.error('FFmpeg error:', error.message);
console.log('Check that FFmpeg is installed and accessible');
} else {
console.error('Audio error:', error.message);
}
}Other Actions
// Send manual heartbeat
kxs.sendHeartbeat();
// Check script version
kxs.checkVersion();REST API
Public Statistics
// Get online player count
const onlineData = await kxs.getOnlineCount();
console.log(`${onlineData.count} players online`);
// Get player count in a game
const gameData = await kxs.getGamePlayerCount('game123');
console.log(`${gameData.count} players in game`);
// Get latest script version
const script = await kxs.getLatestScript();
console.log('Script retrieved:', script.length, 'characters');
// Use CORS proxy
const resource = await kxs.getCorsResource('https://example.com/api/data');
console.log('Resource retrieved:', resource);Administration (requires admin key)
const adminKey = 'your-admin-key';
// Get server status
const status = await kxs.getServerStatus(adminKey);
console.log('Online players:', status.onlineCount);
console.log('Blacklisted IPs:', status.blacklisted);
console.log('Player details:', status.players);
// Blacklist an IP
const blacklistResult = await kxs.blacklistIp(adminKey, '192.168.1.100', 'Inappropriate behavior');
console.log('IP blacklisted:', blacklistResult);
// Remove an IP from blacklist
const unblacklistResult = await kxs.unblacklistIp(adminKey, '192.168.1.100');
console.log('IP removed from blacklist:', unblacklistResult);Complete Example
import { KxsNetwork } from 'kxs.rip';
class GameClient {
private kxs: KxsNetwork;
constructor() {
this.kxs = new KxsNetwork({
wsUrl: 'wss://kxs.rip',
apiUrl: 'https://kxs.rip',
username: 'MyPlayer',
enableVoiceChat: true,
maxReconnectAttempts: 10
});
this.setupEventListeners();
}
private setupEventListeners() {
this.kxs.on('connected', () => {
console.log('✅ Connected to KxsNetwork server');
this.kxs.identify();
});
this.kxs.on('identified', (data) => {
console.log('🆔 Identified with UUID:', data.uuid);
this.joinRandomGame();
});
this.kxs.on('gameStarted', (data) => {
console.log('🎮 Game started with:', data.players);
});
this.kxs.on('chatMessage', (data) => {
if ('user' in data && 'text' in data) {
console.log(`💬 [${data.user}]: ${data.text}`);
}
});
this.kxs.on('killEvent', (data) => {
console.log(`💀 ${data.killer} eliminated ${data.killed}`);
});
this.kxs.on('error', (data) => {
console.error('❌ Error:', data.error);
});
}
async start() {
try {
await this.kxs.connect();
} catch (error) {
console.error('Unable to connect:', error);
}
}
private async joinRandomGame() {
const gameId = `game_${Math.random().toString(36).substr(2, 9)}`;
this.kxs.joinGame(gameId);
}
sendMessage(text: string) {
this.kxs.sendChatMessage(text);
}
reportKill(killer: string, killed: string) {
this.kxs.reportKill(killer, killed);
}
async getStats() {
const online = await this.kxs.getOnlineCount();
console.log(`📊 ${online.count} players online`);
}
disconnect() {
this.kxs.disconnect();
}
}
// Usage
const client = new GameClient();
client.start();
// Send a message after 5 seconds
setTimeout(() => {
client.sendMessage('Hello everyone!');
}, 5000);
// Get stats after 10 seconds
setTimeout(() => {
client.getStats();
}, 10000);TypeScript Types
The module includes complete TypeScript types:
import {
KxsNetwork,
KxsNetworkOptions,
WebSocketEvents,
PlayerData,
AdminStatusData
} from 'kxs.rip';Error Handling
// Connection error handling
try {
await kxs.connect();
} catch (error) {
console.error('Connection error:', error);
}
// API error handling
try {
const data = await kxs.getOnlineCount();
} catch (error) {
console.error('API error:', error);
}
// Listen to WebSocket errors
kxs.on('error', (data) => {
console.error('WebSocket error:', data.error);
});Advanced Features
Automatic Reconnection
The module automatically handles reconnections in case of connection loss:
const kxs = new KxsNetwork({
maxReconnectAttempts: 10, // 10 max attempts
reconnectDelay: 3000 // 3 seconds between each attempt
});Custom Event Management
// Add a listener
const chatHandler = (data) => {
console.log('Message received:', data);
};
kxs.on('chatMessage', chatHandler);
// Remove a listener
kxs.off('chatMessage', chatHandler);Dynamic Configuration
// Change API URL on the fly
kxs.setApiUrl('https://new-server.com');
// Change WebSocket URL (requires reconnection)
kxs.disconnect();
kxs.setWebSocketUrl('wss://new-server.com');
await kxs.connect();License
This module is licensed under Attribution-NonCommercial-ShareAlike 2.0 Generic (CC BY-NC-SA 2.0).
Support
For any questions or issues, please consult the KxsClient project documentation or open an issue on GitHub.
