hgi-discord v2.0.2
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
- Copy
.env.example
to.env
- 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: "user@example.com",
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).