JSPM

discord-notify

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 8
  • Score
    100M100P100Q29756F
  • License MIT

A Discord API-compliant notification service for Node.js applications with file attachments, thread support, and rich embeds

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

npm downloads
wakatime

Join My Dev Community

Join Devlander on Discord
Join Devlander on Twitch
Reddit Follow Landon Johnson On Twitter
Join the discussion on Github

๐Ÿ“‹ Changelog

Keep a Changelog Semantic Versioning Conventional Commits

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

  1. Clone the repository:

    git clone https://github.com/yourusername/discord-notify.git
    cd discord-notify
  2. Install dependencies:

    npm install
  3. Build the package:

    npm run build
  4. Run tests:

    npm test

Discord Webhook Setup

Before using Discord Notify, you need to create a Discord webhook:

Step 1: Create a Discord Webhook

  1. Go to your Discord server settings
  2. Navigate to Integrations > Webhooks
  3. Click "New Webhook"
  4. Choose a channel and give it a name (e.g., "Notifications")
  5. 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 URL
    • appName (string, optional): Name of your application (default: 'Discord Notify')
    • environment (string, optional): Environment name (default: 'development')
    • username (string, optional): Override webhook username
    • avatarUrl (string, optional): Override webhook avatar URL
    • threadId (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:

  1. Create a thread in your Discord channel
  2. Right-click the thread and copy its ID
  3. Use the thread ID in sendToThread() or set it as default in config

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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!

Join Devlander on Discord

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:

If you encounter any issues or have questions, please open an issue on GitHub or join our Discord community for real-time support!