Package Exports
- discord-notify
- discord-notify/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (discord-notify) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Discord Notify
A Discord API-compliant notification service for Node.js applications. Send beautiful, formatted notifications to Discord channels using webhooks with full Discord API compliance.
Hits
Join My Dev Community
๐ Changelog
Features
- ๐ Simple and easy to use
- ๐จ Pre-built notification types (success, error, alert, info)
- ๐ Rich embed support with fields, thumbnails, images, and authors
- ๐ File attachment support
- ๐งต Thread support for organized conversations
- ๐ค Username and avatar overrides
- ๐ง Configurable app name and environment
- ๐ฆ TypeScript support with full type definitions
- โก Lightweight with no external dependencies
- ๐ก๏ธ Discord API compliant with proper error handling
Installation
Quick Install
npm install discord-notify
Manual Setup
Clone the repository:
git clone https://github.com/yourusername/discord-notify.git cd discord-notify
Install dependencies:
npm install
Build the package:
npm run build
Run tests:
npm test
Discord Webhook Setup
Before using Discord Notify, you need to create a Discord webhook:
Step 1: Create a Discord Webhook
- Go to your Discord server settings
- Navigate to Integrations > Webhooks
- Click "New Webhook"
- Choose a channel and give it a name (e.g., "Notifications")
- Copy the webhook URL (it looks like:
https://discord.com/api/webhooks/123456789/abcdef...
)
Step 2: Test Your Webhook
import DiscordNotifyFactory from 'discord-notify';
const notifier = DiscordNotifyFactory({
webhookUrl: 'YOUR_WEBHOOK_URL_HERE'
});
// Test the connection
await notifier.success('๐ Webhook is working!');
Quick Start
Basic Usage
import DiscordNotifyFactory from 'discord-notify';
// Create a notifier instance
const notifier = DiscordNotifyFactory({
webhookUrl: 'https://discord.com/api/webhooks/YOUR_WEBHOOK_URL',
appName: 'My Awesome App',
environment: 'production',
username: 'My Bot', // Optional: Override webhook username
avatarUrl: 'https://example.com/bot-avatar.png' // Optional: Override webhook avatar
});
// Send a simple message
await notifier.send('Hello from my app!');
// Send a success notification
await notifier.success('User registration completed successfully');
// Send an error notification
await notifier.error('Database connection failed');
// Send an alert
await notifier.alert('High memory usage detected');
// Send an info message
await notifier.info('Scheduled backup completed');
// Send to a specific thread
await notifier.sendToThread('Thread message', '1234567890123456789');
// Send with file attachment
await notifier.sendFile(
{ title: 'Log Report', description: 'Application logs for today' },
{ name: 'app.log', data: 'log content here', contentType: 'text/plain' }
);
Advanced Usage Examples
Rich Embed with All Features
await notifier.send({
content: 'Check out this detailed report!',
title: 'Server Status Report',
description: 'Current server metrics and health status',
color: 0x0099ff,
url: 'https://example.com/dashboard',
fields: [
{ name: 'CPU Usage', value: '45%', inline: true },
{ name: 'Memory Usage', value: '67%', inline: true },
{ name: 'Disk Usage', value: '23%', inline: true },
{ name: 'Active Users', value: '1,234', inline: false },
{ name: 'Uptime', value: '99.9%', inline: false }
],
thumbnail: {
url: 'https://example.com/server-icon.png'
},
image: {
url: 'https://example.com/server-graph.png'
},
author: {
name: 'System Monitor',
url: 'https://example.com/monitor',
icon_url: 'https://example.com/monitor-icon.png'
},
footer: {
text: 'Generated by System Monitor',
icon_url: 'https://example.com/footer-icon.png'
}
});
Error Notification with Stack Trace
try {
// Some operation that might fail
throw new Error('Something went wrong');
} catch (error) {
await notifier.error({
title: 'Application Error',
description: error.message,
fields: [
{ name: 'Stack Trace', value: error.stack || 'No stack trace available', inline: false },
{ name: 'Timestamp', value: new Date().toISOString(), inline: true },
{ name: 'Environment', value: process.env.NODE_ENV || 'unknown', inline: true }
]
});
}
File Upload with Logs
import { readFileSync } from 'fs';
// Read log file and send as attachment
const logContent = readFileSync('/var/log/app.log', 'utf8');
const logBuffer = new TextEncoder().encode(logContent);
await notifier.sendFile(
{
title: 'Daily Log Report',
description: 'Application logs for ' + new Date().toLocaleDateString(),
color: 0x00ff00
},
{
name: `app-${new Date().toISOString().split('T')[0]}.log`,
data: logBuffer,
contentType: 'text/plain'
}
);
Thread-based Notifications
// Send to a specific thread for organized conversations
const threadId = '1234567890123456789';
await notifier.sendToThread(
{
title: 'Deployment Started',
description: 'New version deployment initiated',
color: 0xffff00,
fields: [
{ name: 'Version', value: 'v2.1.0', inline: true },
{ name: 'Environment', value: 'production', inline: true }
]
},
threadId
);
// Later, send deployment status to the same thread
await notifier.sendToThread(
{
title: 'Deployment Completed',
description: 'New version successfully deployed',
color: 0x00ff00,
fields: [
{ name: 'Duration', value: '2m 34s', inline: true },
{ name: 'Status', value: 'Success', inline: true }
]
},
threadId
);
Monitoring Integration with Threads
// Create a monitoring system that uses threads for organization
const monitoringThreadId = '1234567890123456789';
setInterval(async () => {
const dbStatus = await checkDatabaseConnection();
const serverStatus = await checkServerHealth();
if (dbStatus.connected && serverStatus.healthy) {
await notifier.sendToThread({
title: 'Health Check Passed',
description: 'All systems operational',
color: 0x00ff00,
fields: [
{ name: 'Database', value: 'โ
Connected', inline: true },
{ name: 'Server', value: 'โ
Healthy', inline: true },
{ name: 'Response Time', value: `${dbStatus.responseTime}ms`, inline: true }
]
}, monitoringThreadId);
} else {
await notifier.sendToThread({
title: 'Health Check Failed',
description: 'Issues detected in system',
color: 0xff0000,
fields: [
{ name: 'Database', value: dbStatus.connected ? 'โ
Connected' : 'โ Failed', inline: true },
{ name: 'Server', value: serverStatus.healthy ? 'โ
Healthy' : 'โ Issues', inline: true },
{ name: 'Error', value: dbStatus.error || serverStatus.error || 'Unknown error', inline: false }
]
}, monitoringThreadId);
}
}, 300000); // Check every 5 minutes
API Reference
DiscordNotifyFactory(config)
Creates a new Discord notifier instance.
Parameters
config
(DiscordNotifyConfig):webhookUrl
(string, required): Your Discord webhook URLappName
(string, optional): Name of your application (default: 'Discord Notify')environment
(string, optional): Environment name (default: 'development')username
(string, optional): Override webhook usernameavatarUrl
(string, optional): Override webhook avatar URLthreadId
(string, optional): Default thread ID for all messages
Returns
A DiscordNotify
instance with the following methods:
Methods
send(args: string | SendArgs): Promise<void>
Sends a basic notification.
// Simple string message
await notifier.send('Hello World!');
// Rich embed with content
await notifier.send({
content: 'Plain text message outside embed',
title: 'User Action',
description: 'A user performed an action',
color: 0x00ff00,
fields: [
{ name: 'User', value: 'john_doe', inline: true },
{ name: 'Action', value: 'login', inline: true }
],
image: {
url: 'https://example.com/image.png'
},
url: 'https://example.com/link'
});
success(args: string | SendArgs): Promise<void>
Sends a success notification with green color and โ emoji.
error(args: string | SendArgs): Promise<void>
Sends an error notification with red color and ๐จ emoji.
alert(args: string | SendArgs): Promise<void>
Sends an alert notification with orange color and โ ๏ธ emoji.
info(args: string | SendArgs): Promise<void>
Sends an info notification with light blue color and โน๏ธ emoji.
extend(args: string | SendArgs): DiscordNotifier
Creates a new notifier that sends multiple embeds in a single message.
const extendedNotifier = notifier.extend({
title: 'Base Information',
description: 'This is the base embed'
});
await extendedNotifier.send({
title: 'Additional Information',
description: 'This will be sent as a second embed'
});
sendFile(args: string | SendArgs, file: FileAttachment): Promise<void>
Sends a notification with a file attachment.
await notifier.sendFile(
{ title: 'Error Log', description: 'Application error details' },
{
name: 'error.log',
data: 'Error details here...',
contentType: 'text/plain'
}
);
sendToThread(args: string | SendArgs, threadId: string): Promise<void>
Sends a notification to a specific Discord thread.
await notifier.sendToThread(
{ title: 'Thread Update', description: 'New information' },
'1234567890123456789'
);
Types
SendArgs
interface SendArgs {
content?: string; // Plain text message (outside of embed)
text?: string; // Legacy alias for content
title?: string;
description?: string;
color?: number;
fields?: DiscordField[];
timestamp?: string;
footer?: {
text: string;
icon_url?: string;
};
thumbnail?: {
url: string;
};
image?: {
url: string;
};
author?: {
name: string;
url?: string;
icon_url?: string;
};
url?: string; // URL for the embed title
}
DiscordField
interface DiscordField {
name: string;
value: string;
inline?: boolean;
}
FileAttachment
interface FileAttachment {
name: string;
data: Uint8Array | string;
contentType?: string;
}
Testing
Run Tests
# Basic functionality tests
npm test
# Unit tests
npm run test:unit
# Integration tests (requires Discord webhook URL)
export DISCORD_WEBHOOK_URL="your_webhook_url"
npm run test:integration
# All tests
npm run test:all
Test Coverage
The test suite covers:
- โ Core functionality
- โ Error handling
- โ Type safety
- โ Integration with Discord API
- โ Performance testing
See tests/README.md for detailed testing information.
๐ Changelog Management
Automated Changelog Generation
This project uses automated changelog generation based on Conventional Commits:
# Generate changelog from git commits
npm run changelog:generate
# View current changelog
cat CHANGELOG.md
Release Process
# Patch release (1.0.0 โ 1.0.1)
npm run release:patch
# Minor release (1.0.1 โ 1.1.0)
npm run release:minor
# Major release (1.1.0 โ 2.0.0)
npm run release:major
Commit Message Format
Use conventional commit format for automatic categorization:
# New feature
git commit -m "feat: add file attachment support"
# Bug fix
git commit -m "fix: handle empty webhook URL gracefully"
# Documentation
git commit -m "docs: update installation guide"
# Breaking change
git commit -m "feat!: change webhook URL parameter to config object"
Changelog Features
- ๐ Automatic categorization by commit type
- ๐ท๏ธ Semantic versioning support
- ๐ GitHub integration with releases
- ๐ Detailed change tracking with commit hashes
- ๐ฏ Migration guides for breaking changes
GitHub Releases
- ๐ Automated releases triggered by version bumps
- ๐ฏ Interactive release manager for manual control
- ๐ Professional release templates with comprehensive notes
- ๐ฆ Asset management with automatic file uploads
- ๐ Full CI/CD integration with testing and deployment
See docs/CHANGELOG_GUIDE.md for comprehensive changelog management documentation. See docs/GITHUB_RELEASES.md for detailed GitHub release information.
Error Handling
The package includes comprehensive error handling that returns detailed information about webhook failures:
// The webhook methods return response information
const response = await notifier.send('Test message');
// Response includes success status, error details, and message ID
Thread Support
To use thread functionality:
- Create a thread in your Discord channel
- Right-click the thread and copy its ID
- Use the thread ID in
sendToThread()
or set it as default in config
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Join Our Discord Community! ๐
Need help? Want to share your projects? Join our growing developer community!
What you'll find in our Discord:
- ๐ Project Showcases - Share what you're building with Discord Notify
- ๐ก Code Reviews - Get feedback on your implementations
- ๐ Bug Reports - Report issues and get help
- ๐ Tutorials - Learn advanced usage patterns
- ๐ค Networking - Connect with other developers
- ๐ฏ Feature Requests - Suggest new features for Discord Notify
Quick Links:
- Discord Server - Main community hub
- GitHub Discussions - Technical discussions
- Twitch Streams - Live coding sessions
- Twitter - Updates and announcements
If you encounter any issues or have questions, please open an issue on GitHub or join our Discord community for real-time support!