OceanicJS

repository·dev·Indexed 43 days ago

https://github.com/oceanicjs/oceanic

A high-performance Discord client library for Node.js (v1.15.0) providing a robust API for interacting with the Discord API. It supports voice functionality via @discordjs/voice, various compression and encoding optimizations (zlib, zstd, erlpack), and comprehensive mapping of Discord data models to JavaScript classes.

Tokens
26.8K
Snippets
70
Records
90
Agent score
53%

What's inside OceanicJS

  1. Quickstart: Initialize a Client

    dev

    To start using oceanic.js, instantiate a new Client with your bot token and call .connect().

    Important: Always attach a listener for the error event. If you do not, any errors will throw an UncaughtError and may terminate your process.

    const { Client } = require("oceanic.js");
    const client = new Client({ token: "[TOKEN]" });
    
    client.on("ready", async() => {
        console.log("Ready as", client.user.tag);
    });
    
    // Always add an error listener to prevent process termination
    client.on("error", (err) => {
        console.error("Something Broke!", err);
    });
    
    client.connect();
  2. Install oceanic.js with voice support

    dev

    To enable voice support (provided by @discordjs/voice), you must include optional dependencies during installation.

    Requirements:

    • NodeJS 22.12.0 or higher.
    npm i oceanic.js --include=optional
  3. Install oceanic.js

    dev

    Install the standard version of oceanic.js using npm. This version omits optional dependencies like voice support and specific compression libraries.

    Requirements:

    • NodeJS 18.13.0 or higher.
    npm i oceanic.js --omit=optional
  4. Install development builds of oceanic.js

    dev

    If you want to use the latest in-development versions, install directly from the development package registry. Note that the documentation for dev builds always reflects the latest commit.

    npm i https://pkg.pr.new/oceanic.js@dev
  5. Manage Sharding and Gateway

    dev

    For large-scale bots, Oceanic provides tools to manage multiple WebSocket connections (shards):

    • Shard: Represents a single connection to the Discord Gateway.
    • ShardManager: Orchestrates multiple Shard instances.
    • Dispatcher: Handles the dispatching of gateway events.
  6. Access client user and application properties

    dev

    The client.user and client.application properties provide access to the bot's own user and application data.

    Note: These properties will throw an UncachedError if you attempt to access them before the client is connected via a gateway (and no shard is READY) or if you have not enabled restMode. If you are using the client for REST-only purposes, ensure you call await client.restMode() first.

    // Requires gateway connection or restMode() to be called first
    console.log(client.user.username);
    console.log(client.application.id);
  7. Handle AuditLog changes with StandardAuditLogChange and RoleAuditLogChange

    dev

    Audit log entries contain a changes array that describes what was modified. There are two types of changes:

    1. StandardAuditLogChange: Used for most property updates. It contains a key, an optional old_value, and an optional new_value.
    2. RoleAuditLogChange: Specifically used for role additions or removals. It uses special keys $add or $remove and provides a new_value containing an array of objects with id and name.

    An AuditLogChange is a union of these two types.

  8. Structure of AuditLog and RawAuditLog

    dev

    OceanicJS provides two primary interfaces for handling audit log data: RawAuditLog and AuditLog.

    • RawAuditLog represents the raw data structure received directly from the API (using snake_case keys).
    • AuditLog represents the processed, high-level structure used within the library (using camelCase keys and instantiated class structures).

    Both interfaces contain collections for:

    • applicationCommands / application_commands
    • autoModerationRules / auto_moderation_rules
    • entries / audit_log_entries
    • guildScheduledEvents / guild_scheduled_events
    • integrations / integrations
    • threads / threads
    • users / users
    • webhooks / webhooks
  9. Configure Gateway Intents

    dev

    Intents define which events your client receives from the Gateway. They are categorized into NonPrivilegedIntents and PrivilegedIntents.

    Privileged Intents (which require specific authorization in the developer portal) include:

    • GUILD_MEMBERS
    • GUILD_PRESENCES
    • MESSAGE_CONTENT

    Use the Intents enum to specify bitwise values for the events you wish to subscribe to.

    // Example of using Intents bitwise values
    const myIntents = Intents.GUILDS | Intents.GUILD_MESSAGES | Intents.DIRECT_MESSAGES;
  10. Access Discord Structures

    dev

    Oceanic maps Discord's data models to rich JavaScript classes. Key structures include:

    • Users & Members: User, Member, ExtendedUser.
    • Guilds: Guild, Role, Invite, GuildPreview, GuildScheduledEvent.
    • Channels: Channel, GuildChannel, TextChannel, VoiceChannel, ThreadChannel, ForumChannel, StageChannel, AnnouncementChannel.
    • Messages: Message, Attachment, Webhook.
    • Other: AuditLogEntry, VoiceState, Permission.
  11. Override default Gateway behavior

    dev

    The OverrideOptions interface allows you to intercept and replace default Gateway processes. This is useful for custom proxying or specialized gateway handling.

    Available overrides:

    • url(shard, totalShards): Replace the gateway URL shards connect to. Warning: This is called multiple times for multiple shards; ensure the implementation is efficient or cached.
    • resumeURL(shard, totalShards): Replace the resume_url received from Discord.
    • getBot(): Replace the response normally received from GET /gateway/bot.
    • appendQuery: Boolean to determine if compression/version info should be appended to the query string.
    const options: GatewayOptions = {
        override: {
            url: async (shard, totalShards) => {
                return `https://custom-gateway.example.com/ws/${shard}?v=10`;
            },
            appendQuery: false
        }
    };
  12. Handle Discord Interactions

    dev

    Oceanic provides specialized classes for different types of interactions received from the gateway. Common interaction types include:

    • Interaction: The base class for all interactions.
    • CommandInteraction: For slash commands.
    • ComponentInteraction: For button, select menu, and other component clicks.
    • AutocompleteInteraction: For autocomplete suggestions in commands.
    • ModalSubmitInteraction: For form submissions via modals.
    • PingInteraction: For heartbeat/ping checks.

    Use these classes to access interaction-specific data like options, components, or user information.