### Install Wave.js with npm Source: https://github.com/j6aoo/wave.js/blob/main/README.md Install the Wave.js SDK using npm. This is the standard package manager for Node.js. ```bash npm install wave.js ``` -------------------------------- ### Install Wave.js with yarn Source: https://github.com/j6aoo/wave.js/blob/main/README.md Install the Wave.js SDK using yarn. An alternative package manager for Node.js. ```bash yarn add wave.js ``` -------------------------------- ### Basic Wave.js Client Setup Source: https://github.com/j6aoo/wave.js/blob/main/README.md Initialize a Wave.js Client to connect to Fluxer. Requires your bot token. Logs bot status and server count upon successful connection. ```javascript const { Client, GatewayDispatchEvents } = require('wave.js'); const client = new Client({ token: 'SEU_BOT_TOKEN_AQUI' }); // Quando o bot estiver pronto client.on(GatewayDispatchEvents.Ready, ({ data }) => { console.log(`๐Ÿš€ Bot online como ${data.user.username}!`); console.log(`๐Ÿ“Š Conectado em ${data.guilds.length} servidores`); }); // Conectar client.connect(); ``` -------------------------------- ### Wave.js Client with TypeScript Source: https://github.com/j6aoo/wave.js/blob/main/README.md Example of setting up a Wave.js client using TypeScript. Includes handling message creation events to respond to '!ping' commands. ```typescript import { Client, GatewayDispatchEvents, Message } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on(GatewayDispatchEvents.MessageCreate, (message: Message) => { if (message.content === '!ping') { message.reply('Pong! ๐Ÿ“'); } }); client.connect(); ``` -------------------------------- ### Performing HTTP Requests with RestClient Source: https://context7.com/j6aoo/wave.js/llms.txt This example demonstrates how to use RestClient for making low-level HTTP requests, including GET, POST, PATCH, and DELETE operations, with support for query parameters, JSON bodies, and file uploads. It can be used standalone or accessed via a Client instance. Ensure the BOT_TOKEN environment variable is set. ```typescript import { Client, RestClient } from 'wave.js'; // Standalone REST client (no gateway needed) const rest = new RestClient({ token: process.env.BOT_TOKEN!, retries: 3, }); // GET with query params const messages = await rest.get('/channels/1234567890123456789/messages', { limit: 10 }); // POST JSON body const message = await rest.post('/channels/1234567890123456789/messages', { content: 'Hello from raw REST!', }); // PATCH await rest.patch('/channels/1234567890123456789/messages/9876543210987654321', { content: 'Edited content', }); // DELETE await rest.delete('/channels/1234567890123456789/messages/9876543210987654321'); // Upload a file attachment import { readFileSync } from 'fs'; const fileBuffer = readFileSync('./image.png'); await rest.post('/channels/1234567890123456789/messages', { content: 'File upload!' }, { files: [ { file: fileBuffer, filename: 'image.png', description: 'A sample image' }, ], }); // Access via the bot client const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { const userData = await client.rest.get('/users/@me'); console.log(userData); }); await client.login(); ``` -------------------------------- ### Managing Bot Shards with ShardingManager Source: https://context7.com/j6aoo/wave.js/llms.txt This example shows how to use ShardingManager to spawn and manage bot processes across multiple shards. It includes event handling for shard creation, ready, and death, as well as methods for broadcasting messages, fetching client values, and respawning shards. Ensure the BOT_TOKEN environment variable is set. ```typescript // manager.js โ€” run this instead of bot.js directly import { ShardingManager } from 'wave.js'; const manager = new ShardingManager('./bot.js', { token: process.env.BOT_TOKEN!, totalShards: 4, // or 'auto' respawn: true, // auto-restart crashed shards }); manager.on('shardCreate', (shard) => { console.log(`Shard ${shard.id} spawned (PID ${shard.process?.pid})`); shard.on('ready', () => console.log(`Shard ${shard.id} ready`)); shard.on('death', () => console.warn(`Shard ${shard.id} died`)); }); await manager.spawn(); // Broadcast a message to all shards await manager.broadcast({ type: 'RELOAD_CONFIG' }); // Fetch a value from every shard const guildCounts = await manager.fetchClientValues('guilds.cache.size'); const total = (guildCounts as number[]).reduce((a, b) => a + b, 0); console.log(`Total guilds across all shards: ${total}`); // Eval arbitrary code in every shard const results = await manager.broadcastEval('this.uptime'); console.log('Uptimes:', results); // Restart all shards await manager.respawnAll(); ``` ```typescript // bot.js โ€” the shard worker import { Client, ShardClientUtil, GatewayDispatchEvents } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); const shard = ShardClientUtil.singleton(client); client.on(GatewayDispatchEvents.Ready, () => { console.log(`Shard [${shard.ids.join(',')}/${shard.count}] ready`); }); await client.login(); ``` -------------------------------- ### Gateway Event Handling Source: https://context7.com/j6aoo/wave.js/llms.txt This section details how to subscribe to various gateway events using `client.on()` and the `GatewayDispatchEvents` enum. Examples include handling message creation, updates, deletions, guild joins, member additions, reactions, voice state changes, and typing indicators. ```APIDOC ## GatewayDispatchEvents โ€” Event Reference `GatewayDispatchEvents` is an enum of every gateway event string. Subscribe with `client.on(event, handler)`. ```typescript import { Client, GatewayDispatchEvents, Message, Guild, GuildMember } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); // Message lifecycle client.on(GatewayDispatchEvents.MessageCreate, (message: Message) => { if (message.author.bot) return; console.log(`[${message.channelId}] ${message.author.username}: ${message.content}`); }); client.on(GatewayDispatchEvents.MessageUpdate, (message: Message) => { console.log(`Message ${message.id} edited`); }); client.on(GatewayDispatchEvents.MessageDelete, ({ id, channel_id }) => { console.log(`Message ${id} deleted from ${channel_id}`); }); // Guild lifecycle client.on(GatewayDispatchEvents.GuildCreate, (guild: Guild) => { console.log(`Joined guild: ${guild.name} (${guild.memberCount} members)`); }); client.on(GatewayDispatchEvents.GuildMemberAdd, (member: GuildMember) => { console.log(`${member.user?.username} joined ${member.guildId}`); }); // Reactions client.on(GatewayDispatchEvents.MessageReactionAdd, (reaction, user) => { console.log(`${user.username} reacted with ${reaction.emoji.name}`); }); // Voice client.on(GatewayDispatchEvents.VoiceStateUpdate, (voiceState) => { console.log(`Voice update for user ${voiceState.userId} in ${voiceState.channelId}`); }); // Typing client.on(GatewayDispatchEvents.TypingStart, ({ user_id, channel_id }) => { console.log(`User ${user_id} is typing in ${channel_id}`); }); await client.login(); ``` ``` -------------------------------- ### Subscribe to Gateway Events in Wave.js Source: https://context7.com/j6aoo/wave.js/llms.txt Subscribe to various gateway events using `client.on(event, handler)`. This example shows how to handle message lifecycle, guild lifecycle, reactions, voice updates, and typing indicators. ```typescript import { Client, GatewayDispatchEvents, Message, Guild, GuildMember } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); // Message lifecycle client.on(GatewayDispatchEvents.MessageCreate, (message: Message) => { if (message.author.bot) return; console.log(`[${message.channelId}] ${message.author.username}: ${message.content}`); }); client.on(GatewayDispatchEvents.MessageUpdate, (message: Message) => { console.log(`Message ${message.id} edited`); }); client.on(GatewayDispatchEvents.MessageDelete, ({ id, channel_id }) => { console.log(`Message ${id} deleted from ${channel_id}`); }); // Guild lifecycle client.on(GatewayDispatchEvents.GuildCreate, (guild: Guild) => { console.log(`Joined guild: ${guild.name} (${guild.memberCount} members)`); }); client.on(GatewayDispatchEvents.GuildMemberAdd, (member: GuildMember) => { console.log(`${member.user?.username} joined ${member.guildId}`); }); // Reactions client.on(GatewayDispatchEvents.MessageReactionAdd, (reaction, user) => { console.log(`${user.username} reacted with ${reaction.emoji.name}`); }); // Voice client.on(GatewayDispatchEvents.VoiceStateUpdate, (voiceState) => { console.log(`Voice update for user ${voiceState.userId} in ${voiceState.channelId}`); }); // Typing client.on(GatewayDispatchEvents.TypingStart, ({ user_id, channel_id }) => { console.log(`User ${user_id} is typing in ${channel_id}`); }); await client.login(); ``` -------------------------------- ### Fetch and Manage Guilds in Wave.js Source: https://context7.com/j6aoo/wave.js/llms.txt Use `client.guilds.fetch()` to retrieve guild data from the API, bypassing the cache. This example demonstrates fetching guild details, editing guild settings, creating channels, and performing moderation actions like banning and kicking. ```typescript import { Client, GatewayDispatchEvents } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Fetch from API (bypasses cache) const guild = await client.guilds.fetch('1234567890123456789'); console.log(`Name: ${guild.name}`); console.log(`Owner: ${guild.ownerId}`); console.log(`Members: ${guild.memberCount}`); console.log(`Icon: ${guild.iconURL({ size: 256, format: 'png' })}`); console.log(`Banner: ${guild.bannerURL({ size: 1024 })}`); console.log(`Created: ${guild.createdAt.toISOString()}`); // Edit guild await guild.edit({ name: 'New Name', description: 'Updated description' }, 'Rebranding'); // Create a text channel const channel = await guild.createChannel({ name: 'announcements', type: 5, // GUILD_ANNOUNCEMENT topic: 'Official news', parent_id: '9876543210987654321', }); console.log(`Channel created: ${channel.id}`); // Moderation await guild.banMember('111222333444555666', { delete_message_seconds: 86400, reason: 'Spam' }); await guild.unbanUser('111222333444555666', 'Appeal accepted'); await guild.kickMember('777888999000111222', 'Rule violation'); // Roles const role = await guild.createRole({ name: 'Moderator', color: 0x3498db, hoist: true }, 'New mod role'); console.log(`Role created: ${role.id}`); const invites = await guild.fetchInvites(); console.log(`Active invites: ${invites.length}`); }); await client.login(); ``` -------------------------------- ### Get Guild Basic Information Source: https://github.com/j6aoo/wave.js/blob/main/README.md Retrieves basic information about a specific guild, such as its name, owner ID, creation date, and URLs for its icon and banner. ```javascript const guild = await client.guilds.fetch('ID_DO_SERVIDOR'); // Dados bรกsicos console.log(`Nome: ${guild.name}`); console.log(`Dono: ${guild.ownerId}`); console.log(`Criado em: ${guild.createdAt.toLocaleDateString()}`); // URLs de imagens console.log(`รcone: ${guild.iconURL()}`); console.log(`Banner: ${guild.bannerURL({ size: 1024 })}`); ``` -------------------------------- ### Client Instantiation and Login Source: https://context7.com/j6aoo/wave.js/llms.txt Demonstrates how to create a new Client instance, log in to the Fluxer platform, and handle various error types. ```APIDOC ## Client โ€” Instantiation and Login `new Client(options)` creates the bot client. Call `client.login()` to open the WebSocket connection; `client.destroy()` disconnects cleanly. Access `client.user` after the `ready` event. ```typescript import { Client, GatewayDispatchEvents, ActivityType, FluxerAPIError, FluxerRateLimitError, FluxerGatewayError, } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN!, intents: 0, // Fluxer does not yet use Discord-style intents messageCacheMaxSize: 500, presence: { status: 'online', activities: [{ name: 'Fluxer', type: ActivityType.Watching }], }, }); client.on(GatewayDispatchEvents.Ready, (user) => { console.log(`Logged in as ${user.username}`); console.log(`Uptime timer started โ€” isReady: ${client.isReady}`); console.log(`Invite: ${client.generateInvite()}`); }); client.on('error', (err) => { if (err instanceof FluxerRateLimitError) { console.warn(`Rate limited on ${err.endpoint}. Retry in ${err.retryAfter}ms`); } else if (err instanceof FluxerAPIError) { console.error(`API ${err.status} [${err.code}] ${err.message}`); } else if (err instanceof FluxerGatewayError) { console.error(`Gateway closed with code ${err.code}`); } }); client.on('debug', (msg) => process.env.DEBUG && console.debug(msg)); await client.login(); // Later: // client.destroy(); ``` ``` -------------------------------- ### Fetch Channels and Send Messages with Wave.js Source: https://context7.com/j6aoo/wave.js/llms.txt Demonstrates fetching a channel by ID and sending various message types, including plain text, rich payloads, and triggering typing indicators. Also shows how to fetch recent messages, perform bulk deletion, and create channel invites. ```typescript import { Client, GatewayDispatchEvents, ChannelType } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Fetch a text channel const channel = await client.channels.fetch('1234567890123456789'); // Send plain text await (channel as any).send('Hello, channel!'); // Send a rich payload await (channel as any).send({ content: 'Message with components', embeds: [{ title: 'Embed title', description: 'Embed body', color: 0x3498db }], }); // Trigger typing indicator await (channel as any).sendTyping(); // Fetch recent messages const messages = await (channel as any).messages.fetch({ limit: 50 }); console.log(`Fetched ${messages.size} messages`); // Bulk delete (up to 100) await (channel as any).bulkDelete(messages); // Create an invite for this channel const invite = await (channel as any).createInvite({ maxAge: 86400, // 1 day in seconds maxUses: 25, unique: true, }); console.log(`Invite: https://fluxer.app/invite/${invite.code}`); }); await client.login(); ``` -------------------------------- ### Fetch Users and Send DMs with Wave.js Source: https://context7.com/j6aoo/wave.js/llms.txt Shows how to fetch user profile data by ID and retrieve details like username, display name, bot status, avatar, and banner. It also demonstrates how to create a direct message channel with a user and send a message. ```typescript import { Client } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { const user = await client.users.fetch('1234567890123456789'); console.log(`Username: ${user.username}`); console.log(`Display: ${user.displayName}`); console.log(`Bot: ${user.bot}`); console.log(`Avatar: ${user.avatarURL({ size: 256, format: 'webp', animated: true })}`); console.log(`Banner: ${user.bannerURL()}`); console.log(`Created: ${user.createdAt.toISOString()}`); // Send a DM const dmChannel = await user.createDM(); await dmChannel.send('Hello from the bot! ๐Ÿ‘‹'); }); await client.login(); ``` -------------------------------- ### Instantiate and Login Wave.js Client Source: https://context7.com/j6aoo/wave.js/llms.txt Instantiate the `Client` class with options and log in to the Fluxer platform. Handles various error types like rate limits and API errors. Access `client.user` after the `ready` event. ```typescript import { Client, GatewayDispatchEvents, ActivityType, FluxerAPIError, FluxerRateLimitError, FluxerGatewayError, } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN!, intents: 0, // Fluxer does not yet use Discord-style intents messageCacheMaxSize: 500, presence: { status: 'online', activities: [{ name: 'Fluxer', type: ActivityType.Watching }], }, }); client.on(GatewayDispatchEvents.Ready, (user) => { console.log(`Logged in as ${user.username}`); console.log(`Uptime timer started โ€” isReady: ${client.isReady}`); console.log(`Invite: ${client.generateInvite()}`); }); client.on('error', (err) => { if (err instanceof FluxerRateLimitError) { console.warn(`Rate limited on ${err.endpoint}. Retry in ${err.retryAfter}ms`); } else if (err instanceof FluxerAPIError) { console.error(`API ${err.status} [${err.code}] ${err.message}`); } else if (err instanceof FluxerGatewayError) { console.error(`Gateway closed with code ${err.code}`); } }); client.on('debug', (msg) => process.env.DEBUG && console.debug(msg)); await client.login(); // Later: // client.destroy(); ``` -------------------------------- ### Manage Invites: Create, Fetch, and Accept Source: https://context7.com/j6aoo/wave.js/llms.txt Utilize client.invites for global invite operations. Guilds and channels also provide invite methods. Fetching invite metadata does not require authentication. ```typescript import { Client } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Fetch invite metadata (no auth needed) const info = await client.invites.fetch('abcdef'); console.log(`Guild: ${info.guild?.name}, created by: ${info.inviter?.username}`); console.log(`Uses: ${info.uses}/${info.max_uses}, expires: ${info.expires_at}`); // Accept an invite (user-mode token) await client.invites.accept('abcdef'); // Create an invite from a channel (via the channel object) const channel = await client.channels.fetch('1234567890123456789'); const invite = await (channel as any).createInvite({ maxAge: 3600, // 1 hour maxUses: 5, temporary: false, unique: true, }); console.log(`https://fluxer.app/invite/${invite.code}`); // List all invites for a guild const guild = await client.guilds.fetch('9876543210987654321'); const guildInvites = await guild.fetchInvites(); console.log(`${guildInvites.length} active invites`); }); await client.login(); ``` -------------------------------- ### Handle Guild Creation Events Source: https://github.com/j6aoo/wave.js/blob/main/README.md Logs information when the bot joins a new server (guild), including the server's name and member count. ```javascript const { GatewayDispatchEvents } = require('wave.js'); // Quando o bot entrar em um novo servidor client.on(GatewayDispatchEvents.GuildCreate, (guild) => { console.log(`โœ… Entrei no servidor: ${guild.name}`); console.log(`๐Ÿ‘ฅ Membros: ${guild.memberCount}`); }); ``` -------------------------------- ### Build and Handle Select Menus Source: https://context7.com/j6aoo/wave.js/llms.txt Use SelectMenuBuilder and SelectMenuOptionBuilder to create dropdown menus for user selection. Handles selections by custom ID and returns selected values. ```typescript import { Client, GatewayDispatchEvents, ActionRowBuilder, SelectMenuBuilder, SelectMenuOptionBuilder, } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on(GatewayDispatchEvents.MessageCreate, async (message) => { if (message.content !== '!role') return; const menu = new SelectMenuBuilder() .setCustomId('role_picker') .setPlaceholder('Pick your roleโ€ฆ') .setMinValues(1) .setMaxValues(2) .addOptions( new SelectMenuOptionBuilder() .setLabel('Developer') .setValue('developer') .setDescription('Backend / frontend / full-stack') .setEmoji({ id: null, name: '๐Ÿ’ป' }), new SelectMenuOptionBuilder() .setLabel('Designer') .setValue('designer') .setDescription('UI/UX and graphic design') .setEmoji({ id: null, name: '๐ŸŽจ' }), new SelectMenuOptionBuilder() .setLabel('Gamer') .setValue('gamer') .setDescription('Here for the fun') .setEmoji({ id: null, name: '๐ŸŽฎ' }), ); const row = new ActionRowBuilder().addComponents(menu); await message.reply({ content: 'Select up to 2 roles:', components: [row.toJSON()] }); }); client.on(GatewayDispatchEvents.InteractionCreate, async (interaction: any) => { if (interaction.type !== 3) return; if (interaction.data.custom_id !== 'role_picker') return; const chosen: string[] = interaction.data.values; await interaction.reply({ content: `You selected: ${chosen.join(', ')}`, ephemeral: true }); }); await client.login(); ``` -------------------------------- ### InviteManager Source: https://context7.com/j6aoo/wave.js/llms.txt Handles invite codes globally and per-guild/channel. ```APIDOC ## InviteManager โ€” Create, Fetch, and Accept Invites `client.invites` handles invite codes at the global client level; guilds and channels also expose invite methods. ### Fetch Invite Metadata Fetches metadata for a given invite code. No authentication is required. ```typescript await client.invites.fetch('abcdef') ``` ### Accept Invite Accepts an invite using a user-mode token. ```typescript await client.invites.accept('abcdef') ``` ### Create Invite Creates an invite from a channel object with specified options. ```typescript await (channel as any).createInvite({ maxAge: 3600, maxUses: 5, temporary: false, unique: true, }) ``` ### Fetch Guild Invites Fetches all active invites for a specific guild. ```typescript await guild.fetchInvites() ``` ``` -------------------------------- ### client.setPresence / setActivity / setStatus Source: https://context7.com/j6aoo/wave.js/llms.txt Allows updating the bot's visible status and activity at any time after the client has logged in. ```APIDOC ## client.setPresence / setActivity / setStatus Update the bot's visible status and activity at any time after login. ```typescript import { Client, ActivityType } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', () => { // Full presence object client.setPresence({ status: 'dnd', activities: [{ name: 'maintenance mode', type: ActivityType.Playing }], }); // Shorthand: just activity client.setActivity('your commands', ActivityType.Listening); // Shorthand: just status client.setStatus('idle'); }); await client.login(); ``` ``` -------------------------------- ### Manage Relationships: Friends and Blocks Source: https://context7.com/j6aoo/wave.js/llms.txt Use client.relationships to fetch, add, block, update nicknames, and remove relationships. Ensure the bot token is valid and the user IDs are correct. ```typescript import { Client, RelationshipType } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Fetch all current relationships const rels = await client.relationships.fetch(); for (const rel of rels) { const label = RelationshipType[rel.type] ?? rel.type; console.log(`${rel.user.username}: ${label}`); } // Send a friend request by user ID await client.relationships.add('1234567890123456789'); // Or by username + discriminator await client.relationships.addByTag('SomeUser', '0001'); // Block a user await client.relationships.block('9876543210987654321'); // Set a nickname for a friend await client.relationships.updateNickname('1234567890123456789', 'Best Buddy'); // Remove / unblock await client.relationships.remove('1234567890123456789'); await client.relationships.unblock('9876543210987654321'); }); await client.login(); ``` -------------------------------- ### SelectMenuBuilder Source: https://context7.com/j6aoo/wave.js/llms.txt Create dropdown selection menus with up to 25 options. Allows users to pick one or multiple values from a list. ```APIDOC ## SelectMenuBuilder โ€” Dropdown Selection Menus Build string-select dropdown menus with up to 25 options. ```typescript import { Client, GatewayDispatchEvents, ActionRowBuilder, SelectMenuBuilder, SelectMenuOptionBuilder, } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on(GatewayDispatchEvents.MessageCreate, async (message) => { if (message.content !== '!role') return; const menu = new SelectMenuBuilder() .setCustomId('role_picker') .setPlaceholder('Pick your roleโ€ฆ') .setMinValues(1) .setMaxValues(2) .addOptions( new SelectMenuOptionBuilder() .setLabel('Developer') .setValue('developer') .setDescription('Backend / frontend / full-stack') .setEmoji({ id: null, name: '๐Ÿ’ป' }), new SelectMenuOptionBuilder() .setLabel('Designer') .setValue('designer') .setDescription('UI/UX and graphic design') .setEmoji({ id: null, name: '๐ŸŽจ' }), new SelectMenuOptionBuilder() .setLabel('Gamer') .setValue('gamer') .setDescription('Here for the fun') .setEmoji({ id: null, name: '๐ŸŽฎ' }), ); const row = new ActionRowBuilder().addComponents(menu); await message.reply({ content: 'Select up to 2 roles:', components: [row.toJSON()] }); }); client.on(GatewayDispatchEvents.InteractionCreate, async (interaction: any) => { if (interaction.type !== 3) return; if (interaction.data.custom_id !== 'role_picker') return; const chosen: string[] = interaction.data.values; await interaction.reply({ content: `You selected: ${chosen.join(', ')}`, ephemeral: true }); }); await client.login(); ``` ``` -------------------------------- ### ShardingManager Methods Source: https://context7.com/j6aoo/wave.js/llms.txt The ShardingManager spawns the bot file as child processes, one per shard, with IPC for eval and value broadcasting. ```APIDOC ## ShardingManager ### Description Manages multiple child processes (shards) for a bot application, enabling distributed execution and inter-process communication. ### Constructor `new ShardingManager(file: string, options: ShardingManagerOptions)` ### Options - `token` (string): The bot token. - `totalShards` (number | 'auto'): The total number of shards to spawn, or 'auto' to let the library determine. - `respawn` (boolean): Whether to automatically restart crashed shards. ### Events - `shardCreate(shard: Shard): void` - Emitted when a shard is created. - `shard.on('ready')` - Emitted when a shard is ready. - `shard.on('death')` - Emitted when a shard dies. ### Methods - `spawn(): Promise` - Spawns all the shards. - `broadcast(data: any): Promise` - Broadcasts a message to all shards. - `fetchClientValues(property: string): Promise` - Fetches a property value from all shards. - `broadcastEval(script: string): Promise` - Evaluates a script in all shards. - `respawnAll(): Promise` - Restarts all shards. ``` -------------------------------- ### Handle Message Creation Events Source: https://github.com/j6aoo/wave.js/blob/main/README.md Listen for new messages and respond to commands. Ignores messages from other bots. Supports simple greetings and echoing user-provided text. ```javascript const { GatewayDispatchEvents } = require('wave.js'); client.on(GatewayDispatchEvents.MessageCreate, async (message) => { // Ignora mensagens de bots if (message.author.bot) return; // Comando simples if (message.content === '!ola') { await message.channel.send(`Olรก, ${message.author.username}! ๐Ÿ‘‹`); } // Comando com argumentos if (message.content.startsWith('!dizer ')) { const texto = message.content.slice(7); await message.channel.send(texto); } }); ``` -------------------------------- ### Fetch and List Guild Channels Source: https://github.com/j6aoo/wave.js/blob/main/README.md Fetches a specific guild by its ID and then retrieves and lists all channels within that guild, including their names and types. ```javascript // Buscar um servidor especรญfico const guild = await client.guilds.fetch('ID_DO_SERVIDOR'); console.log(guild.name); // Listar todos os canais do servidor const channels = await guild.channels.fetch(); for (const [id, channel] of channels) { console.log(`${channel.name} (${channel.type})`); } ``` -------------------------------- ### UserManager Source: https://context7.com/j6aoo/wave.js/llms.txt Fetch user profiles, retrieve user details, and initiate direct messages with users. ```APIDOC ## UserManager โ€” Fetch Users and DMs `client.users` caches known user objects. Fetch by ID to retrieve profile data. ```typescript import { Client } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { const user = await client.users.fetch('1234567890123456789'); console.log(`Username: ${user.username}`); console.log(`Display: ${user.displayName}`); console.log(`Bot: ${user.bot}`); console.log(`Avatar: ${user.avatarURL({ size: 256, format: 'webp', animated: true })}`); console.log(`Banner: ${user.bannerURL()}`); console.log(`Created: ${user.createdAt.toISOString()}`); // Send a DM const dmChannel = await user.createDM(); await dmChannel.send('Hello from the bot! ๐Ÿ‘‹'); }); await client.login(); ``` ``` -------------------------------- ### Guild Management Source: https://context7.com/j6aoo/wave.js/llms.txt The `GuildManager` (`client.guilds`) allows fetching, editing, and managing guilds. This includes creating channels, banning/kicking members, managing roles, and fetching invites. ```APIDOC ## GuildManager โ€” Fetch and Manage Guilds `client.guilds` is the `GuildManager` cache. Use `fetch()` to get full guild data from the API. ```typescript import { Client, GatewayDispatchEvents } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Fetch from API (bypasses cache) const guild = await client.guilds.fetch('1234567890123456789'); console.log(`Name: ${guild.name}`); console.log(`Owner: ${guild.ownerId}`); console.log(`Members: ${guild.memberCount}`); console.log(`Icon: ${guild.iconURL({ size: 256, format: 'png' })}`); console.log(`Banner: ${guild.bannerURL({ size: 1024 })}`); console.log(`Created: ${guild.createdAt.toISOString()}`); // Edit guild await guild.edit({ name: 'New Name', description: 'Updated description' }, 'Rebranding'); // Create a text channel const channel = await guild.createChannel({ name: 'announcements', type: 5, // GUILD_ANNOUNCEMENT topic: 'Official news', parent_id: '9876543210987654321', }); console.log(`Channel created: ${channel.id}`); // Moderation await guild.banMember('111222333444555666', { delete_message_seconds: 86400, reason: 'Spam' }); await guild.unbanUser('111222333444555666', 'Appeal accepted'); await guild.kickMember('777888999000111222', 'Rule violation'); // Roles const role = await guild.createRole({ name: 'Moderator', color: 0x3498db, hoist: true }, 'New mod role'); console.log(`Role created: ${role.id}`); const invites = await guild.fetchInvites(); console.log(`Active invites: ${invites.length}`); }); await client.login(); ``` ``` -------------------------------- ### Reply to Messages in Fluxer Source: https://github.com/j6aoo/wave.js/blob/main/README.md Demonstrates different methods for responding to user messages within Fluxer channels using Wave.js. ```javascript // Responder na mesma mensagem (cria uma thread visual) await message.reply('Esta รฉ uma resposta!'); // Enviar no canal await message.channel.send('Mensagem normal no canal'); // Responder mencionando o autor await message.channel.send(`${message.author}, vocรช foi mencionado!`); ``` -------------------------------- ### ButtonBuilder and ActionRowBuilder Source: https://context7.com/j6aoo/wave.js/llms.txt Build clickable buttons and group them into action rows. Supports various button styles and configurations, including links and disabled states. ```APIDOC ## ButtonBuilder and ActionRowBuilder โ€” Interactive Buttons Build clickable buttons and group them into action rows (max 5 buttons per row, max 5 rows per message). ```typescript import { Client, GatewayDispatchEvents, ActionRowBuilder, ButtonBuilder, ButtonStyle, } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on(GatewayDispatchEvents.MessageCreate, async (message) => { if (message.content !== '!buttons') return; const row = new ActionRowBuilder() .addComponents( new ButtonBuilder() .setCustomId('confirm') .setLabel('Confirm โœ…') .setStyle(ButtonStyle.Success), new ButtonBuilder() .setCustomId('cancel') .setLabel('Cancel โŒ') .setStyle(ButtonStyle.Danger), new ButtonBuilder() .setLabel('Fluxer Website') .setStyle(ButtonStyle.Link) .setURL('https://fluxer.app'), new ButtonBuilder() .setCustomId('disabled_btn') .setLabel('Unavailable') .setStyle(ButtonStyle.Secondary) .setDisabled(true), ); await message.reply({ content: 'Choose an action:', components: [row.toJSON()] }); }); // Handle button clicks client.on(GatewayDispatchEvents.InteractionCreate, async (interaction: any) => { if (interaction.type !== 3) return; // MessageComponent if (interaction.data.custom_id === 'confirm') { await interaction.reply({ content: 'โœ… Confirmed!', ephemeral: true }); } else if (interaction.data.custom_id === 'cancel') { await interaction.reply({ content: 'โŒ Cancelled.', ephemeral: true }); } }); await client.login(); ``` ``` -------------------------------- ### Permissions and BitField Source: https://context7.com/j6aoo/wave.js/llms.txt Provides utilities for checking and managing permissions using bitfields. ```APIDOC ## Permissions and BitField `Permissions` extends `BitField` for bigint-based permission checking. Administrators automatically pass all permission checks unless `checkAdmin` is set to `false`. ### Check Permission Checks if a member has a specific permission. Admin bypass is enabled by default. ```typescript const perms = new Permissions(BigInt(member.permissions ?? '0')); perms.has('KickMembers'); ``` ### Check Permission Without Admin Bypass Checks for a specific permission without bypassing administrator privileges. ```typescript perms.has('BanMembers', false); ``` ### Get All Permissions Serializes the permissions into an array of permission names. ```typescript perms.toArray(); ``` ### Combine Permissions Creates a new Permissions object by combining multiple permission flags. ```typescript new Permissions( Permissions.FLAGS.KickMembers | Permissions.FLAGS.BanMembers | Permissions.FLAGS.ManageMessages ); ``` ``` -------------------------------- ### Update Bot Presence and Activity Source: https://context7.com/j6aoo/wave.js/llms.txt Update the bot's visible status and activity at any time after login using `setPresence`, `setActivity`, or `setStatus`. ```typescript import { Client, ActivityType } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', () => { // Full presence object client.setPresence({ status: 'dnd', activities: [{ name: 'maintenance mode', type: ActivityType.Playing }], }); // Shorthand: just activity client.setActivity('your commands', ActivityType.Listening); // Shorthand: just status client.setStatus('idle'); }); await client.login(); ``` -------------------------------- ### Build and Handle Interactive Buttons Source: https://context7.com/j6aoo/wave.js/llms.txt Use ButtonBuilder and ActionRowBuilder to create clickable buttons for messages. Handles button interactions by custom ID. ```typescript import { Client, GatewayDispatchEvents, ActionRowBuilder, ButtonBuilder, ButtonStyle, } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on(GatewayDispatchEvents.MessageCreate, async (message) => { if (message.content !== '!buttons') return; const row = new ActionRowBuilder() .addComponents( new ButtonBuilder() .setCustomId('confirm') .setLabel('Confirm โœ…') .setStyle(ButtonStyle.Success), new ButtonBuilder() .setCustomId('cancel') .setLabel('Cancel โŒ') .setStyle(ButtonStyle.Danger), new ButtonBuilder() .setLabel('Fluxer Website') .setStyle(ButtonStyle.Link) .setURL('https://fluxer.app'), new ButtonBuilder() .setCustomId('disabled_btn') .setLabel('Unavailable') .setStyle(ButtonStyle.Secondary) .setDisabled(true), ); await message.reply({ content: 'Choose an action:', components: [row.toJSON()] }); }); // Handle button clicks client.on(GatewayDispatchEvents.InteractionCreate, async (interaction: any) => { if (interaction.type !== 3) return; // MessageComponent if (interaction.data.custom_id === 'confirm') { await interaction.reply({ content: 'โœ… Confirmed!', ephemeral: true }); } else if (interaction.data.custom_id === 'cancel') { await interaction.reply({ content: 'โŒ Cancelled.', ephemeral: true }); } }); await client.login(); ``` -------------------------------- ### Using Collection for Extended Map Operations Source: https://context7.com/j6aoo/wave.js/llms.txt Demonstrates various functional helpers like find, filter, map, reduce, and sorting provided by the Collection class, which extends native Map. Ensure Collection is imported before use. ```typescript import { Collection } from 'wave.js'; const col = new Collection(); col.set('a', { name: 'Alice', score: 90 }); col.set('b', { name: 'Bob', score: 75 }); col.set('c', { name: 'Carol', score: 88 }); // find โ€” first match const topScorer = col.find(v => v.score >= 88); console.log(topScorer?.name); // 'Alice' // filter โ€” returns a new Collection const highScorers = col.filter(v => v.score >= 85); console.log(highScorers.size); // 2 // map โ€” returns a plain array const names = col.map(v => v.name.toUpperCase()); console.log(names); // ['ALICE', 'BOB', 'CAROL'] // reduce โ€” aggregate const total = col.reduce((acc, v) => acc + v.score, 0); console.log(total); // 253 // first / last / random console.log(col.first()?.name); // 'Alice' console.log(col.last()?.name); // 'Carol' console.log(col.first(2).map(v => v.name)); // ['Alice', 'Bob'] // sorted const ranked = col.sorted((a, b) => b.score - a.score); console.log(ranked.map(v => `${v.name}: ${v.score}`)); // ['Alice: 90', 'Carol: 88', 'Bob: 75'] // toArray / keyArray / clone console.log(col.keyArray()); // ['a', 'b', 'c'] const clone = col.clone(); console.log(clone.size); // 3 ``` -------------------------------- ### Manage Webhooks with WebhookManager Source: https://context7.com/j6aoo/wave.js/llms.txt Utilize WebhookManager for creating, executing, editing, and deleting webhooks. Supports standard, GitHub-compatible, and Slack-compatible payloads. ```typescript import { Client } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Create a webhook const webhook = await client.webhooks.create('1234567890123456789', { name: 'Build Notifier', avatar: 'https://example.com/ci-icon.png', }); console.log(`Webhook token: ${webhook.token}`); // Execute it (fire-and-forget) await client.webhooks.execute(webhook.id, webhook.token!, { content: '๐Ÿš€ Deployment to production succeeded!', username: 'CI Bot', avatar_url: 'https://example.com/ci-icon.png', embeds: [{ title: 'Build #42', description: 'All 128 tests passed.', color: 0x57f287 }], }); // Execute and wait for the returned Message object const msg = await client.webhooks.execute( webhook.id, webhook.token!, { content: 'Tracked message' }, true, // wait=true ); console.log(`Message ID: ${msg?.id}`); // GitHub-compatible payload await client.webhooks.executeGithub(webhook.id, webhook.token!, { repository: { full_name: 'fluxerapp/wave.js' }, commits: [{ message: 'fix: handle 429 correctly', author: { name: 'Dev' } }], }); // Edit then delete the webhook await client.webhooks.edit(webhook.id, { name: 'Updated Notifier' }); await client.webhooks.delete(webhook.id); }); await client.login(); ``` -------------------------------- ### WebhookManager Source: https://context7.com/j6aoo/wave.js/llms.txt Manage webhook creation, execution, editing, and deletion. Supports standard and GitHub-compatible payloads for seamless integration. ```APIDOC ## WebhookManager โ€” Create and Execute Webhooks `client.webhooks` manages webhook CRUD and execution, including GitHub/Slack-compatible payloads. ```typescript import { Client } from 'wave.js'; const client = new Client({ token: process.env.BOT_TOKEN! }); client.on('ready', async () => { // Create a webhook const webhook = await client.webhooks.create('1234567890123456789', { name: 'Build Notifier', avatar: 'https://example.com/ci-icon.png', }); console.log(`Webhook token: ${webhook.token}`); // Execute it (fire-and-forget) await client.webhooks.execute(webhook.id, webhook.token!, { content: '๐Ÿš€ Deployment to production succeeded!', username: 'CI Bot', avatar_url: 'https://example.com/ci-icon.png', embeds: [{ title: 'Build #42', description: 'All 128 tests passed.', color: 0x57f287 }], }); // Execute and wait for the returned Message object const msg = await client.webhooks.execute( webhook.id, webhook.token!, { content: 'Tracked message' }, true, // wait=true ); console.log(`Message ID: ${msg?.id}`); // GitHub-compatible payload await client.webhooks.executeGithub(webhook.id, webhook.token!, { repository: { full_name: 'fluxerapp/wave.js' }, commits: [{ message: 'fix: handle 429 correctly', author: { name: 'Dev' } }], }); // Edit then delete the webhook await client.webhooks.edit(webhook.id, { name: 'Updated Notifier' }); await client.webhooks.delete(webhook.id); }); await client.login(); ``` ``` -------------------------------- ### RestClient Methods Source: https://context7.com/j6aoo/wave.js/llms.txt The RestClient exposes typed HTTP methods with automatic rate-limit queuing. ```APIDOC ## RestClient ### Description Provides a low-level interface for making HTTP requests, with built-in rate-limiting and retry mechanisms. ### Constructor `new RestClient(options: RestClientOptions)` ### Options - `token` (string): The authentication token. - `retries` (number): The number of times to retry a failed request. ### Methods - `get(path: string, query?: object): Promise` - Performs a GET request. - `post(path: string, body?: object, options?: { files?: FileUpload[] }): Promise` - Performs a POST request. Can include JSON body and file uploads. - `patch(path: string, body?: object): Promise` - Performs a PATCH request. - `delete(path: string): Promise` - Performs a DELETE request. ### FileUpload - `file` (Buffer): The file content. - `filename` (string): The name of the file. - `description` (string): An optional description for the file. ```