eris

repository·dev·Indexed 23 days ago

https://github.com/abalabahaha/eris

A lightweight and efficient NodeJS Discord library wrapper for interfacing with the Discord API. It provides tools for building Discord bots, including support for gateway management via sharding, REST request handling, voice support, and management of guilds, members, roles, channels, and application commands. Version 0.18.0 requires Node.js 10.4 or higher.

Tokens
20.7K
Snippets
3
Records
150
Agent score
81%

What's inside eris

  1. Install Eris

    dev

    Install Eris using npm.

    Requirements:

    • Node.js 10.4 or higher.
    • For voice support: Python 2.7 and a C++ compiler are required.

    Installation Commands:

    • To install without optional dependencies (standard): npm install --no-optional eris
    • To install with voice support: npm install eris (remove the --no-optional flag).
    npm install --no-optional eris
  2. Use REST mode for direct API access

    dev

    When options.restMode is enabled, you can bypass the cache and fetch fresh data directly from the Discord REST API using getREST* methods. This is useful for data that changes frequently or isn't fully cached.

    Available REST methods include:

    • getRESTChannel(channelID)
    • getRESTGuild(guildID, withCounts)
    • getRESTGuildChannels(guildID)
    • getRESTGuildMember(guildID, memberID)
    • getRESTGuildMembers(guildID, options)
    • getRESTGuildRole(guildID, roleID)

    Note: These methods will reject if restMode is not enabled in the client configuration.

  3. Use the Collection class to manage object sets

    dev

    The Collection class is a specialized Map designed to hold instances of a specific base class (baseObject). It provides utility methods for managing, updating, and iterating over these objects, and can optionally enforce a maximum size (limit).

    Key Features

    • Type Safety: Automatically wraps raw data objects into instances of baseObject when adding them.
    • Automatic Updates: The update() method can either create a new instance or update an existing one based on its id.
    • Size Limiting: If a limit is provided, the collection will automatically remove the oldest items (via iterator order) when the limit is exceeded.
    • Functional Utilities: Includes filter, map, find, reduce, every, and some for easy data manipulation.
  4. Manage Shard connections with the Shard class

    dev

    The Shard class manages an individual WebSocket connection to the Discord gateway. It handles connection lifecycles, heartbeats, identification, and presence updates.

    Key properties:

    • id: The unique ID of the shard.
    • connecting: Boolean indicating if the shard is currently attempting to connect.
    • ready: Boolean indicating if the shard has successfully identified/resumed and is ready to receive events.
    • latency: Current latency between the shard and Discord in milliseconds.
    • status: Current connection status ("disconnected", "connecting", "handshaking", "ready", "identifying", or "resuming").
  5. VoiceChannel properties and data structure

    dev

    A VoiceChannel extends GuildTextableChannel and contains the following specific properties:

    • bitrate: The bitrate of the channel.
    • nsfw: Whether the channel is NSFW.
    • permissionOverwrites: A Collection of PermissionOverwrite objects.
    • position: The position of the channel in the list.
    • rtcRegion: The RTC region ID (null for automatic).
    • status: The voice channel status.
    • userLimit: The maximum number of users allowed in the channel.
    • videoQualityMode: The camera video quality mode (1 for auto, 2 for 720p).
    • voiceMembers: A Collection of Member objects currently in the channel.
  6. How reaction buttons work in commands

    dev

    The CommandClient supports interactive command responses using reaction buttons. When a command is executed, you can attach buttons that users can click via emoji reactions.

    Configuration

    In your command options, provide a reactionButtons array:

    • emoji: The emoji to watch (use name:id for custom emojis).
    • type:
      • 'edit': The response message is edited to the new content.
      • 'cancel': The message is unwatched (cleaned up).
    • response: The content to switch to. If a function, it receives (msg, args, userID).
    • filter: An optional function (msg, emoji, userID) => boolean to restrict which users can trigger the button.
    • reactionButtonTimeout: Time in milliseconds before the buttons stop working (default: 60000).

    Lifecycle

    1. The command executes and returns a response.
    2. The client adds reactions to the response message.
    3. The client tracks the message in activeMessages.
    4. When a user reacts, the client executes the corresponding action.execute and either edits or cancels the interaction.
  7. ThreadChannel properties and metadata

    dev

    A ThreadChannel extends GuildTextableChannel and provides specific properties related to thread state and activity:

    Core Properties

    • ownerID: The ID of the user that created the thread.
    • memberCount: Approximate number of users in the thread (capped at 50).
    • messageCount: Number of messages (excluding starter and deleted messages).
    • totalMessageSent: Total number of messages ever sent in the thread.
    • lastPinTimestamp: Timestamp of the last pinned message (as a Number/Date).
    • member: The ThreadMember object for the current user, if they have joined.
    • members: A Collection<ThreadMember> of all members in the channel.

    threadMetadata

    An object containing:

    • archived: Boolean indicating if the thread is archived.
    • archiveTimestamp: Timestamp of the last archive status change.
    • autoArchiveDuration: Duration in minutes for automatic archiving (60, 1440, 4320, or 10080).
    • locked: Boolean indicating if the thread is locked.
    • createTimestamp: Timestamp when the thread was created (for threads created after 09 January 2022).
  8. Initialize the Eris Client

    dev
    To use Eris, instantiate the Client class with your Discord bot token. Bot tokens should be prefixed with Bot (e.g., Bot MTEx...). You can provide an optional options object to configure the client's behavior, such as intents, sharding, and REST settings.
  9. Initialize CommandClient

    dev

    To create a Discord bot with built-in command handling, instantiate CommandClient. It extends the standard Eris Client and accepts a token, options (standard Eris client options), and commandOptions to configure the command framework.

    Command Options

    • argsSplitter: Function to split command arguments. Defaults to splitting by consecutive whitespace: (str) => str.split(/\s+/g).
    • defaultCommandOptions: Object containing default settings for all commands (e.g., invalidUsageMessage).
    • defaultHelpCommand: Boolean. If true (default), a help command is automatically registered.
    • description: String. Description shown in the help command.
    • ignoreBots: Boolean. If true (default), ignores messages from other bot accounts.
    • ignoreSelf: Boolean. If true (default), ignores the bot's own messages.
    • name: String. The bot name shown in the help command.
    • owner: String. The owner's name shown in the help command.
    • prefix: String or Array of Strings. The command prefix. Use @mention to automatically use the bot's actual mention.
  10. Create a basic Discord bot with Eris

    dev

    To start a bot, instantiate the Eris class with your bot token and an options object specifying your intents. You must call .connect() to establish the connection to Discord. You can listen to events like ready, error, and messageCreate using the .on() method.

    const Eris = require("eris");
    
    // Replace TOKEN with your bot account's token
    const bot = new Eris("Bot TOKEN", {
        intents: [
            "guildMessages"
        ]
    });
    
    bot.on("ready", () => { // When the bot is ready
        console.log("Ready!"); // Log "Ready!"
    });
    
    bot.on("error", (err) => {
      console.error(err); // or your preferred logger
    });
    
    bot.on("messageCreate", (msg) => { // When a message is created
        if(msg.content === "!ping") { // If the message content is "!ping"
            bot.createMessage(msg.channel.id, "Pong!");
            // Send a message in the same channel with "Pong!"
        } else if(msg.content === "!pong") { // Otherwise, if the message is "!pong"
            bot.createMessage(msg.channel.id, "Ping!");
            // Respond with "Ping!"
        }
    });
    
    bot.connect(); // Get the bot to connect to Discord
  11. Configure ShardManager concurrency

    dev

    The ShardManager uses a concurrency option to manage how many shards attempt to connect at the same time. This helps prevent hitting gateway rate limits during startup or reconnection.

    By default, concurrency is set to 1. You can adjust this value using setConcurrency(concurrency) on the ShardManager instance.

  12. Configure Eris Client options

    dev

    The Client constructor accepts an options object. Key configuration areas include:

    Intents

    options.intents: A list of intent names, pre-shifted intent numbers, or a raw bitmask. By default, all non-privileged intents are enabled. Note that some intents (like guildPresences or guildMembers) must be enabled in the Discord Developer Portal.

    Sharding

    • options.maxShards: Total number of shards. Use 'auto' to let Eris determine the count via Discord.
    • options.shardConcurrency: Number of shards to start simultaneously. Use 'auto' for Discord's recommended concurrency.
    • options.firstShardID: The ID of the first shard to run.
    • options.lastShardID: The ID of the last shard to run.

    REST Configuration

    options.rest: An object for configuring the REST request handler:

    • options.rest.domain: The domain for API requests (defaults to discord.com).
    • options.rest.baseURL: The base URL for API requests.
    • options.rest.requestTimeout: Milliseconds before REST requests timeout.
    • options.rest.ratelimiterOffset: Milliseconds to offset ratelimit timing calculations.
    • options.rest.latencyThreshold: Average request latency at which Eris emits latency errors.
    • options.rest.restMode: Whether to enable getting objects over REST (recommended to check cache first).

    Other Options

    • options.allowedMentions: Default mentions allowed in createMessage/editMessage. Can specify everyone, repliedUser, roles (boolean or array of IDs), and users (boolean or array of IDs).
    • options.compress: Whether to request WebSocket data to be compressed.
    • options.defaultImageFormat: Default format for avatars/icons ("jpg", "png", "gif", or "webp").
    • options.defaultImageSize: Default size for images (power of two between 16 and 2048).