@feizk/gateway
v1.0.0
Published
TypeScript WebSocket client for the Discord Gateway API
Downloads
7
Maintainers
Readme
@feizk/gateway
A TypeScript WebSocket client for the Discord Gateway API with full lifecycle management, intelligent reconnection, and comprehensive error handling.
Part of the Feizk Discord ecosystem - a collection of powerful, type-safe packages for Discord bot development.
✨ Features
- 🚀 Full Gateway Support: Complete Discord Gateway API v10 implementation
- 🔄 Smart Reconnection: Exponential backoff with resume capability
- 💓 Heartbeat Management: Automatic heartbeat with timeout detection
- 🎯 Type-Safe Events: Strongly typed event system for all Gateway events
- 🛠️ Rich Error Context: Detailed error information with recovery suggestions
- 🔧 Sharding Support: Basic shard configuration (manager coming soon)
- 📦 Modern TypeScript: Built with strict TypeScript for excellent DX
- 🧪 Well Tested: Comprehensive test suite with high coverage
📦 Installation
npm install @feizk/gateway
# or
yarn add @feizk/gateway
# or
pnpm add @feizk/gateway🚀 Quick Start
import { GatewayClient, GatewayIntent } from '@feizk/gateway';
const client = new GatewayClient({
token: 'your-bot-token',
intents: GatewayIntent.Guilds | GatewayIntent.GuildMessages,
});
// Listen for when the bot is ready
client.on('ready', data => {
console.log(`🤖 Connected as ${data.user.username}!`);
console.log(`📊 Serving ${data.guilds.length} guilds`);
});
// Handle errors gracefully
client.on('error', error => {
console.error('❌ Gateway error:', error.getDetailedMessage());
console.log('💡 Suggestions:', error.getRecoverySuggestions());
});
// Listen for connection state changes
client.on('stateChange', (newState, oldState) => {
console.log(`🔄 Connection state: ${oldState} → ${newState}`);
});
// Connect to Discord
await client.connect();📚 Advanced Usage
Event Handling
// Listen to specific Discord events
client.on('dispatch', (eventName, data) => {
switch (eventName) {
case 'GUILD_CREATE':
console.log('Joined guild:', data.name);
break;
case 'MESSAGE_CREATE':
console.log('New message:', data.content);
break;
}
});
// Listen to Gateway lifecycle events
client.on('hello', data => {
console.log(`Heartbeat interval: ${data.heartbeat_interval}ms`);
});
client.on('resumed', () => {
console.log('Session resumed successfully');
});
client.on('reconnect', () => {
console.log('Discord requested reconnection');
});Sharding Configuration
const client = new GatewayClient({
token: 'your-bot-token',
intents: GatewayIntent.Guilds,
shard: [0, 2], // Shard 0 of 2 total shards
});
console.log('Shard info:', client.shard); // [0, 2]Custom Configuration
const client = new GatewayClient({
token: 'your-bot-token',
intents: GatewayIntent.Guilds | GatewayIntent.GuildMessages,
// Custom Gateway URL (usually not needed)
gatewayUrl: 'wss://gateway.discord.gg/?v=10&encoding=json',
// Reconnection settings
maxReconnectAttempts: 10,
reconnectDelay: 2000,
maxReconnectDelay: 60000,
// Large guild optimization
largeThreshold: 100,
// Initial presence
presence: {
status: 'online',
since: null,
activities: [],
afk: false,
},
});Session Management
// Access session information
console.log('Session ID:', client.session.id);
console.log('Last sequence:', client.session.sequence);
// Check connection state
console.log('Connected:', client.connected);
console.log('State:', client.state);Error Handling
client.on('error', error => {
// Rich error context
console.log('Error code:', error.code);
console.log('Operation:', error.context.operation);
console.log('Connection state:', error.context.connectionState);
console.log('Last sequence:', error.context.lastSequence);
// Get detailed information
console.log(error.getDetailedMessage());
// Get recovery suggestions
error.getRecoverySuggestions().forEach(suggestion => {
console.log('💡', suggestion);
});
// JSON serialization for logging
console.log(JSON.stringify(error.toJSON(), null, 2));
});Presence Updates
// Update bot presence
client.updatePresence({
status: 'dnd',
since: null,
activities: [
{
name: 'with Discord API',
type: 0, // Playing
},
],
afk: false,
});Graceful Shutdown
process.on('SIGINT', async () => {
console.log('Shutting down...');
await client.disconnect();
process.exit(0);
});🎯 Gateway Intents
The package re-exports all Discord Gateway intents for convenience:
import { GatewayIntent } from '@feizk/gateway';
// Common combinations
const basicIntents = GatewayIntent.Guilds | GatewayIntent.GuildMessages;
const allIntents =
GatewayIntent.Guilds |
GatewayIntent.GuildMembers |
GatewayIntent.GuildMessages |
GatewayIntent.GuildMessageReactions |
GatewayIntent.DirectMessages;
// Privileged intents (require enabling in Discord Developer Portal)
const privilegedIntents =
GatewayIntent.GuildMembers | GatewayIntent.GuildPresences | GatewayIntent.MessageContent;🔧 Connection States
The client goes through various connection states:
disconnected: Not connected to Discordconnecting: Establishing WebSocket connectionconnected: Successfully connected and readyresuming: Attempting to resume previous sessionreconnecting: Reconnecting after connection loss
🛠️ Utility Functions
import {
validateToken,
getGatewayUrl,
calculateIntents,
hasIntent,
exponentialBackoff,
} from '@feizk/gateway';
// Validate token format
const isValid = validateToken('your-token');
// Get Gateway URL for specific API version
const url = getGatewayUrl(10);
// Work with intents
const totalIntents = calculateIntents([GatewayIntent.Guilds, GatewayIntent.GuildMessages]);
const hasGuildIntent = hasIntent(totalIntents, GatewayIntent.Guilds);
// Calculate backoff delay
const delay = exponentialBackoff(attemptNumber);🧪 Testing
The package includes comprehensive tests:
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch🏗️ Building
# Build the package
npm run build
# Build in development mode with watch
npm run dev
# Type check
npm run typecheck📋 API Reference
GatewayClient
Constructor Options
| Option | Type | Default | Description |
| ---------------------- | ------------------ | ------- | ----------------------------------- |
| token | string | - | Discord bot token (required) |
| intents | number | - | Gateway intents bitfield (required) |
| gatewayUrl | string | Auto | Discord Gateway URL |
| shard | [number, number] | - | Shard info [id, count] |
| largeThreshold | number | 50 | Large guild member threshold |
| presence | object | - | Initial presence data |
| maxReconnectAttempts | number | 5 | Max reconnection attempts |
| reconnectDelay | number | 1000 | Base reconnection delay (ms) |
| maxReconnectDelay | number | 30000 | Max reconnection delay (ms) |
Methods
connect(): Promise<void>- Connect to Discord Gatewaydisconnect(code?, reason?): Promise<void>- Disconnect from Gatewaysend(payload): void- Send raw payload to GatewayupdatePresence(presence): void- Update bot presence
Properties
state: ConnectionState- Current connection stateconnected: boolean- Whether client is connectedsession: object- Session ID and sequence numbershard?: [number, number]- Shard information
Events
ready- Bot is ready (receives ready data)resumed- Session resumed successfullyhello- Received hello from Discordheartbeat- Heartbeat sent (receives sequence number)heartbeatAck- Heartbeat acknowledgedinvalidSession- Session invalidated (receives resumable boolean)reconnect- Discord requested reconnectiondispatch- Gateway event received (receives event name and data)raw- Raw Gateway payload (receives full payload)error- Error occurred (receives GatewayError)close- WebSocket closed (receives code and reason)stateChange- Connection state changed (receives new and old state)
🤝 Contributing
We welcome contributions! Please see our contributing guidelines for details.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Related Packages
@feizk/rest- Discord REST API client (coming soon)@feizk/core- High-level Discord bot framework (coming soon)@feizk/voice- Discord voice connections (coming soon)
🆘 Support
Made with ❤️ by the Feizk team. Happy bot building! 🤖
