# 🎮 Discord PrevNames

> Track Discord username & display name changes in real-time with this unofficial module

![License](https://img.shields.io/badge/license-ISC-blue.svg)
![Version](https://img.shields.io/badge/version-1.0.0-green.svg)
![Platform](https://img.shields.io/badge/platform-Discord-5865F2.svg)
![Node](https://img.shields.io/badge/node-%3E=14-darkgreen.svg)
![Database](https://img.shields.io/badge/records-5M+-orange.svg)
[![Documentation](https://img.shields.io/badge/docs-discprev.xyz-blue.svg)](https://docs.discprev.xyz)

## 📚 Documentation

Full documentation available at: [https://docs.discprev.xyz](https://docs.discprev.xyz)

## 🚀 Overview

Discord PrevNames is an unofficial module that allows you to track and retrieve Discord users' previous usernames and display names. Using Server-Sent Events (SSE), it provides real-time notifications when users change their names and maintains a historical record of these changes. With over 5 million previous names stored in our database, we offer one of the largest Discord name history tracking services available.

## ✨ Key Features

- **Real-time Monitoring** - Get instant notifications when users change their names
- **Display Name Tracking** - Track display name changes in real-time
- **Event-Driven Architecture** - Built with EventEmitter for easy event handling
- **Automatic Reconnection** - Maintains stable connection with automatic retry mechanism
- **Simple API** - Easy-to-use methods for retrieving user history

## 📦 Installation

```bash
npm install discord-prevnames
```

## 🎯 Quick Start

```javascript
const PrevNames = require('discord-prevnames');

async function main() {
    const prevnames = new PrevNames();

    // Listen for name changes
    prevnames.on('prevnamesadd', (data) => {
        console.log('Name change detected:', {
            userId: data.userId,
            type: data.type,
            previousName: data.name,
            changedAt: data.changedAt
        });
    });

    // Get user's name history
    try {
        const history = await prevnames.getUserPrevnames('USER_ID');
        console.log('User history:', history);
    } catch (error) {
        console.error('Error:', error.message);
    }
}

main().catch(console.error);
```

## 📊 Event Data Structure

```typescript
interface NameChangeEvent {
    userId: string;          // Discord User ID
    type: 'displayname';     // Type of name change
    name: string;           // Previous name
    changedAt: string;      // Timestamp of change
}
```

## 🔧 API Reference

For complete API documentation, visit [https://docs.discprev.xyz](https://docs.discprev.xyz)

Below is a quick overview of the main features:

### Class: PrevNames

#### Constructor
```javascript
const prevnames = new PrevNames();
```

#### Methods

**.on(eventName, callback)**
- Listen for name change events
- Returns an unsubscribe function
```javascript
const unsubscribe = prevnames.on('prevnamesadd', (data) => {
    console.log('New name change:', data);
});

// Later, to stop listening
unsubscribe();
```

**.getUserPrevnames(userId)**
- Retrieve user's name history
- Throws error if userId is invalid
```javascript
async function getUserHistory() {
    try {
        const history = await prevnames.getUserPrevnames('123456789');
        console.log('History:', history);
    } catch (error) {
        console.error('Error:', error.message);
    }
}
```

**.stop()**
- Stop listening to name change events
- Removes all event listeners
```javascript
prevnames.stop();
```

## 🌐 API Endpoints

The module interacts with the following endpoints:
```plaintext
GET  /api/users/:userId/prevnames    # Get user's name history
GET  /api/webhooks/prevnames/listen  # Stream real-time name changes
```

## 🔐 Error Handling

The module includes built-in error handling for:
- Invalid user IDs
- Network connection issues
- API response errors
- Event stream disruptions

```javascript
async function handleUserHistory() {
    try {
        const history = await prevnames.getUserPrevnames('invalid_id');
    } catch (error) {
        console.error('Error:', error.message); // "User ID invalid"
    }
}
```

## 📈 Advanced Usage

### Handling Different Name Change Types

```javascript
async function trackNameChanges() {
    const prevnames = new PrevNames();
    
    prevnames.on('prevnamesadd', (data) => {
        if (data.type === 'displayname') {
            console.log(`Display name change for user ${data.userId}`);
            console.log(`Previous name: ${data.name}`);
            console.log(`Changed at: ${new Date(data.changedAt).toLocaleString()}`);
        }
    });
    
    // Example of fetching history alongside listening to changes
    try {
        const history = await prevnames.getUserPrevnames('123456789');
        console.log('Initial history:', history);
    } catch (error) {
        console.error('Error fetching history:', error.message);
    }
}

trackNameChanges().catch(console.error);
```

### Auto-Reconnection Handling

The module automatically handles disconnections and reconnects with a 3-second delay:

```javascript
// The module will automatically:
// 1. Detect disconnections
// 2. Wait 3 seconds
// 3. Attempt to reconnect
// 4. Resume event streaming
```

## 🛠️ Future Features

- [ ] Username change tracking
- [ ] Bulk history retrieval
- [ ] Customizable retry intervals
- [ ] Rate limiting protection
- [ ] Filtered event listening
- [ ] Historical data analysis

## 🤝 Contributing

Contributions are welcome! Feel free to submit issues and pull requests.

## 📝 License

ISC © Discord Prevnames

---

<div align="center">
    <strong>Keep track of Discord name changes with ease</strong>
</div>