### Iterate Over Shards Example Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md An example demonstrating how to iterate through the client's shards using the Symbol.iterator method. ```javascript for (const [id, shard] of client.shards) { console.log(`Shard ${id}: ${shard.status}`); } ``` -------------------------------- ### Complete Oceanic.js Client Initialization Example Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md A comprehensive example demonstrating client initialization with various configurations including allowed mentions, cache limits, image settings, REST, and gateway options. ```typescript import { Client, Intents, Permissions, ChannelTypes } from "oceanic.js"; const client = new Client({ token: process.env.DISCORD_TOKEN, // Mention settings allowedMentions: { everyone: false, users: true, roles: true, repliedUser: false }, // Cache configuration collectionLimits: { messages: 100, members: 1000, guilds: Infinity, privateChannels: 50 }, // Image settings defaultImageFormat: "png", defaultImageSize: 2048, // REST configuration rest: { timeout: 30000 }, // Gateway configuration gateway: { autoReconnect: true, intents: Intents.GUILDS | Intents.GUILD_MEMBERS | Intents.GUILD_MESSAGES | Intents.MESSAGE_CONTENT, largeThreshold: 250, compression: "zlib", presence: { status: "online", activities: [ { name: "for commands", type: 2 // LISTENING } ] } } }); // Error handling client.on("error", (error) => { console.error("Client error:", error); }); // Event handling client.on("ready", () => { console.log(`Ready as ${client.user.username}`); }); client.on("messageCreate", async (message) => { if (message.author.bot) return; if (message.content === "!ping") { await message.reply("Pong!"); } }); // Connect await client.connect(); ``` -------------------------------- ### Install Oceanic.js (Standard) Source: https://github.com/oceanicjs/oceanic/blob/dev/README.md Installs the stable version of the oceanic.js package using npm. This command omits optional dependencies by default. ```bash npm i oceanic.js --omit=optional ``` -------------------------------- ### Install Oceanic.js (Development Build) Source: https://github.com/oceanicjs/oceanic/blob/dev/README.md Installs the latest in-development version of oceanic.js directly from a package registry. Use this for testing the newest features or bug fixes. ```bash npm i https://pkg.pr.new/oceanic.js@dev ``` -------------------------------- ### Get Client Start Time Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves the timestamp when the client was created. Useful for calculating uptime. ```typescript const startTime = client.time.get("start"); const uptime = Date.now() - startTime; ``` -------------------------------- ### Install Oceanic.js with Voice Support Source: https://github.com/oceanicjs/oceanic/blob/dev/README.md Installs oceanic.js including optional dependencies for voice support. Requires NodeJS 22.12.0 or higher. ```bash npm i oceanic.js --include=optional ``` -------------------------------- ### Client Initialization with Intents Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md Example of initializing a new client with specific gateway intents enabled. Ensure all required intents are included for desired event handling. ```typescript const client = new Client({ gateway: { intents: Intents.GUILDS | Intents.GUILD_MEMBERS | Intents.GUILD_MESSAGES | Intents.MESSAGE_CONTENT } }); ``` -------------------------------- ### Basic Bot Setup with Oceanic.js Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Initializes a Discord client with specified intents, logs in, and sets up event listeners for ready, message creation, and errors. Requires DISCORD_TOKEN environment variable. ```typescript import { Client, Intents } from "oceanic.js"; const client = new Client({ token: process.env.DISCORD_TOKEN, gateway: { intents: Intents.GUILDS | Intents.GUILD_MESSAGES | Intents.MESSAGE_CONTENT } }); client.on("ready", () => { console.log("Ready as", client.user.tag); }); client.on("messageCreate", async (message) => { if (message.content === "!ping") { await message.reply("Pong!"); } }); client.on("error", (error) => { console.error("Client error:", error); }); await client.connect(); ``` -------------------------------- ### Manage Member Roles and Status Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Examples for adding roles, setting multiple roles, timing out, kicking, and banning members. Ensure you have the necessary permissions before performing these actions. ```typescript // Add role await member.addRole(roleID); // Set roles await member.edit({ roles: [roleID1, roleID2] }); // Timeout await member.timeout(60000); // 60 seconds // Kick await member.kick("Spamming"); // Ban await guild.ban(userID, { deleteMessageSeconds: 86400 }); ``` -------------------------------- ### Basic Client Setup and Event Handling Source: https://github.com/oceanicjs/oceanic/blob/dev/README.md This snippet demonstrates how to initialize the Oceanic.js client with a token and set up basic event listeners for 'ready' and 'error' events. It's crucial to handle errors to prevent process termination. ```javascript const { Client } = require("oceanic.js"); const client = new Client({ token: "[TOKEN]" }); client.on("ready", async() => { console.log("Ready as", client.user.tag); }); // if you do not add a listener for the error event, any errors will cause an UncaughtError to be thrown, // and your process may be killed as a result. client.on("error", (err) => { console.error("Something Broke!", err); }); client.connect(); ``` -------------------------------- ### Get Bot Gateway Information Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Call `getBotGateway` to retrieve the WebSocket gateway URL and the recommended number of shards for your bot. It also provides details on session start limits, including total, remaining, reset time, and maximum concurrency. ```typescript const gateway = await client.rest.getBotGateway(); console.log(`Need ${gateway.shards} shards`); ``` -------------------------------- ### Accessing Command Options Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Example of how to access command options like name and count from an interaction's options. ```typescript client.on("interactionCreate", (interaction) => { if (interaction instanceof CommandInteraction) { const options = interaction.options; const name = options.getString("name"); const count = options.getInteger("count"); } }); ``` -------------------------------- ### Handling Uncaught Errors in Oceanic.js Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/errors.md Demonstrates how to attach an 'error' event listener to prevent application crashes when an error occurs without a dedicated listener. The 'BAD' example shows a crash scenario, while the 'GOOD' example illustrates proper error handling. ```typescript const client = new Client({ token: "TOKEN" }); client.on("messageCreate", () => { throw new Error("Something broke!"); }); // Process will crash with UncaughtError // GOOD: Attach error listener client.on("error", (error) => { console.error("Client error:", error); }); ``` -------------------------------- ### Get Current Application Info Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Retrieves information about the current bot's application. Use this to access application-specific details. ```typescript async getCurrent(): Promise ``` -------------------------------- ### Handle Interactions Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Listen for interactionCreate events to handle slash commands, buttons, and modals. Use interaction.options to get user input and interaction.reply to respond. ```typescript client.on("interactionCreate", async (interaction) => { if (interaction instanceof CommandInteraction) { const user = interaction.options.getUser("user"); await interaction.reply("Response!"); } }); ``` -------------------------------- ### Example: Check Send Messages Permission Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Demonstrates how to check if a member has the 'SEND_MESSAGES' permission using the Permission class. ```typescript const perms = new Permission(member.permissions); if (perms.has("SEND_MESSAGES")) { // Member can send messages } ``` -------------------------------- ### Configure Gateway Compression with Zstd Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md Sets the gateway connection to use Zstandard compression for reduced bandwidth. Ensure the 'zstd-napi' dependency is installed or Node.js version is 23.8.0+. ```typescript const client = new Client({ gateway: { compression: "zstd" // Use zstd compression } }); ``` -------------------------------- ### User.tag Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Gets the user's tag in 'username#discriminator' format. ```APIDOC ## User.tag ### Description Gets the user's tag in the format "username#discriminator". This is useful for display purposes. ### Method ```typescript get tag(): string ``` ### Example ```typescript console.log(user.tag); // "discord#0001" ``` ``` -------------------------------- ### Configure Manual Sharding Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Manually configure sharding parameters like the total number of shards, the starting shard ID, and the maximum concurrency. This is useful for distributing shards across multiple processes. ```typescript const client = new Client({ token: "TOKEN", gateway: { maxShards: 4, // Total shards to spawn firstShardID: 0, // Start with shard 0 maxConcurrency: 1 // Spawn 1 shard at a time } }); ``` ```typescript // Process 1: Shards 0-1 const client1 = new Client({ token: "TOKEN", gateway: { maxShards: 4, firstShardID: 0, maxConcurrency: 1 } }); // Process 2: Shards 2-3 const client2 = new Client({ token: "TOKEN", gateway: { maxShards: 4, firstShardID: 2, maxConcurrency: 1 } }); ``` -------------------------------- ### Union Types for Flexibility Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/types.md Provides examples of union types used for creating flexible type signatures, such as combining different channel types or user types. ```typescript type AnyGuildChannel = TextChannel | VoiceChannel | CategoryChannel | /* ... */ type AnyUser = User | ExtendedUser; ``` -------------------------------- ### Connect Client to Discord Gateway Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Connect the client to Discord's gateway to start receiving events. Ensure an authentication token is provided and restMode is not enabled. ```typescript client.on("ready", () => { console.log("Connected!"); }); await client.connect(); ``` -------------------------------- ### Get Connected Third-Party Accounts Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Use this method to retrieve a list of connected third-party accounts for the bot. ```typescript async getConnections(): Promise> ``` -------------------------------- ### Graceful Error Handling with Oceanic.js Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/errors.md A comprehensive example demonstrating robust error handling for various Oceanic.js operations. It includes attaching a general error listener and using try-catch blocks to handle specific errors like DiscordRESTError, DiscordHTTPError, RateLimitedError, and DependencyError for voice support. ```typescript import { Client, DiscordRESTError, DiscordHTTPError, RateLimitedError, UncachedError, DependencyError } from "oceanic.js"; const client = new Client({ token: "TOKEN" }); // Always attach error listener client.on("error", (error) => { console.error("Client error:", error); }); // Specific REST error handling try { await client.rest.channels.createMessage(channelID, { content: "Hello!" }); } catch (error) { if (error instanceof DiscordRESTError) { if (error.code === 50001) { console.error("Missing access to channel"); } else if (error.code === 40001) { console.error("Unauthorized"); } else { console.error("API Error:", error.message); } } else if (error instanceof DiscordHTTPError) { console.error("Network error:", error.code); } else if (error instanceof RateLimitedError) { console.error(`Rate limited, wait ${error.delay}ms`); } } // Voice support with dependency check try { const connection = client.joinVoiceChannel({ channelID: voiceChannelID, guildID: guildID, voiceAdapterCreator: () => {} }); } catch (error) { if (error instanceof DependencyError) { console.error("Voice support not available. Install @discordjs/voice"); } } ``` -------------------------------- ### client.rest.webhooks.get Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Retrieves information about a specific webhook. This can be used to get details like the webhook's name, channel, and token. ```APIDOC ## get ### Description Get webhook information. ### Method GET ### Endpoint /webhooks/{webhook.id} ### Parameters #### Path Parameters - **webhookID** (string) - Required - The ID of the webhook to retrieve information for. #### Query Parameters - **token** (string) - Optional - The token of the webhook. If provided, allows fetching webhook details without needing to be in the same channel. ### Response #### Success Response (Webhook) - Returns a Webhook object containing the webhook's details. #### Response Example ```json { "id": "987654321098765432", "name": "My Awesome Webhook", "type": 1, "token": "a_webhook_token", "channel_id": "111111111111111111", "guild_id": "222222222222222222", "avatar": null, "application_id": null, "source_channel": null, "source_guild": null, "url": "https://discord.com/api/webhooks/987654321098765432/a_webhook_token" } ``` ``` -------------------------------- ### getBotGateway Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Retrieves gateway connection information, including the WSS gateway URL and the recommended number of shards for optimal performance. It also provides details about session start limits. ```APIDOC ## getBotGateway() ### Description Get gateway connection info and recommended shard count. ### Method `GET` ### Endpoint `/gateway/bot` ### Parameters None ### Response #### Success Response (200) - **url** (string) - The WSS gateway URL. - **shards** (number) - The recommended shard count. - **sessionStartLimit** (object) - Information about session start limits: - **total** (number) - Total identifies allowed in 24 hours. - **remaining** (number) - Remaining identifies available. - **resetAfter** (number) - Milliseconds until the limit resets. - **maxConcurrency** (number) - Maximum concurrent connections allowed. #### Response Example ```json { "url": "wss://gateway.discord.gg/?v=9&encoding=json", "shards": 1, "sessionStartLimit": { "total": 100, "remaining": 99, "resetAfter": 14400000, "maxConcurrency": 1 } } ``` ``` -------------------------------- ### Initialize Client with Options Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Instantiate the Client with a configuration object. ```typescript const client = new Client(options); ``` -------------------------------- ### Client Constructor Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Initializes a new Discord client instance. Accepts an optional options object for configuration. ```APIDOC ## new Client(options?: ClientOptions) ### Description Creates a new Discord client instance. This is the primary class for interfacing with Discord and extends TypedEmitter. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`ClientOptions`) - Optional - Configuration for the client. **ClientOptions fields:** - **token** (`string`) - Optional - Bot token (auto-prefixed with `Bot `). - **auth** (`string`) - Optional - Full auth header value (alternative to token). - **allowedMentions** (`AllowedMentions`) - Optional - Default mention settings for messages. - **collectionLimits** (`CollectionLimitsOptions`) - Optional - Cache size limits for each entity type. - **defaultImageFormat** (`ImageFormat`) - Optional - Default format for CDN images. - **defaultImageSize** (`number`) - Optional - Default size for CDN images. - **disableCache** (`boolean | "no-warning"`) - Optional - Disable all caching (or with no warning). - **disableMemberLimitScaling** (`boolean`) - Optional - Disable member cache limit scaling for large guilds. - **rest** (`RESTOptions`) - Optional - REST request options (timeouts, etc.). - **gateway** (`GatewayOptions`) - Optional - Gateway connection options. ### Request Example ```typescript const client = new Client({ token: "YOUR_BOT_TOKEN", collectionLimits: { messages: 50, guilds: Infinity } }); ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Get Message Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Fetch a single message from the channel using its unique ID. ```typescript async getMessage(messageID: string): Promise ``` -------------------------------- ### Create a new Discord Client instance Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Instantiate the Client class with custom options for token and collection limits. ```typescript const client = new Client({ token: "YOUR_BOT_TOKEN", collectionLimits: { messages: 50, guilds: Infinity } }); ``` -------------------------------- ### Get Subcommand Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves the selected subcommand name. The option can be optionally required. ```typescript getSubcommand(required?: boolean): string | null ``` -------------------------------- ### ApplicationCommand Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Represents a slash command definition with properties for ID, name, description, options, and permissions. ```APIDOC ## Class: ApplicationCommand Represents a slash command definition. ### Properties | Property | Type | Description | |----------|------|-------------| | id | string | Command ID | | appID | string | Application ID | | guildID | string \| null | Guild ID (null = global) | | name | string | Command name | | description | string | Command description | | options | `CommandOption[]` | Command parameters | | defaultMemberPermissions | number \| null | Default required permissions | | dmPermission | boolean | Allowed in DMs | | nsfw | boolean | Marked as NSFW | | type | `ApplicationCommandType` | Slash / user / message command | ### Methods #### edit(options) ```typescript async edit(options: Types.Applications.EditApplicationCommandOptions): Promise ``` Edit the command. --- #### delete() ```typescript async delete(): Promise ``` Delete the command. --- ``` -------------------------------- ### Get Permission Bitmask Value Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Returns the numerical bitmask value of the current Permission object. ```typescript toJSON(): number ``` -------------------------------- ### Initialize and Connect Oceanic.js Client Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/overview.md This snippet shows how to initialize the Oceanic.js Client with a token, log a message when the client is ready, handle errors, and establish a connection to the Discord gateway. ```typescript import { Client } from "oceanic.js"; const client = new Client({ token: "YOUR_TOKEN" }); client.on("ready", () => { console.log("Ready as", client.user.tag); }); client.on("error", (err) => { console.error("Error:", err); }); await client.connect(); ``` -------------------------------- ### Get Messages Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Fetch multiple messages from the channel. Options can be provided to filter or paginate the results. ```typescript async getMessages(options?: Types.Channels.GetMessagesOptions): Promise> ``` -------------------------------- ### Get Subcommand Group Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves the selected subcommand group name. The option can be optionally required. ```typescript getSubcommandGroup(required?: boolean): string | null ``` -------------------------------- ### connect() Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Connects the client to Discord's gateway, enabling event reception. This method should be called after setting up event listeners. ```APIDOC ## connect() ### Description Connect the client to Discord's gateway and start receiving events. ### Method `async connect(): Promise` ### Throws `TypeError` if no auth token or restMode is enabled. ### Example ```typescript client.on("ready", () => { console.log("Connected!"); }); await client.connect(); ``` ``` -------------------------------- ### Get Attachment Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves an attachment option value by its name. The option can be optionally required. ```typescript getAttachment(name: string, required?: boolean): Attachment | null ``` -------------------------------- ### Handle Client Ready Event Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md Listen for the 'ready' event to know when the client has successfully connected and is ready to process events. This is typically the first event emitted after connection. ```typescript client.on("ready", () => { console.log("Client ready"); }); ``` -------------------------------- ### Get Role Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a role option value by its name. The option can be optionally required. ```typescript getRole(name: string, required?: boolean): Role | null ``` -------------------------------- ### Get Member Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a member option value by its name. The option can be optionally required. ```typescript getMember(name: string, required?: boolean): Member | null ``` -------------------------------- ### Get User Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a user option value by its name. The option can be optionally required. ```typescript getUser(name: string, required?: boolean): User | null ``` -------------------------------- ### Get Boolean Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a boolean option value by its name. The option can be optionally required. ```typescript getBoolean(name: string, required?: boolean): boolean | null ``` -------------------------------- ### restMode(fakeReady?) Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Initializes the client for REST-only operations without establishing a gateway connection. This populates essential client properties like `application` and `user`. ```APIDOC ## restMode(fakeReady?) ### Description Initialize the client for REST-only operation without gateway connection. Populates the `application` and `user` properties. ### Method `async restMode(fakeReady?: boolean): Promise` ### Parameters #### Path Parameters - **fakeReady** (boolean) - Optional - Emit a `ready` event after initialization. Defaults to `true`. ### Returns The client instance (for chaining). ### Example ```typescript const client = new Client({ token: "TOKEN" }); await client.restMode(); console.log("Bot user:", client.user.username); // Can now use REST operations without gateway ``` ``` -------------------------------- ### Handling Slash Commands in Oceanic.js Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Demonstrates how to create a global slash command and handle its interactions. Requires a client instance and interaction event handling. ```typescript import { Client, Intents, Types } from "oceanic.js"; const client = new Client({ /* ... */ }); // Create slash command await client.rest.applications.createGlobalCommand({ name: "greet", description: "Greet a user", options: [ { type: Types.Applications.CommandOptionTypes.USER, name: "user", description: "User to greet", required: true } ] }); // Handle slash command client.on("interactionCreate", async (interaction) => { if (interaction instanceof client.util.CommandInteraction) { const user = interaction.options.getUser("user"); await interaction.reply(`Hello, ${user?.username}ǃ`); } }); ``` -------------------------------- ### Get Number Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a number option value by its name. The option can be optionally required. ```typescript getNumber(name: string, required?: boolean): number | null ``` -------------------------------- ### Set Initial Bot Presence Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Configure the bot's initial status and activities when it connects to the gateway. The 'status' can be 'online', 'idle', 'dnd', or 'invisible'. ```typescript import { Intents } from "oceanic.js"; const client = new Client({ token: "TOKEN", gateway: { presence: { status: "online", // "online", "idle", "dnd", "invisible" activities: [ { name: "with commands", type: 0 // 0=PLAYING, 1=STREAMING, 2=LISTENING, 3=WATCHING, 4=CUSTOM } ] } } }); ``` -------------------------------- ### Get Integer Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves an integer option value by its name. The option can be optionally required. ```typescript getInteger(name: string, required?: boolean): number | null ``` -------------------------------- ### client.rest.oauth.getHelper Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Creates an OAuth helper instance for a given access token. This helper can be used to perform authenticated API requests. ```APIDOC ## getHelper ### Description Create an OAuth helper for a specific token. ### Method N/A (Client-side method) ### Endpoint N/A (Client-side method) ### Parameters #### Path Parameters - **accessToken** (string) - Required - The OAuth access token to create the helper with. ### Response #### Success Response (OAuthHelper) - Returns an OAuthHelper object that can be used for authenticated requests. ### Response Example ``` [OAuthHelper object] ``` ``` -------------------------------- ### Get String Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a string option value by its name. The option can be optionally required. ```typescript getString(name: string, required?: boolean): string | null ``` -------------------------------- ### Get Webhook Information Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Retrieves information about a specific webhook. An optional token can be provided for authentication. ```typescript async get(webhookID: string, token?: string): Promise ``` -------------------------------- ### REST Client Configuration Options Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Configuration options for the REST client constructor. These include request timeout and custom base URL. ```typescript { timeout?: number; // Request timeout in ms baseURL?: string; // Custom API base URL } ``` -------------------------------- ### fetchIntegrations Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Fetch all integrations associated with the guild. ```APIDOC ## fetchIntegrations ### Description Fetch all integrations. ### Method `fetchIntegrations` ### Response #### Success Response - **Array** - An array of Integration objects. ``` -------------------------------- ### Access Select Menu Values Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Example of how to access typed select menu values within a ComponentInteraction. ```typescript client.on("interactionCreate", (interaction) => { if (interaction instanceof ComponentInteraction) { if (interaction.data.customID === "role-select") { const roles = interaction.data.resolved?.roles; const roleIDs = interaction.values; } } }); ``` -------------------------------- ### getVoiceConnection(guildID) Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Retrieves the active voice connection for a given guild. Requires the `@discordjs/voice` package to be installed. ```APIDOC ## getVoiceConnection(guildID) ### Description Get the active voice connection in a guild. ### Method `getVoiceConnection(guildID: string): VoiceConnection | undefined` ### Parameters #### Path Parameters - **guildID** (string) - Yes - Snowflake ID of the guild. ### Requires `@discordjs/voice` package ### Throws `DependencyError` if @discordjs/voice not installed. ``` -------------------------------- ### User.createDM Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Opens a direct message channel with the user. ```APIDOC ## User.createDM ### Description Opens a direct message channel with this user. ### Method ```typescript async createDM(): Promise ``` ``` -------------------------------- ### Get User by ID Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Use this method to retrieve a user's information by their unique user ID. ```typescript async getUser(userID: string): Promise ``` -------------------------------- ### Working with Collections in Oceanic.js Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Shows how to use array-like and collection-specific methods on the client.users collection, including filtering, mapping, and accessing elements. ```typescript import { Collection } from "oceanic.js"; const users = client.users; // Array-like methods const bots = users.filter(u => u.bot); const admins = users.filter(u => u.id === "123456789"); const usernames = users.map(u => u.username); // Collection methods const first = users.first(); const last = users.last(5); const random = users.random(); // Standard Map methods for (const [id, user] of users) { console.log(`${id}: ${user.username}`); } users.forEach(user => { console.log(user.username); }); ``` -------------------------------- ### Client Methods Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/SUMMARY.txt The Client class serves as the main entry point for interacting with the Discord API. It provides methods for managing the connection, handling status updates, and performing core operations like fetching channels or managing voice connections. ```APIDOC ## Client Methods ### Description Methods available on the `Client` class for managing the Discord bot's connection, presence, and basic API interactions. ### Methods - `connect()`: Establishes a connection to the Discord gateway. - `disconnect()`: Closes the connection to the Discord gateway. - `editStatus(status)`: Updates the bot's presence status. - `getChannel(channelId)`: Retrieves a channel by its ID. - `joinVoiceChannel(channelId, options)`: Joins a voice channel. - `leaveVoiceChannel(channelId)`: Leaves a voice channel. - `restMode(enabled)`: Toggles REST mode for the client. ### Parameters - `connect()`: No parameters. - `disconnect()`: No parameters. - `editStatus(status)`: `status` (object) - The new presence status. - `getChannel(channelId)`: `channelId` (string) - The ID of the channel to retrieve. - `joinVoiceChannel(channelId, options)`: `channelId` (string) - The ID of the voice channel to join. `options` (object) - Optional voice connection options. - `leaveVoiceChannel(channelId)`: `channelId` (string) - The ID of the voice channel to leave. - `restMode(enabled)`: `enabled` (boolean) - Whether to enable or disable REST mode. ### Return Type - `connect()`: `Promise` - `disconnect()`: `Promise` - `editStatus(status)`: `Promise` - `getChannel(channelId)`: `Promise` - `joinVoiceChannel(channelId, options)`: `Promise` - `leaveVoiceChannel(channelId)`: `Promise` - `restMode(enabled)`: `void` ### Throws - `DiscordRESTError`: If a REST API error occurs. - `GatewayError`: If a WebSocket error occurs during connection. - `DependencyError`: If required voice dependencies are missing for voice methods. ### Examples ```typescript // Connect to Discord await client.connect(); // Edit status await client.editStatus('online', { name: 'Playing a game' }); // Get a channel const channel = await client.getChannel('123456789012345678'); // Join a voice channel const connection = await client.joinVoiceChannel('987654321098765432'); ``` ``` -------------------------------- ### Configure Gateway Compression Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Choose a compression algorithm for gateway messages to improve performance. Options include 'zlib', 'zstd', or disabling compression entirely. ```typescript import { CompressionConfigs } from "oceanic.js"; const client = new Client({ token: "TOKEN", gateway: { compression: "zlib" // or "zstd" or undefined (none) } }); ``` ```typescript const client = new Client({ token: "TOKEN", gateway: { compression: CompressionConfigs.ZLIB // Alternative syntax } }); ``` -------------------------------- ### Get OAuth Authorization URL Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Generates an OAuth authorization URL. Use this method to initiate the OAuth flow. ```typescript getAuthorizationURL(options?: Types.OAuth.GetAuthorizationURLOptions): string ``` -------------------------------- ### Setting Bot Status and Activity Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md Demonstrates how to update the bot's presence status (online, idle, dnd, invisible) and its activity. The activity can be playing a game, streaming, listening, or watching. ```typescript await client.editStatus("idle", [ { name: "with commands", type: 0 }, { name: "on Twitch", type: 1, url: "https://twitch.tv/..." } ]); ``` -------------------------------- ### client.rest.oauth.getCurrentUser Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Retrieves information about the currently authenticated user using an OAuth token. This is useful for verifying the token and getting user details. ```APIDOC ## getCurrentUser ### Description Get current user info using OAuth token. ### Method GET ### Endpoint /users/@me ### Parameters No parameters required. Authentication is handled via the OAuth token. ### Response #### Success Response (ExtendedUser) - Returns an ExtendedUser object containing the current user's information. ### Response Example ```json { "id": "123456789012345678", "username": "exampleUser", "discriminator": "0001", "public_flags": 1, "flags": 0, "avatar": "a_hash", "bot": false, "banner": null, "accent_color": null, "global_name": "Example User", "avatar_decoration_data": null, "banner_color": null, "display_name": "Example User", "email": "user@example.com", "verified": true } ``` ``` -------------------------------- ### Utilities & Helpers Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Provides various utility classes and constants for common tasks, such as collections, event emitters, and API route definitions. ```APIDOC ## Utilities & Helpers ### Description A collection of utility classes, wrappers, and constants designed to assist with common programming tasks within the library. ### Classes - **Collection**: A Map-like collection with added array methods. - **TypedCollection**: A collection that automatically constructs entity objects. - **TypedEmitter**: An event emitter with type safety for event payloads. - **InteractionOptionsWrapper**: Provides typed access to slash command options. - **Util**: Contains general utility methods for the client. ### Constants - **Routes**: Static definitions for Discord API endpoints. - **Constants**: Enums and configuration values used throughout the library. - **Time**: Utilities for tracking uptime and time-related operations. ``` -------------------------------- ### Get Current Bot User Information Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Use this method to fetch the bot's own user information, including extended details. ```typescript async getCurrentUser(): Promise ``` -------------------------------- ### Initialize Client in REST-Only Mode Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Run the client without a gateway connection for REST operations only. This populates essential client properties like application and user. ```typescript const client = new Client({ token: "TOKEN" }); // Initialize for REST-only use await client.restMode(true); // true = emit ready event console.log("Bot:", client.user.username); // Can now use REST operations const me = await client.rest.users.getCurrentUser(); const guilds = await client.rest.misc.getCurrentUserGuilds(); ``` -------------------------------- ### Get User Tag Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Retrieves the user's tag in the format 'username#discriminator'. This is useful for displaying the user's full identifier. ```typescript get tag(): string ``` ```typescript console.log(user.tag); // "discord#0001" ``` -------------------------------- ### Get Public Gateway Information Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Use `getGateway` to obtain the public WebSocket gateway URL. This method does not provide rate limit information. ```typescript async getGateway(): Promise ``` -------------------------------- ### Initialize Client for REST-only Operation Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Initialize the client for REST-only operations without a gateway connection. This populates the application and user properties and can optionally emit a ready event. ```typescript const client = new Client({ token: "TOKEN" }); await client.restMode(); console.log("Bot user:", client.user.username); // Can now use REST operations without gateway ``` -------------------------------- ### Get Channel Option Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Retrieves a channel option value by its name. The option can be optionally required. Supports generic type for specific channel types. ```typescript getChannel(name: string, required?: boolean): T | null ``` -------------------------------- ### joinVoiceChannel(options) Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Joins a voice channel in a specified guild. This method requires the `@discordjs/voice` package and an adapter creator. ```APIDOC ## joinVoiceChannel(options) ### Description Join a voice channel. ### Method `joinVoiceChannel(options: Types.Voice.JoinVoiceChannelOptions): VoiceConnection` ### Parameters #### Path Parameters - **options** (Types.Voice.JoinVoiceChannelOptions) - Yes - Options object for joining the voice channel. - **channelID** (string) - Yes - Voice channel snowflake ID. - **guildID** (string) - Yes - Guild snowflake ID. - **selfDeaf** (boolean) - No - Self-deafen when joining. - **selfMute** (boolean) - No - Self-mute when joining. - **voiceAdapterCreator** (function) - Yes - Adapter creator function from @discordjs/voice. - **debug** (boolean) - No - Enable debug logging. ### Requires `@discordjs/voice` package ### Throws `DependencyError` if @discordjs/voice not installed. ``` -------------------------------- ### RESTOptions Configuration Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Configure HTTP request settings like timeout and base URL. The default timeout is 15 seconds. ```typescript { timeout?: number; baseURL?: string; } ``` ```typescript const client = new Client({ token: "TOKEN", rest: { timeout: 30000 // 30 second request timeout } }); ``` -------------------------------- ### Utilities Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/SUMMARY.txt Provides various helper functions and utilities for common tasks, such as formatting, data manipulation, and constants. ```APIDOC ## Utilities ### Description The utilities module contains helper functions and constants that can be used across your application for various tasks. ### Examples - **Permissions**: Utility for working with Discord permissions. - **Snowflake**: Utilities for handling Snowflake IDs. - **Constants**: Access to various Discord-related constants. ``` -------------------------------- ### ShardManager connect Method Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md Connect all shards to the gateway. This is automatically called by client.connect(). ```typescript async connect(): Promise ``` -------------------------------- ### createRole Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Create a new role within the guild. Role permissions can be specified. ```APIDOC ## createRole ### Description Create a new role. ### Method `createRole` ### Parameters #### Options - **options** (Types.Guilds.CreateRoleOptions) - Optional - Object containing role creation options. **Example:** ```typescript const role = await guild.createRole({ name: "Moderators", permissions: Permissions.SEND_MESSAGES | Permissions.BAN_MEMBERS }); ``` ### Response #### Success Response - **Role** (Role) - The newly created Role object. ``` -------------------------------- ### Configure CDN Image Formats and Sizes Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Set default formats and sizes for CDN image URLs. These settings are used when generating URLs for user avatars and other images. ```typescript const client = new Client({ token: "TOKEN", defaultImageFormat: "webp", // "jpg", "jpeg", "png", "webp", "gif" defaultImageSize: 256 // 16, 20, 22, 24, 28, 32, 40, 44, 48, 56, 60, 64, 80, 96, 100, 128, 160, 240, 256, 300, 320, 480, 512, 600, 640, 1024, 1280, 1536, 2048, 3072, 4096 }); ``` -------------------------------- ### Interact with the REST API Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/README.md Perform Discord operations via the client.rest manager. Examples include creating messages, adding guild members, creating commands, and executing webhooks. ```typescript client.rest.channels.createMessage(channelID, { content: "..." }); client.rest.guilds.addMember(guildID, userID, { ... }); client.rest.applications.createGlobalCommand({ ... }); client.rest.webhooks.execute(webhookID, token, { ... }); ``` -------------------------------- ### Full Presence Structure Definition Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md Defines the complete structure for setting a bot's presence, including status, activities (with types and optional URLs), and an AFK flag. ```typescript { status: "online" | "idle" | "dnd" | "invisible"; activities?: [ { name: string; type: 0 | 1 | 2 | 3 | 4; url?: string; // For STREAMING type } ]; afk: boolean; } ``` -------------------------------- ### DiscordRESTError Properties Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/errors.md Inspect the properties of a DiscordRESTError to get detailed information about the API error. This includes Discord-specific error codes, HTTP status, response body, and request details. ```typescript error.code: number // Discord error code (e.g., 50001 for "Missing Access") error.message: string // Formatted error message with endpoint info error.method: RESTMethod // HTTP method (GET, POST, PUT, PATCH, DELETE) error.response: Response // Raw Response object error.resBody: Record | null // Parsed error response error.status: number // HTTP status code error.statusText: string // HTTP status text error.headers: Headers // Response headers error.path: string // Request path error.name = "DiscordRESTError" ``` -------------------------------- ### Client Class Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/SUMMARY.txt The primary class for connecting to Discord and managing the library's core functionalities. It serves as the main entry point for interacting with the library's features. ```APIDOC ## Client Class ### Description The `Client` class is the central hub for interacting with Discord. It handles connections, event listeners, and provides access to other managers like REST and Gateway. ### Usage ```typescript import { Client } from "oceanic.js"; const client = new Client({ auth: "Bot YOUR_BOT_TOKEN" }); client.on("ready", () => { console.log("Client is ready!"); }); client.login(); ``` ### Methods - **login(token?: string)**: Connects the client to Discord. - **destroy()**: Disconnects the client from Discord. - **on(event, listener)**: Attaches an event listener. - **off(event, listener)**: Removes an event listener. ``` -------------------------------- ### Default Client Properties Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/configuration.md View the default client properties used if not explicitly set. These include process.platform for OS and default browser/device names. ```typescript { os: process.platform, // "linux", "darwin", "win32" browser: "Oceanic", device: "Oceanic" } ``` -------------------------------- ### getOAuthHelper(accessToken) Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Creates an OAuth2 helper instance using a provided user access token. This helper can be used for making OAuth2-related API calls. ```APIDOC ## getOAuthHelper(accessToken) ### Description Create an OAuth helper for a specific user access token. ### Method `getOAuthHelper(accessToken: string): OAuthHelper` ### Parameters #### Path Parameters - **accessToken** (string) - Yes - User access token with `Bearer ` prefix. ### Returns `OAuthHelper` instance for that token. ``` -------------------------------- ### Command Option Structure Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/types.md Defines the structure for command options, including their type, name, description, and optional parameters like choices, sub-options, and validation constraints. Use this to build complex command structures. ```typescript type CommandOption = { type: CommandOptionType; name: string; description: string; required?: boolean; choices?: CommandChoice[]; options?: CommandOption[]; min_value?: number; max_value?: number; min_length?: number; max_length?: number; autocomplete?: boolean; channel_types?: ChannelType[]; default?: unknown; } ``` -------------------------------- ### Get Cached Channel by ID Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/client.md Retrieve a channel from the client's cache using its snowflake ID. This method searches across guild channels, threads, private channels, and group channels. ```typescript const channel = client.getChannel("123456789"); if (channel && "guild" in channel) { console.log("Guild channel:", channel.name); } ``` -------------------------------- ### Create OAuth Helper Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Creates an OAuth helper instance for a specific access token. This helper can be used to perform authenticated actions. ```typescript getHelper(accessToken: string): OAuthHelper ``` -------------------------------- ### Version and URL Constants Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md Constants for Discord API versions, base URLs, and package information. Includes valid CDN image sizes. ```typescript export const GATEWAY_VERSION = 10; // Discord Gateway API v10 export const REST_VERSION = 10; // Discord REST API v10 export const BASE_URL = "https://discord.com"; export const API_URL = `${BASE_URL}/api/v${REST_VERSION}`; export const VERSION = "1.14.0"; // Package version export const USER_AGENT = "Oceanic/1.14.0 (https://github.com/OceanicJS/Oceanic)"; export const MEDIA_PROXY_SIZES = [16, 20, 22, ...]; // Valid CDN image sizes ``` -------------------------------- ### Get First Element or N Elements from Collection Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/utilities.md The first method retrieves either the first element of the collection or a specified number of elements from the beginning. It returns an array if an amount is provided, otherwise a single element or undefined. ```typescript first(): V | undefined; first(amount: number): Array; ``` ```typescript const latest = collection.first(); const top5 = collection.first(5); ``` -------------------------------- ### Create Global Slash Command Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/rest-manager.md Creates a new global slash command for the application. Ensure the options object is correctly formatted. ```typescript async createGlobalCommand( options: Types.Applications.CreateApplicationCommandOptions ): Promise ``` -------------------------------- ### setTopic Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/structures.md Change the topic of the channel. ```APIDOC ## setTopic(topic, reason?) ### Description Change the channel topic. ### Method ``` async setTopic(topic: string | null, reason?: string): Promise ``` ### Parameters #### Request Body - **topic** (string | null) - Required - The new topic for the channel. #### Query Parameters - **reason** (string) - Optional - The reason for changing the topic. ``` -------------------------------- ### Gateway Compression Configuration Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md Configures the compression method for the gateway connection to reduce bandwidth usage. Supported types include zlib, zstd, and none. ```APIDOC ## Gateway Compression ### Description Configures the compression method for the gateway connection to reduce bandwidth usage. Supported types include zlib, zstd, and none. ### Options `GatewayOptions.compression` can be set to one of the following values: - `"zlib"`: Uses zlib compression. Requires `pako` or `zlib-sync` or Node 22.15.0+. - `"zstd"`: Uses zstd compression. Requires `zstd-napi` or Node 23.8.0+. - `"none"`: No compression is used. ### Example ```typescript const client = new Client({ gateway: { compression: "zstd" // Use zstd compression } }); ``` ``` -------------------------------- ### Handle Shard Connection Event Source: https://github.com/oceanicjs/oceanic/blob/dev/_autodocs/api-reference/gateway.md The 'connect' event is emitted when an individual shard successfully establishes a connection. It provides the shard ID. ```typescript client.on("connect", (shardID: number) => { console.log(`Shard ${shardID} connected`); }); ```