npm package: @lorayazilimltd/discord-webhook-manager
Description: 🚀 Easy Discord webhook manager with full TypeScript support. Send messages, embeds & files without discord.js dependency.
Author: KynuxDev
Latest version: 1.0.0

# Discord Webhook Manager

[![npm version](https://badge.fury.io/js/discord-webhook-manager.svg)](https://www.npmjs.com/package/discord-webhook-manager)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Easy-to-use Discord webhook client for Node.js with full TypeScript support. Send messages, embeds, and files without the need for discord.js dependency.

## 🚀 Features

- ✅ **TypeScript Support** - Full type safety and IntelliSense
- ✅ **Zero Discord.js Dependency** - Lightweight and focused
- ✅ **Method Chaining** - Fluent API for embed building
- ✅ **File Uploads** - Support for multiple file attachments
- ✅ **Embed Builder** - Easy embed creation with validation
- ✅ **Error Handling** - Comprehensive error management
- ✅ **Webhook Management** - Get, update, and delete webhooks
- ✅ **Message Editing** - Edit and delete sent messages
- ✅ **ESM & CommonJS** - Both module formats supported

## 📦 Installation

```bash
npm install @lorayazilimltd/discord-webhook-manager
```

```bash
yarn add @lorayazilimltd/discord-webhook-manager
```

```bash
pnpm add @lorayazilimltd/discord-webhook-manager
```

## 🎯 Quick Start

```typescript
import { WebhookClient, EmbedBuilder } from '@lorayazilimltd/discord-webhook-manager';

// Initialize webhook client
const webhook = new WebhookClient('YOUR_WEBHOOK_URL');

// Send a simple message
await webhook.send('Hello Discord!');

// Send an embed
const embed = new EmbedBuilder()
  .setTitle('My Embed')
  .setDescription('This is a test embed')
  .setColor('BLUE')
  .addField('Field Name', 'Field Value')
  .setTimestamp();

await webhook.sendEmbed(embed);
```

## 📚 API Documentation

### WebhookClient

#### Constructor

```typescript
new WebhookClient(webhookURL: string, options?: WebhookClientOptions)
```

**Options:**
- `userAgent?: string` - Custom user agent (default: 'discord-webhook-manager/1.0.0')
- `timeout?: number` - Request timeout in ms (default: 10000)
- `throwErrors?: boolean` - Whether to throw errors or return them (default: true)

#### Methods

##### send(content: string)
Send a simple text message.

```typescript
await webhook.send('Hello World!');
```

##### sendEmbed(embed: EmbedBuilder | EmbedData)
Send an embed message.

```typescript
const embed = new EmbedBuilder()
  .setTitle('Title')
  .setDescription('Description');

await webhook.sendEmbed(embed);
```

##### sendEmbeds(embeds: (EmbedBuilder | EmbedData)[])
Send multiple embeds (max 10).

```typescript
const embed1 = new EmbedBuilder().setTitle('Embed 1');
const embed2 = new EmbedBuilder().setTitle('Embed 2');

await webhook.sendEmbeds([embed1, embed2]);
```

##### sendFile(file: FileData, content?: string, embed?: EmbedBuilder | EmbedData)
Send a file with optional content and embed.

```typescript
const file = {
  name: 'image.png',
  data: Buffer.from('...'),
  contentType: 'image/png'
};

await webhook.sendFile(file, 'Check out this image!');
```

##### sendFiles(files: FileData[], content?: string, embed?: EmbedBuilder | EmbedData)
Send multiple files.

```typescript
const files = [
  { name: 'file1.txt', data: 'Content 1' },
  { name: 'file2.txt', data: 'Content 2' }
];

await webhook.sendFiles(files, 'Multiple files attached');
```

##### sendMessage(payload: MessagePayload)
Send a complex message with full payload control.

```typescript
await webhook.sendMessage({
  content: 'Hello!',
  username: 'Custom Bot Name',
  avatar_url: 'https://example.com/avatar.png',
  embeds: [embed.build()],
  tts: false
});
```

##### getInfo()
Get webhook information.

```typescript
const info = await webhook.getInfo();
console.log(info.name, info.avatar);
```

##### updateInfo(data: WebhookUpdateData)
Update webhook name and/or avatar.

```typescript
await webhook.updateInfo({
  name: 'New Webhook Name',
  avatar: 'base64_image_data'
});
```

##### editMessage(messageId: string, payload: MessagePayload)
Edit a message sent by this webhook.

```typescript
await webhook.editMessage('123456789', {
  content: 'Updated message content'
});
```

##### deleteMessage(messageId: string)
Delete a message sent by this webhook.

```typescript
await webhook.deleteMessage('123456789');
```

##### delete()
Delete the webhook entirely.

```typescript
await webhook.delete();
```

### EmbedBuilder

Create rich embeds with method chaining.

#### Methods

```typescript
const embed = new EmbedBuilder()
  .setTitle('Embed Title')
  .setDescription('Embed description')
  .setURL('https://example.com')
  .setColor('BLUE')
  .setTimestamp()
  .setAuthor('Author Name', 'icon_url', 'author_url')
  .setFooter('Footer Text', 'footer_icon_url')
  .setImage('https://example.com/image.png')
  .setThumbnail('https://example.com/thumb.png')
  .addField('Field Name', 'Field Value', true)
  .addFields(
    { name: 'Field 1', value: 'Value 1', inline: true },
    { name: 'Field 2', value: 'Value 2', inline: true }
  );
```

#### Static Helper Methods

```typescript
// Create pre-formatted embeds
EmbedBuilder.createError('Something went wrong!');
EmbedBuilder.createSuccess('Operation completed!');
EmbedBuilder.createWarning('Be careful!');
EmbedBuilder.createInfo('Just so you know...');
EmbedBuilder.createBasic('Title', 'Description', 'GREEN');
```

#### Validation

```typescript
const validation = embed.isValid();
if (!validation.valid) {
  console.log('Embed errors:', validation.errors);
}

// Get embed character count
console.log('Character count:', embed.length);
```

### Colors

Pre-defined color constants:

```typescript
import { Colors } from 'discord-webhook-manager';

embed.setColor(Colors.RED);
embed.setColor(Colors.GREEN);
embed.setColor(Colors.BLUE);
embed.setColor('RANDOM'); // Random color
embed.setColor('#FF0000'); // Hex color
embed.setColor(0xFF0000); // Number color
```

### File Types

```typescript
interface FileData {
  name: string;                    // Filename
  data: Buffer | Uint8Array | string; // File content
  contentType?: string;            // MIME type (auto-detected if not provided)
}
```

## 🎨 Examples

### Basic Usage

```typescript
import { WebhookClient } from 'discord-webhook-manager';

const webhook = new WebhookClient('YOUR_WEBHOOK_URL');

// Simple message
await webhook.send('Hello Discord!');
```

### Rich Embed

```typescript
import { WebhookClient, EmbedBuilder, Colors } from '@lorayazilimltd/discord-webhook-manager';

const webhook = new WebhookClient('YOUR_WEBHOOK_URL');

const embed = new EmbedBuilder()
  .setTitle('🎉 Server Status')
  .setDescription('All systems operational!')
  .setColor(Colors.GREEN)
  .addField('CPU Usage', '45%', true)
  .addField('Memory Usage', '67%', true)
  .addField('Uptime', '7 days', true)
  .setFooter('Last updated')
  .setTimestamp();

await webhook.sendEmbed(embed);
```

### File Upload

```typescript
import fs from 'fs';

const fileBuffer = fs.readFileSync('screenshot.png');

await webhook.sendFile({
  name: 'screenshot.png',
  data: fileBuffer,
  contentType: 'image/png'
}, 'Here is the latest screenshot!');
```

### Error Handling

```typescript
try {
  await webhook.send('Hello!');
} catch (error) {
  console.error('Failed to send message:', error.message);
}

// Or with throwErrors: false
const webhook = new WebhookClient('URL', { throwErrors: false });
const result = await webhook.send('Hello!');

if (!result.success) {
  console.error('Error:', result.error);
}
```

### Message Management

```typescript
// Send and get message ID
const response = await webhook.send('Original message');
const messageId = response.message?.id;

// Edit the message
if (messageId) {
  await webhook.editMessage(messageId, {
    content: 'Updated message!',
    embeds: [
      new EmbedBuilder()
        .setTitle('Updated')
        .setColor('YELLOW')
        .build()
    ]
  });
  
  // Delete after 10 seconds
  setTimeout(() => {
    webhook.deleteMessage(messageId);
  }, 10000);
}
```

### Webhook Management

```typescript
// Get webhook info
const info = await webhook.getInfo();
console.log(`Webhook: ${info.name} in channel ${info.channel_id}`);

// Update webhook
await webhook.updateInfo({
  name: 'My New Bot Name'
});

// Delete webhook (be careful!)
// await webhook.delete();
```

## ⚠️ Error Handling

The library provides comprehensive error handling:

```typescript
import { WebhookClient } from 'discord-webhook-manager';

// Throws errors by default
const webhook1 = new WebhookClient('URL');

// Returns errors in response
const webhook2 = new WebhookClient('URL', { throwErrors: false });

const result = await webhook2.send('Test');
if (!result.success) {
  console.log('Error code:', result.error?.code);
  console.log('Error message:', result.error?.message);
}
```

## 📋 Limits

Discord has the following limits:

- **Message content**: 2000 characters
- **Embed title**: 256 characters
- **Embed description**: 4096 characters
- **Embed fields**: 25 maximum
- **Field name**: 256 characters
- **Field value**: 1024 characters
- **Footer text**: 2048 characters
- **Author name**: 256 characters
- **Total embed**: 6000 characters
- **Embeds per message**: 10 maximum

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🔗 Links

- [npm package](https://www.npmjs.com/package/@lorayazilimltd/discord-webhook-manager)
- [GitHub repository](https://github.com/KynuxDev/discord-webhook-manager)
- [Discord Developer Portal](https://discord.com/developers/docs/resources/webhook)

## ⭐ Support

If you find this library helpful, please consider giving it a star on GitHub!