npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hgi-discord

v2.0.2

Published

Send log messages to Discord

Readme

HGI Discord

A Node.js service for sending messages and logging to Discord channels. Supports both ES Modules (import) and CommonJS (require) and provides rich message formatting with embeds.

All messages are logged to the console by default. When Discord is activated (via DISCORD_ON=true), messages will be sent to both the console and Discord.

Installation

npm install

For use in other projects:

npm install hgi-discord

Requirements

  • Node.js >=14.16

Setup

  1. Copy .env.example to .env
  2. Add your Discord configuration to the .env file:
DISCORD_TOKEN=your_discord_bot_token
DISCORD_ON=true
DISCORD_SERVER=your_discord_server_name
DISCORD_CHANNEL=your_discord_channel_name
DISCORD_NAME=YourApp

Usage

This package supports both ES Modules (import) and CommonJS (require) syntax.

ES Modules (Modern Syntax)

// Using ES Modules syntax with import
import { createDiscordClient, DiscordService } from 'hgi-discord';

// Create a client using environment variables
const discord = createDiscordClient();

// Send a text message
discord.sendMessage('Hello from my application!');

// Send a file attachment
discord.sendAttachment('Here is a file', 'File content', 'example.txt');

CommonJS (Legacy Syntax)

// Using CommonJS syntax with require
const { createDiscordClient, DiscordService } = require('hgi-discord');

// Create a client using environment variables
const discord = createDiscordClient();

// Send a text message
discord.sendMessage('Hello from my application!');

// Send a file attachment
discord.sendAttachment('Here is a file', 'File content', 'example.txt');

Singleton Pattern

The DiscordService uses a singleton pattern to ensure only one connection to Discord is established, regardless of how many times you initialize the client in your application:

// In file1.js
const { createDiscordClient } = require('hgi-discord');
const client1 = createDiscordClient({ discordName: 'Service1' });

// In file2.js
const { createDiscordClient } = require('hgi-discord');
const client2 = createDiscordClient({ discordName: 'Service2' });

// Both client1 and client2 reference the same instance
// The discordName from the first initialization is used
console.log(client1 === client2); // true
console.log(client1.getDiscordName()); // 'Service1'
console.log(client2.getDiscordName()); // 'Service1'

This means:

  • You can safely import and initialize the client in multiple files
  • Only one connection to Discord will be established
  • The configuration from the first initialization is used for all instances
  • For testing purposes, you can reset the singleton with DiscordService.resetInstance()

Working with Subclasses

The singleton pattern is designed to work correctly with subclasses. If you extend DiscordService, each subclass will be properly instantiated instead of returning the singleton instance:

// Define a custom logging service that extends DiscordService
class MyLogger extends DiscordService {
  constructor(options) {
    super(options);
    // Custom initialization...
  }
  
  // Override methods as needed
  logMessage(message, level = 'info') {
    // Your custom implementation
    // (Required when extending DiscordService)
  }
}

// The singleton pattern doesn't affect subclasses
const client = createDiscordClient(); // Creates or returns singleton
const logger = new MyLogger({ discordName: 'MyLogger' }); // Creates new subclass instance

console.log(client instanceof DiscordService); // true
console.log(logger instanceof DiscordService); // true
console.log(logger instanceof MyLogger); // true
console.log(client === logger); // false - different instances

Message Types with Embeds

The package provides several helper methods for sending different types of messages with appropriate colors:

// Information message (blue)
discord.log('Information Title', 'This is an informational message');

// Success message (green)
discord.sendSuccessMessage('Success Title', 'Operation completed successfully');

// Error message (red)
discord.sendErrorMessage('Error Title', 'An error occurred');

// Warning message (yellow)
discord.sendWarningMessage('Warning Title', 'This is a warning message');

// Custom embed with full customization
discord.sendEmbedMessage({
  color: DiscordService.Color.SUCCESS, // Or use a custom hex color like 0x7289da
  title: 'My Message Title',
  description: 'This is the message content',
  author: {
    name: 'Author Name',
    url: 'https://example.com',
    iconUrl: 'https://example.com/icon.png'
  },
  footer: 'Footer text',
  timestamp: true // Adds current timestamp to the message
});

Error Handling

The service automatically handles Error objects in any of the message methods:

try {
  // Some code that might throw an error
  throw new Error('Something went wrong');
} catch (error) {
  // Send the error with formatted stack trace
  discord.sendErrorMessage('Operation Failed', error, {
    footer: 'Error reported automatically'
  });
  
  // You can also pass the error directly to sendMessage
  discord.sendMessage(error);
  
  // Or any other message method
  discord.log('Information', error);
}

JSON Object Logging

The logMessage method supports different parameter formats:

// Basic string message with level
logger.logMessage("Application started successfully", "success");

// JSON object with message and level properties
logger.logMessage({
  message: "This is a structured log message",
  level: "error" // Optional, defaults to "info" if not provided
});

// Any JSON object without specific properties - will be stringified
logger.logMessage({
  email: "[email protected]",
  action: "login",
  ip: "192.168.1.1",
  timestamp: new Date().toISOString()
});

// Error objects are automatically handled
try {
  // Your code that might throw
  JSON.parse('invalid json');
} catch (error) {
  // The Error object will be automatically handled
  logger.logMessage(error);
}

// Error objects in JSON
logger.logMessage({
  error: new Error('Database connection failed')
});

Logging Behavior

By default, the module logs all messages to the console, providing immediate feedback during development.

  • When DISCORD_ON=false or Discord token is missing:
    • All messages are logged to the console only
    • No attempt is made to connect to Discord

Available Colors

  • DiscordService.Color.ERROR: Red (0xfc033d)
  • DiscordService.Color.SUCCESS: Green (0x07f275)
  • DiscordService.Color.ACTION: Yellow (0xf2cf07)
  • DiscordService.Color.MESSAGE: Blue (0x076df2)

You can also use any valid hex color code as a number (e.g., 0x7289da for Discord blue).