### Local Development Setup for discord.js Guide Source: https://github.com/discordjs/guide/blob/main/CONTRIBUTING.md Installs project dependencies and starts a local development server for the discord.js guide. Assumes git, Node.js, and npm are installed. The server typically runs on port 8080, but can be configured. ```bash git clone https://github.com/discordjs/guide.git cd guide npm install npm run dev ``` -------------------------------- ### Configure package.json scripts Source: https://github.com/discordjs/guide/blob/main/guide/improving-dev-environment/package-json-scripts.md An example of a package.json file structure containing custom scripts for starting the application and linting source code. ```json { "name": "my-bot", "version": "1.0.0", "description": "A Discord bot!", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node .", "lint": "eslint ." }, "keywords": [], "author": "", "license": "ISC" } ``` -------------------------------- ### Install Keyv Backend Drivers Source: https://github.com/discordjs/guide/blob/main/guide/keyv/README.md Installs optional backend drivers for Keyv, such as Redis, MongoDB, SQLite, PostgreSQL, and MySQL. Choose the driver corresponding to your preferred persistent storage. ```sh npm install @keyv/redis npm install @keyv/mongo npm install @keyv/sqlite npm install @keyv/postgres npm install @keyv/mysql ``` ```sh yarn add @keyv/redis yarn add @keyv/mongo yarn add @keyv/sqlite yarn add @keyv/postgres yarn add @keyv/mysql ``` ```sh pnpm add @keyv/redis pnpm add @keyv/mongo pnpm add @keyv/sqlite pnpm add @keyv/postgres pnpm add @keyv/mysql ``` ```sh bun add @keyv/redis bun add @keyv/mongo bun add @keyv/sqlite bun add @keyv/postgres bun add @keyv/mysql ``` -------------------------------- ### Install Pino Logger and pino-pretty Source: https://github.com/discordjs/guide/blob/main/guide/miscellaneous/useful-packages.md Installs the Pino logger package and the pino-pretty utility for development. Supports npm, yarn, pnpm, and bun package managers. ```sh npm install pino@next npm install -g pino-pretty ``` ```sh yarn add pino@next yarn global add pino-pretty ``` ```sh pnpm add pino@next pnpm add --global pino-pretty ``` ```sh bun add pino@next bun add --global pino-pretty ``` -------------------------------- ### Basic discord.js and Sequelize Setup Source: https://github.com/discordjs/guide/blob/main/guide/sequelize/README.md Sets up a basic discord.js client and initializes a Sequelize instance for database connection. This code requires Node.js 7.6+ for async/await. ```javascript // Require Sequelize const Sequelize = require('sequelize'); // Require the necessary discord.js classes const { Client, Events, GatewayIntentBits } = require('discord.js'); // Create a new client instance const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // When the client is ready, run this code (only once) client.once(Events.ClientReady, readyClient => { console.log(`Ready! Logged in as ${readyClient.user.tag}`); }); client.on(Events.InteractionCreate, async interaction => { if (!interaction.isChatInputCommand()) return; const { commandName } = interaction; // ... }); // Login to Discord with your client's token client.login('your-token-goes-here'); ``` -------------------------------- ### Install ESLint with npm, yarn, pnpm, or bun Source: https://github.com/discordjs/guide/blob/main/guide/preparations/setting-up-a-linter.md Installs the ESLint package and its JavaScript configuration as development dependencies. This command is compatible with npm, yarn, pnpm, and bun package managers, ensuring flexibility in project setup. ```npm npm install --save-dev eslint @eslint/js ``` ```yarn yarn add eslint @eslint/js --dev ``` ```pnpm pnpm add --save-dev eslint @eslint/js ``` ```bun bun add --dev eslint ``` -------------------------------- ### Install Keyv with npm, yarn, pnpm, or bun Source: https://github.com/discordjs/guide/blob/main/guide/keyv/README.md Installs the Keyv package using different Node.js package managers. Keyv is a simple key-value store that works with multiple backends. ```sh npm install keyv ``` ```sh yarn add keyv ``` ```sh pnpm add keyv ``` ```sh bun add keyv ``` -------------------------------- ### Run Development Script with pino-pretty Source: https://github.com/discordjs/guide/blob/main/guide/miscellaneous/useful-packages.md Commands to execute the 'dev' script defined in package.json, which starts the bot with prettified log output using pino-pretty. Supports npm, yarn, pnpm, and bun. ```sh npm run dev ``` ```sh yarn run dev ``` ```sh pnpm run dev ``` ```sh bun run dev ``` -------------------------------- ### Install Sequelize and SQLite Source: https://github.com/discordjs/guide/blob/main/guide/sequelize/README.md Installs the necessary packages for discord.js, Sequelize, and SQLite using different package managers. Ensure you have Node.js version 7.6 or above for async/await support. ```npm npm install discord.js sequelize sqlite3 ``` ```yarn yarn add discord.js sequelize sqlite3 ``` ```pnpm pnpm install discord.js sequelize sqlite3 ``` ```bun bun add discord.js sequelize sqlite3 ``` -------------------------------- ### Updating Final Code Example Wording Source: https://github.com/discordjs/guide/blob/main/CONTRIBUTING.md Demonstrates a revision in the guide's text, changing 'Our final code' to 'Your final code' to maintain a consistent user-focused perspective when presenting code examples. ```diff - Our final code should look like this: ... + Your final code should look like this: ... ``` -------------------------------- ### Discord.js Bot Setup with Keyv for Prefixes Source: https://github.com/discordjs/guide/blob/main/guide/keyv/README.md Initializes a Discord.js client and sets up a Keyv instance to store per-guild prefixes, using SQLite as the backend. It includes necessary intents and loads configuration from a JSON file. ```javascript const { Keyv } = require('keyv'); const { Client, Events, GatewayIntentBits } = require('discord.js'); const { globalPrefix, token } = require('./config.json'); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] }); const prefixes = new Keyv('sqlite://path/to.sqlite'); ``` -------------------------------- ### Install Windows build tools Source: https://github.com/discordjs/guide/blob/main/guide/voice/README.md Installs necessary build tools for Windows environments to support native dependency compilation. ```npm npm install --global --production --add-python-to-path windows-build-tools ``` ```yarn yarn global add --production --add-python-to-path windows-build-tools ``` ```pnpm pnpm add --global --production --add-python-to-path windows-build-tools ``` ```bun bun add --global --production --add-python-to-path windows-build-tools ``` -------------------------------- ### JavaScript String Examples: Concatenation vs. Template Literals Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md Illustrates the usage of standard string concatenation versus ES6 template literals for outputting variable values, performing calculations, calling functions, and creating multiline strings. Template literals provide a more concise and readable syntax. ```javascript // variables/function used throughout the examples const username = 'Sanctuary'; const password = 'pleasedonthackme'; function letsPretendThisDoesSomething() { return 'Yay for sample data.'; } // regular string concatenation console.log('Your username is: **' + username + '**.'); console.log('Your password is: **' + password + '**.'); console.log('1 + 1 = ' + (1 + 1)); console.log('And here\'s a function call: ' + letsPretendThisDoesSomething()); console.log( 'Putting strings on new lines\n' + 'can be a bit painful\n' + 'with string concatenation. :( '); ``` ```javascript // variables/function used throughout the examples const username = 'Sanctuary'; const password = 'pleasedonthackme'; function letsPretendThisDoesSomething() { return 'Yay for sample data.'; } // template literals console.log(`Your username is: **${username}**.`); console.log(`Your password is: **${password}**.`); console.log(`1 + 1 = ${1 + 1}`); console.log(`And here's a function call: ${letsPretendThisDoesSomething()}`); console.log(` Putting strings on new lines is a breeze with template literals! :) `); // NOTE: template literals will also render the indentation inside them // there are ways around that, which we'll discuss in another section. ``` -------------------------------- ### Discord Bot Startup Code with ES6 Syntax Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md This code snippet initializes a discord.js client, sets up event listeners for bot readiness and interactions, and handles basic chat commands using ES6 features like `const` and arrow functions. ```javascript const { Client, Events, GatewayIntentBits } = require('discord.js'); const config = require('./config.json'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.once(Events.ClientReady, () => { console.log('Ready!'); }); client.on(Events.InteractionCreate, interaction => { if (!interaction.isChatInputCommand()) return; const { commandName } = interaction; if (commandName === 'ping') { interaction.reply('Pong.'); } else if (commandName === 'beep') { interaction.reply('Boop.'); } else if (commandName === 'server') { interaction.reply('Guild name: ' + interaction.guild.name + '\nTotal members: ' + interaction.guild.memberCount); } else if (commandName === 'user-info') { interaction.reply('Your username: ' + interaction.user.username + '\nYour ID: ' + interaction.user.id); } }); client.login(config.token); ``` -------------------------------- ### Basic Keyv Usage (Set, Get, Clear) Source: https://github.com/discordjs/guide/blob/main/guide/keyv/README.md Demonstrates the fundamental Map-like API of Keyv, including setting a key-value pair, retrieving a value by its key, clearing all data, and retrieving a non-existent key. All operations return Promises. ```javascript (async () => { // true await keyv.set('foo', 'bar'); // bar await keyv.get('foo'); // undefined aawait keyv.clear(); // undefined aawait keyv.get('foo'); })(); ``` -------------------------------- ### JavaScript Object Destructuring for Configuration Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md Illustrates how object destructuring simplifies extracting properties from configuration objects in JavaScript. It reduces verbosity compared to traditional property access. ```javascript const config = require('./config.json'); const prefix = config.prefix; const token = config.token; ``` ```javascript const { prefix, token } = require('./config.json'); ``` -------------------------------- ### Initialize Express web server Source: https://github.com/discordjs/guide/blob/main/guide/oauth2/README.md A Node.js script using the Express framework to serve an index.html file and listen for incoming HTTP requests on a specified port. ```javascript const express = require('express'); const { port } = require('./config.json'); const app = express(); app.get('/', (request, response) => { return response.sendFile('index.html', { root: '.' }); }); app.listen(port, () => console.log(`App listening at http://localhost:${port}`)); ``` -------------------------------- ### Implement basic Discord.js bot client Source: https://github.com/discordjs/guide/blob/main/guide/sharding/README.md A standard Discord.js client implementation that listens for interaction events. This example shows a basic stats command that returns the cached guild count, which requires modification when sharding is enabled. ```javascript // bot.js const { Client, Events, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.on(Events.InteractionCreate, interaction => { if (!interaction.isChatInputCommand()) return; const { commandName } = interaction; if (commandName === 'stats') { return interaction.reply(`Server count: ${client.guilds.cache.size}.`); } }); client.login('your-token-goes-here'); ``` -------------------------------- ### Install Git on Ubuntu/Debian Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/errors.md This command installs the Git version control system on Ubuntu or Debian-based Linux distributions. Git is often a dependency for various development tools and processes. ```bash sudo apt-get install git ``` -------------------------------- ### Install and Use dotenv for Environment Variables Source: https://github.com/discordjs/guide/blob/main/guide/creating-your-bot/README.md Provides instructions for installing the `dotenv` package using npm, yarn, pnpm, or noting its automatic support in Bun. It then shows how to load environment variables from a `.env` file into `process.env` for use in your application. ```sh npm install dotenv ``` ```sh yarn add dotenv ``` ```sh pnpm add dotenv ``` ```sh # dotenv is not necessary with Bun # Bun reads .env files automatically ``` ```dotenv A=123 B=456 DISCORD_TOKEN=your-token-goes-here ``` ```javascript const dotenv = require('dotenv'); dotenv.config(); console.log(process.env.A); console.log(process.env.B); console.log(process.env.DISCORD_TOKEN); ``` -------------------------------- ### Install @napi-rs/canvas package Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/canvas.md Commands to install the @napi-rs/canvas dependency using various Node.js package managers. ```npm npm install @napi-rs/canvas ``` ```yarn yarn add @napi-rs/canvas ``` ```pnpm pnpm add @napi-rs/canvas ``` ```bun bun add @napi-rs/canvas ``` -------------------------------- ### Install undici for Discord.js Bots Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/rest-api.md Instructions for installing the 'undici' HTTP client library using various package managers (npm, yarn, pnpm, bun). This library is essential for making API requests in Node.js. ```sh npm install undici ``` ```sh yarn add undici ``` ```sh pnpm add undici ``` ```sh bun add undici ``` -------------------------------- ### Initialize Discord Client Instance Source: https://context7.com/discordjs/guide/llms.txt Demonstrates how to instantiate the discord.js Client with required GatewayIntents. It includes an event listener for the 'ready' state and the login process using a bot token. ```javascript const { Client, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions ] }); client.once(Events.ClientReady, readyClient => { console.log(`Ready! Logged in as ${readyClient.user.tag}`); }); client.login(token); ``` -------------------------------- ### Initialize Discord Bot Client and Login - JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/creating-your-bot/main-file.md This JavaScript code snippet demonstrates how to create a new Discord client instance using discord.js. It requires the 'discord.js' library and your bot's token from a 'config.json' file. The client is configured with `GatewayIntentBits.Guilds` to receive guild-related events and caches. The code logs a 'Ready!' message to the console when the bot successfully connects to Discord. ```javascript // Require the necessary discord.js classes const { Client, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); // Create a new client instance const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // When the client is ready, run this code (only once). // The distinction between `client: Client` and `readyClient: Client` is important for TypeScript developers. // It makes some properties non-nullable. client.once(Events.ClientReady, readyClient => { console.log(`Ready! Logged in as ${readyClient.user.tag}`); }); // Log in to Discord with your client's token client.login(token); ``` -------------------------------- ### Create and Configure Audio Player Source: https://github.com/discordjs/guide/blob/main/guide/voice/audio-player.md Demonstrates how to instantiate an audio player using @discordjs/voice, including optional configuration for handling scenarios where there are no active subscribers. ```javascript const { createAudioPlayer } = require('@discordjs/voice'); const player = createAudioPlayer(); ``` ```javascript const { createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice'); const player = createAudioPlayer({ behaviors: { noSubscriber: NoSubscriberBehavior.Pause, }, }); ``` -------------------------------- ### Initialize package.json Source: https://github.com/discordjs/guide/blob/main/guide/improving-dev-environment/package-json-scripts.md Commands to generate a new package.json file in the current directory. This is a prerequisite for managing project dependencies and scripts. ```npm npm init -y ``` ```yarn yarn init -y ``` ```pnpm pnpm init ``` ```bun bun init -y ``` -------------------------------- ### Running ESLint for Linting discord.js Guide Code Source: https://github.com/discordjs/guide/blob/main/CONTRIBUTING.md Executes the ESLint linter to check for code style consistency and potential errors in JavaScript files and code blocks within Markdown files. This script is part of the local development setup. ```bash npm run lint ``` -------------------------------- ### Create basic HTML user interface Source: https://github.com/discordjs/guide/blob/main/guide/oauth2/README.md A simple HTML template used to display the application interface to the user. ```html My Discord OAuth2 App
Hoi!
``` -------------------------------- ### Create Audio Resources with Discord.js Source: https://github.com/discordjs/guide/blob/main/guide/voice/audio-resources.md Demonstrates various ways to instantiate an AudioResource, including basic file loading, enabling inline volume control, and using pre-encoded Opus streams for better performance. ```javascript const { createReadStream } = require('node:fs'); const { join } = require('node:path'); const { createAudioResource, StreamType } = require('@discordjs/voice'); // Basic, default options are: // Input type is unknown, so will use FFmpeg to convert to Opus under-the-hood // Inline volume is opt-in to improve performance let resource = createAudioResource(join(__dirname, 'file.mp3')); // Will use FFmpeg with volume control enabled resource = createAudioResource(join(__dirname, 'file.mp3'), { inlineVolume: true }); resource.volume.setVolume(0.5); // Will play .ogg or .webm Opus files without FFmpeg for better performance // Remember, inline volume is still disabled resource = createAudioResource(createReadStream(join(__dirname, 'file.ogg'), { inputType: StreamType.OggOpus, })); // Will play with FFmpeg due to inline volume being enabled. resource = createAudioResource(createReadStream(join(__dirname, 'file.webm'), { inputType: StreamType.WebmOpus, inlineVolume: true, })); player.play(resource); ``` -------------------------------- ### Execute project scripts Source: https://github.com/discordjs/guide/blob/main/guide/improving-dev-environment/package-json-scripts.md Commands to run defined scripts from the package.json file using different package managers. Replace with the specific key defined in the scripts object. ```npm npm run ``` ```yarn yarn run ``` ```pnpm pnpm run ``` ```bun bun run ``` -------------------------------- ### Manage Threads with Discord.js Source: https://context7.com/discordjs/guide/llms.txt Covers creating public and private threads, starting threads from messages, managing membership, and handling thread state like archiving and locking. ```javascript const { ChannelType, ThreadAutoArchiveDuration } = require('discord.js'); const thread = await channel.threads.create({ name: 'food-talk', autoArchiveDuration: ThreadAutoArchiveDuration.OneHour, reason: 'Needed a separate thread for food', }); const privateThread = await channel.threads.create({ name: 'mod-talk', autoArchiveDuration: ThreadAutoArchiveDuration.OneHour, type: ChannelType.PrivateThread, reason: 'Needed a separate thread for moderation', }); const messageThread = await message.startThread({ name: 'discussion', autoArchiveDuration: ThreadAutoArchiveDuration.OneHour, }); if (thread.joinable) await thread.join(); await thread.leave(); await thread.setArchived(true); await thread.setLocked(true); await thread.members.add('140214425276776449'); await thread.members.remove('140214425276776449'); const webhook = webhooks.first(); await webhook.send({ content: 'Message in thread!', threadId: '123456789012345678', }); ``` -------------------------------- ### Basic discord.js Bot Setup with ES6 Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/async-await.md Initializes a discord.js client with specified intents and logs a message when the bot is ready. It also sets up a listener for interaction events, specifically checking for chat input commands. ```javascript const { Client, Events, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); client.once(Events.ClientReady, () => { console.log('I am ready!'); }); client.on(Events.InteractionCreate, interaction => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'react') { // ... } }); client.login('your-token-goes-here'); ``` -------------------------------- ### Create Public Thread from Message Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/threads.md Creates a public thread starting from an existing message. If the originating message is deleted, the thread becomes orphaned. This method is called on the message object itself. ```javascript const thread = await message.startThread({ name: 'food-talk', autoArchiveDuration: ThreadAutoArchiveDuration.OneHour, reason: 'Needed a separate thread for food', }); console.log(`Created thread: ${thread.name}`); ``` -------------------------------- ### Configure OAuth2 credentials and server settings Source: https://github.com/discordjs/guide/blob/main/guide/oauth2/README.md A JSON configuration file storing the Discord application's client ID, client secret, and the local server port. ```json { "clientId": "", "clientSecret": "", "port": 53134 } ``` -------------------------------- ### Configure System Startup for PM2 on Linux/macOS Source: https://github.com/discordjs/guide/blob/main/guide/improving-dev-environment/pm2.md Generate and run the necessary startup script for PM2 on Linux or macOS systems. This ensures your bot processes automatically start when the operating system boots. ```sh # Detects the available init system, generates the config, and enables startup system pm2 startup pm2 startup [ubuntu | ubuntu14 | ubuntu12 | centos | centos6 | arch | oracle | amazon | macos | darwin | freesd | systemd | systemv | upstart | launchd | rcd | openrc] # Example output for an Ubuntu user: # [PM2] You have to run this command as root. Execute the following command: # sudo su -c "env PATH=$PATH:/home/user/.nvm/versions/node/v8.9/bin pm2 startup ubuntu -u user --hp /home/user ``` -------------------------------- ### Fetch User Data with Access Token Source: https://github.com/discordjs/guide/blob/main/guide/oauth2/README.md This JavaScript code snippet demonstrates how to use the obtained access token to fetch the current user's data from the Discord API. It makes a GET request to the '/api/users/@me' endpoint, including the authorization header with the token type and access token. The user data is then logged to the console. ```javascript const { request } = require('undici'); // Assuming oauthData is available from the previous step // const oauthData = { token_type: 'Bearer', access_token: '...' }; const userResult = await request('https://discord.com/api/users/@me', { headers: { authorization: `${oauthData.token_type} ${oauthData.access_token}`, }, }); console.log(await userResult.body.json()); ``` -------------------------------- ### Markdown for Code Samples Directory Structure Source: https://github.com/discordjs/guide/blob/main/CONTRIBUTING.md Provides guidance on organizing code samples. When creating a page that teaches a step-by-step process, the final code should be placed in the `/code-samples` directory. The folder structure within `/code-samples` should mirror the structure within the `/guide` directory (e.g., `guide/foo/bar.md` corresponds to `code-samples/foo/bar/index.js`). ```markdown ``` -------------------------------- ### Building and Sending Rich Embeds Source: https://context7.com/discordjs/guide/llms.txt Utilizes the EmbedBuilder class to create visually structured messages with fields, images, and footers. It also includes an example of attaching local files to an embed. ```javascript const { EmbedBuilder, AttachmentBuilder } = require('discord.js'); const exampleEmbed = new EmbedBuilder() .setColor(0x0099FF) .setTitle('Some title') .setURL('https://discord.js.org/') .setAuthor({ name: 'Some name', iconURL: 'https://i.imgur.com/AfFp7pu.png', url: 'https://discord.js.org' }) .setDescription('Some description here') .setThumbnail('https://i.imgur.com/AfFp7pu.png') .addFields( { name: 'Regular field title', value: 'Some value here' }, { name: '\u200B', value: '\u200B' }, { name: 'Inline field title', value: 'Some value here', inline: true }, { name: 'Inline field title', value: 'Some value here', inline: true }, ) .setImage('https://i.imgur.com/AfFp7pu.png') .setTimestamp() .setFooter({ text: 'Some footer text here', iconURL: 'https://i.imgur.com/AfFp7pu.png' }); channel.send({ embeds: [exampleEmbed] }); const file = new AttachmentBuilder('../assets/discordjs.png'); const embedWithImage = new EmbedBuilder() .setTitle('Some title') .setImage('attachment://discordjs.png'); channel.send({ embeds: [embedWithImage], files: [file] }); ``` -------------------------------- ### Create and Configure Action Rows Source: https://github.com/discordjs/guide/blob/main/guide/interactive-components/action-rows.md Demonstrates how to instantiate an ActionRowBuilder and add components to it. Includes a TypeScript-specific example for defining component types using generics. ```javascript const row = new ActionRowBuilder() .addComponents(component); ``` ```typescript new ActionRowBuilder() ``` -------------------------------- ### Creating a Webhook with discord.js in JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/webhooks.md This code example illustrates how to create a new webhook associated with a specific text channel using the `createWebhook` method. It allows setting the webhook's name and avatar. ```javascript channel.createWebhook({ name: 'Some-username', avatar: 'https://i.imgur.com/AfFp7pu.png', }) .then(webhook => console.log(`Created webhook ${webhook}`)) .catch(console.error); ``` -------------------------------- ### Initializing WebhookClient with URL in JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/webhooks.md Demonstrates creating a `WebhookClient` by providing the webhook's URL directly. This is a convenient way to initialize the client when the full URL is available. ```javascript const webhookClient = new WebhookClient({ url: 'https://discord.com/api/webhooks/id/token' }); ``` -------------------------------- ### JavaScript Object Destructuring with Renamed Variables Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md Demonstrates how to rename variables during object destructuring in JavaScript when the property name is a reserved keyword or conflicts with an existing variable. This ensures proper assignment. ```javascript // `default` is a reserved keyword const { 'default': defaultValue } = someObject; console.log(defaultValue); // 'Some default value here' ``` -------------------------------- ### Create a Role with Specific Permissions - JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/permissions.md Creates a new role with a specified name and a set of permissions defined by an array of flag strings. This allows for granular control over new roles' capabilities from the start. ```javascript const { PermissionsBitField } = require('discord.js'); guild.roles.create({ name: 'Mod', permissions: [PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.KickMembers] }); ``` -------------------------------- ### Initialize Keyv Instance Source: https://github.com/discordjs/guide/blob/main/guide/keyv/README.md Creates a new Keyv instance. You can initialize it for in-memory storage or connect to various persistent backends like Redis, MongoDB, SQLite, PostgreSQL, or MySQL by providing the appropriate connection URI. ```javascript const { Keyv } = require('keyv'); // One of the following const keyv = new Keyv(); // for in-memory storage const keyv = new Keyv('redis://user:pass@localhost:6379'); const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); const keyv = new Keyv('sqlite://path/to/database.sqlite'); const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname'); const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname'); ``` -------------------------------- ### Initializing WebhookClient with ID and Token in JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/webhooks.md Shows how to create a `WebhookClient` instance using a webhook's ID and token. This method is useful for interacting with webhooks without needing a full bot client. ```javascript const webhookClient = new WebhookClient({ id: 'id', token: 'token' }); ``` -------------------------------- ### Set Base Permissions for a Role - JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/permissions.md Sets the base permissions for a given role using an array of permission flags. Permissions not included in the array are denied for the role. This example sets permissions for the '@everyone' role. ```javascript const { PermissionsBitField } = require('discord.js'); guild.roles.everyone.setPermissions([PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.ViewChannel]); ``` -------------------------------- ### Array Destructuring in JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md Demonstrates array destructuring to extract elements from an array into distinct variables. This method is more concise than traditional index-based access. It also shows how to skip elements using commas. ```javascript const [name, age, location] = args; ``` ```javascript const [, username, id] = message.content.match(someRegex); ``` -------------------------------- ### Initialize ShardingManager for Discord.js Source: https://github.com/discordjs/guide/blob/main/guide/sharding/README.md This snippet demonstrates how to set up a ShardingManager to spawn multiple bot processes. It requires the path to the main bot file and the bot token, and includes an event listener to log shard creation. ```javascript const { ShardingManager } = require('discord.js'); const manager = new ShardingManager('./bot.js', { token: 'your-token-goes-here' }); manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`)); manager.spawn(); ``` -------------------------------- ### JavaScript Object Destructuring for Interaction Commands Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md Shows how object destructuring can be used within an event listener to easily access properties like `commandName` from an interaction object in JavaScript. This makes command handling cleaner. ```javascript client.on(Events.InteractionCreate, interaction => { const { commandName } = interaction; if (commandName === 'ping') { // ping command here... } else if (commandName === 'beep') { // beep command here... } // other commands here... }); ``` -------------------------------- ### Display shop inventory in Discord.js Source: https://github.com/discordjs/guide/blob/main/guide/sequelize/currency.md Retrieves all available items from the CurrencyShop database and formats them into a readable code block for the user. ```javascript else if (commandName === 'shop') { const items = await CurrencyShop.findAll(); return interaction.reply(codeBlock(items.map(i => `${i.name}: ${i.cost}💰`).join('\n'))); } ``` -------------------------------- ### Configure pino-pretty in package.json Scripts Source: https://github.com/discordjs/guide/blob/main/guide/miscellaneous/useful-packages.md Sets up a 'dev' script in package.json to run the bot and pipe its output to pino-pretty for formatted, human-readable logs during development. Includes options to hide PID/hostname and format timestamps. ```json { "name": "my-bot", "version": "1.0.0", "description": "A Discord bot!", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node .", "lint": "eslint .", "dev": "node . | pino-pretty -i pid,hostname -t 'yyyy-mm-dd HH:MM:ss'" }, "keywords": [], "author": "", "license": "ISC" } ``` -------------------------------- ### Handle Authorization Code in Express Source: https://github.com/discordjs/guide/blob/main/guide/oauth2/README.md This snippet demonstrates how to extract the authorization code from the request query parameters in an Express.js application. It logs the code and serves an index.html file. This is the first step in the authorization code grant flow. ```javascript app.get('/', (request, response) => { console.log(`The access code is: ${request.query.code}`); return response.sendFile('index.html', { root: '.' }); }); ``` -------------------------------- ### Initialize Sequelize Database and Sync Models (JavaScript) Source: https://github.com/discordjs/guide/blob/main/guide/sequelize/currency.md This script initializes a Sequelize instance for an SQLite database, defines models for CurrencyShop, Users, and UserItems, and then synchronizes these models with the database. It includes functionality to upsert initial data into the CurrencyShop and ensures the database is synced only once. The `--force` or `-f` flag can be used to drop and recreate tables. ```javascript const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'sqlite', logging: false, storage: 'database.sqlite', }); const CurrencyShop = require('./models/CurrencyShop.js')(sequelize, Sequelize.DataTypes); require('./models/Users.js')(sequelize, Sequelize.DataTypes); require('./models/UserItems.js')(sequelize, Sequelize.DataTypes); const force = process.argv.includes('--force') || process.argv.includes('-f'); sequelize.sync({ force }).then(async () => { const shop = [ CurrencyShop.upsert({ name: 'Tea', cost: 1 }), CurrencyShop.upsert({ name: 'Coffee', cost: 2 }), CurrencyShop.upsert({ name: 'Cake', cost: 5 }), ]; await Promise.all(shop); console.log('Database synced'); sequelize.close(); }).catch(console.error); ``` -------------------------------- ### Await Modal Submit Interaction Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/collectors.md This example demonstrates how to use `awaitModalSubmit` to wait for a modal submission. It's useful within command or button executions. A `time` limit is crucial as Discord doesn't notify about modal dismissals. Requires 'discord.js'. ```javascript initialInteraction.awaitModalSubmit({ time: 60_000, filter }) .then(interaction => interaction.editReply('Thank you for your submission!')) .catch(err => console.log('No modal submit interaction was collected')); ``` -------------------------------- ### Probe and Create Audio Resource with @discordjs/voice Source: https://github.com/discordjs/guide/blob/main/guide/voice/audio-resources.md This snippet demonstrates how to use demuxProbe to analyze the beginning of an audio stream and create a compatible AudioResource. It handles various file formats by automatically detecting the stream type and passing it to createAudioResource. ```javascript const { createReadStream } = require('node:fs'); const { demuxProbe, createAudioResource } = require('@discordjs/voice'); async function probeAndCreateResource(readableStream) { const { stream, type } = await demuxProbe(readableStream); return createAudioResource(stream, { inputType: type }); } async function createResources() { // Creates an audio resource with inputType = StreamType.Arbitrary const mp3Stream = await probeAndCreateResource(createReadStream('file.mp3')); // Creates an audio resource with inputType = StreamType.OggOpus const oggStream = await probeAndCreateResource(createReadStream('file.ogg')); // Creates an audio resource with inputType = StreamType.WebmOpus const webmStream = await probeAndCreateResource(createReadStream('file.webm')); } createResources(); ``` -------------------------------- ### Markdown for General Document Structure and Code Examples Source: https://github.com/discordjs/guide/blob/main/CONTRIBUTING.md Illustrates standard Markdown usage for section titles, paragraphs, and embedding code blocks. It emphasizes using blank lines for readability and shows a basic JavaScript code snippet within a Markdown file. ```markdown ## Section title Here's an example of how you'd do that really cool thing: ```js const { data } = request; console.log(data); `​`` And here's a sentence that would explain how that works, maybe. ::: tip Here's where we'd tell you something even cooler than the really cool thing you just learned. ::: ::: warning This is where we'd warn you about the possible issues that arise when using this method. ::: ``` -------------------------------- ### Purchase items from a database shop in Discord.js Source: https://github.com/discordjs/guide/blob/main/guide/sequelize/currency.md Allows users to buy items by querying a database, checking for existence and sufficient funds. It updates the user's balance and adds the item to their inventory upon a successful transaction. ```javascript else if (commandName === 'buy') { const itemName = interaction.options.getString('item'); const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: itemName } } }); if (!item) return interaction.reply(`That item doesn't exist.`); if (item.cost > getBalance(interaction.user.id)) { return interaction.reply(`You currently have ${getBalance(interaction.user.id)}, but the ${item.name} costs ${item.cost}!`); } const user = await Users.findOne({ where: { user_id: interaction.user.id } }); addBalance(interaction.user.id, -item.cost); await user.addItem(item); return interaction.reply(`You've bought: ${item.name}.`); } ``` -------------------------------- ### JavaScript Arrow Functions vs. Regular Functions Source: https://github.com/discordjs/guide/blob/main/guide/additional-info/es6-syntax.md Demonstrates the syntax and conciseness of ES6 arrow functions compared to traditional ES5 regular functions for event handling and simple operations in JavaScript. Arrow functions offer a shorter syntax and lexical `this` binding. ```javascript // regular functions, full ES5 client.once(Events.ClientReady, function() { console.log('Ready!'); }); client.on(Events.TypingStart, function(typing) { console.log(typing.user.tag + ' started typing in #' + typing.channel.name); }); client.on(Events.MessageCreate, function(message) { console.log(message.author.tag + ' sent: ' + message.content); }); var doubleAge = function(age) { return 'Your age doubled is: ' + (age * 2); }; // inside a message collector command var collectorFilter = function(m) { return m.content === 'I agree' && !m.author.bot; }; var collector = message.createMessageCollector({ filter: collectorFilter, time: 15_000 }); ``` ```javascript // arrow functions, full ES6 client.once(Events.ClientReady, () => console.log('Ready!')); client.on(Events.TypingStart, typing => console.log(`${typing.user.tag} started typing in #${typing.channel.name}`)); client.on(Events.MessageCreate, message => console.log(`${message.author.tag} sent: ${message.content}`)); const doubleAge = age => `Your age doubled is: ${age * 2}`; // inside a message collector command const collectorFilter = m => m.content === 'I agree' && !m.author.bot; const collector = message.createMessageCollector({ filter: collectorFilter, time: 15_000 }); ``` -------------------------------- ### Discord Bot Application Skeleton (JavaScript) Source: https://github.com/discordjs/guide/blob/main/guide/sequelize/currency.md This code snippet provides the basic structure for a Discord bot application using discord.js. It initializes the client, sets up intents, defines event handlers for 'ready' and 'messageCreate', and includes a placeholder for interaction handling. It also demonstrates importing database models and using a Collection for caching. ```javascript const { Op } = require('sequelize'); const { Client, codeBlock, Collection, Events, GatewayIntentBits } = require('discord.js'); const { Users, CurrencyShop } = require('./dbObjects.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] }); const currency = new Collection(); client.once(Events.ClientReady, readyClient => { console.log(`Ready! Logged in as ${readyClient.user.tag}`); }); client.on(Events.MessageCreate, async message => { if (message.author.bot) return; addBalance(message.author.id, 1); }); client.on(Events.InteractionCreate, async interaction => { if (!interaction.isChatInputCommand()) return; const { commandName } = interaction; // ... }); client.login('your-token-goes-here'); ``` -------------------------------- ### Create Channel with Permission Overwrites (JavaScript) Source: https://github.com/discordjs/guide/blob/main/guide/popular-topics/permissions.md Creates a new channel with initial permission overwrites defined in an array. Each object in the array specifies the `id` of the role or user and the `allow` or `deny` permissions using `PermissionsBitField`. This is useful for setting up channels with specific access controls from the start. ```javascript const { ChannelType, PermissionsBitField } = require('discord.js'); guild.channels.create({ name: 'new-channel', type: ChannelType.GuildText, permissionOverwrites: [ { id: interaction.guild.id, deny: [PermissionsBitField.Flags.ViewChannel], }, { id: interaction.user.id, allow: [PermissionsBitField.Flags.ViewChannel], }, ], }); ``` -------------------------------- ### Generate Random String for OAuth2 State Parameter in JavaScript Source: https://github.com/discordjs/guide/blob/main/guide/oauth2/README.md This JavaScript function generates a random string used for the OAuth2 'state' parameter. This helps prevent CSRF attacks by ensuring the request and response states match. The generated string is encoded in Base64 before being appended to the OAuth2 URL. ```javascript function generateRandomString() { let randomString = ''; const randomNumber = Math.floor(Math.random() * 10); for (let i = 0; i < 20 + randomNumber; i++) { randomString += String.fromCharCode(33 + Math.floor(Math.random() * 94)); } return randomString; } window.onload = () => { // ... if (!accessToken) { const randomString = generateRandomString(); localStorage.setItem('oauth-state', randomString); document.getElementById('login').href += `&state=${btoa(randomString)}`; return (document.getElementById('login').style.display = 'block'); } }; ```