npm package: @gbrlstr/kick-flow
Description: A modern TypeScript library for the Kick.com API with automatic OAuth 2.1 management.
Author: Gabriel Carlos
Latest version: 1.0.5

# Kick Flow

[![npm package][npm-img]][npm-url]
[![Downloads][downloads-img]][downloads-url]
[![Issues][issues-img]][issues-url]

> This project is not affiliated with or endorsed by [Kick.com API](https://docs.kick.com/apis). This is an independent, community-driven library for interacting with the Kick.com API.

> A modern TypeScript library for the [Kick.com API](https://docs.kick.com/apis) with real-time WebSocket chat support.

## ✨ Features

- **🔧 Zero Dependencies** - Built with Node.js native APIs
- **📝 Full TypeScript Support** - Complete type definitions
- **🔐 OAuth 2.1 + PKCE** - Automatic token management
- **🏗️ Modular Design** - Organized API endpoints
- **🚀 Production Ready** - Comprehensive error handling
- **💬 Real-time Chat** - WebSocket connection to Kick.com chat events
- **🔄 Auto-reconnection** - Automatic WebSocket reconnection with retry logic
- **🎯 Multi-chat Support** - Connect to multiple chat rooms simultaneously
- **🛡️ Cloudflare Bypass** - Automatic handling of Kick.com's protection

## 📦 Installation

```bash
npm install @gbrlstr/kick-flow
```

## 🚀 Quick Start

### Basic API Usage

```typescript
import { KickFlow } from '@gbrlstr/kick-flow';

const client = new KickFlow({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
});

// Get channel information
const channel = await client.channels.getChannel('gbrldev');
console.log(`${channel.user.username} has ${channel.followers_count} followers`);

// Get top live streams
const streams = await client.livestreams.getLivestreams({
  sort: 'viewer_count',
  limit: 10
});
```

### Real-time Chat

```typescript
// Connect to chat using channel name
const chatWS = await client.chat.connectToChatByChannel('gbrldev');

// Listen for messages
chatWS.on('message', (message) => {
  console.log(`${message.sender.username}: ${message.content}`);
});

// Connect to WebSocket
await chatWS.connect();
```

## 📖 Examples

We provide comprehensive examples for different use cases:

### 🔥 [Simple API Usage](./examples/simple-api.ts)
Basic demonstration of all API endpoints:
```bash
pnpm tsx examples/simple-api.ts
```

### 💬 [WebSocket Chat](./examples/websocket-simple.ts)
Real-time chat monitoring with automatic channel lookup:
```bash
pnpm tsx examples/websocket-simple.ts
```

### ⚡ [Direct WebSocket](./examples/websocket-direct.ts)
Fast connection using direct chatroom IDs:
```bash
pnpm tsx examples/websocket-direct.ts
```

### 🧠 [Advanced API](./examples/advanced-api.ts)
Error handling, batch operations, and analytics:
```bash
pnpm tsx examples/advanced-api.ts
```

**💡 Pro tip:** Start with `simple-api.ts` to understand the basics, then try `websocket-simple.ts` for real-time chat!

## 🔐 Authentication

### Bot Mode (Server-to-Server)
```typescript
const client = new KickFlow({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
});
```

### User Authentication (OAuth 2.1)
```typescript
const client = new KickFlow({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  redirectUri: 'http://localhost:3000/callback',
});

// Generate auth URL
const pkceParams = client.generatePKCEParams();
const authUrl = client.getAuthorizationUrl(pkceParams, ['public', 'chat:write']);

// Exchange code for token
const token = await client.exchangeCodeForToken({
  code: authorizationCode,
  codeVerifier: pkceParams.codeVerifier,
});
```

## 📡 API Reference

### 📺 Channels
```typescript
// Get channel information (includes followers, live status, etc.)
const channel = await client.channels.getChannel('username');

// Get multiple channels
const channels = await client.channels.getChannels({ 
  slug: ['user1', 'user2'] 
});
```

### 🎮 Categories
```typescript
// Search categories
const categories = await client.categories.getCategories({ q: 'gaming' });

// Get specific category
const category = await client.categories.getCategory(1);
```

### 🔴 Livestreams
```typescript
// Get live streams with filters
const streams = await client.livestreams.getLivestreams({
  category_id: 1,
  language: 'en',
  sort: 'viewer_count',
  limit: 20
});
```

## 💬 Real-time Chat (WebSocket)

### Connect by Channel Name (Recommended)
```typescript
// Automatically gets chatroom ID and connects
const chatWS = await client.chat.connectToChatByChannel('channelname');

// Listen for events
chatWS.on('message', (message) => {
  console.log(`${message.sender.username}: ${message.content}`);
});

chatWS.on('user_joined', (user) => {
  console.log(`${user.username} joined!`);
});

chatWS.on('subscription', (sub) => {
  console.log(`${sub.username} subscribed for ${sub.months} months!`);
});

// Connect
await chatWS.connect();
```

### Direct Connection (Faster)
```typescript
// Connect using known chatroom ID (faster, no API call)
const chatWS = client.chat.connectToChat(12345678);
await chatWS.connect();
```

### Finding Chatroom IDs
If you prefer direct connections, you can find chatroom IDs manually:

1. Open kick.com in your browser
2. Navigate to a channel (e.g., kick.com/xqc)
3. Open Developer Tools (F12)
4. Go to Network tab
5. Look for WebSocket connections or API calls
6. Extract the chatroom ID from the response

Or run: `pnpm tsx examples/websocket-direct.ts guide`

## ⚠️ Error Handling

The library provides specific error types for different scenarios:

```typescript
import {
  KickFlow,
  KickOAuthError,
  KickNotFoundError,
  KickRateLimitError,
} from '@gbrlstr/kick-flow';

try {
  const result = await client.categories.getCategories({ q: 'gaming' });
} catch (error) {
  if (error instanceof KickOAuthError) {
    console.log('OAuth failed:', error.responseBody);
  } else if (error instanceof KickNotFoundError) {
    console.log('Resource not found');
  } else if (error instanceof KickRateLimitError) {
    console.log('Rate limited, retry after:', error.retryAfter, 'seconds');
  }
}
```

## 🛠️ Configuration

```typescript
interface KickFlowConfig {
  clientId: string;           // Kick app client ID
  clientSecret: string;       // Kick app client secret
  redirectUri?: string;       // OAuth redirect URI (optional for bot mode)
  baseUrl?: string;          // API base URL (default: https://api.kick.com)
  oauthUrl?: string;         // OAuth URL (default: https://id.kick.com)
  debug?: boolean;           // Enable debug logging (default: false)
}
```

## 🎯 WebSocket Events

The WebSocket client supports all Kick.com chat events:

- **`message`** - Chat messages (includes replies, emotes)
- **`user_joined`** / **`user_left`** - User presence
- **`subscription`** - New subscriptions
- **`gift_subscription`** - Gift subscriptions
- **`chatroom_updated`** - Chat settings changes
- **`connect`** / **`disconnect`** - Connection status
- **`error`** - Connection errors

## 🔧 Requirements

- **Node.js** >= 18.0.0
- **TypeScript** >= 5.0.0 (for development)
- **Chrome/Chromium** (automatically downloaded by Puppeteer)

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🔗 Links

- [📚 Kick.com API Documentation](https://docs.kick.com/apis)
- [📦 NPM Package](https://www.npmjs.com/package/@gbrlstr/kick-flow)
- [🐙 GitHub Repository](https://github.com/gbrlstr/kick-flow)

---


[downloads-img]: https://img.shields.io/npm/dt/@gbrlstr/kick-flow
[downloads-url]: https://www.npmtrends.com/@gbrlstr/kick-flow
[npm-img]: https://img.shields.io/npm/v/@gbrlstr/kick-flow
[npm-url]: https://www.npmjs.com/package/@gbrlstr/kick-flow
[issues-img]: https://img.shields.io/github/issues/gbrlstr/kick-flow
[issues-url]: https://github.com/gbrlstr/kick-flow/issues