From 4ffe09fd3d0167e9952a2264f4ebdaddc9c18fae Mon Sep 17 00:00:00 2001 From: Supercrafter100 <58982133+supercrafter100@users.noreply.github.com> Date: Mon, 23 Oct 2023 21:06:37 +0200 Subject: [PATCH 1/3] proposed new folder layout --- 01-discordjs/.env-example | 1 - 01-discordjs/README.md | 39 ++++++++ 01-discordjs/bot.js | 66 ++----------- 01-discordjs/commands/choochoo.js | 8 +- 01-discordjs/commands/gif.js | 48 --------- 01-discordjs/commands/randomwalk.js | 52 ---------- 01-discordjs/commands/roshambo.js | 104 -------------------- README.md | 147 ++++++---------------------- 8 files changed, 80 insertions(+), 385 deletions(-) create mode 100644 01-discordjs/README.md delete mode 100644 01-discordjs/commands/gif.js delete mode 100644 01-discordjs/commands/randomwalk.js delete mode 100644 01-discordjs/commands/roshambo.js diff --git a/01-discordjs/.env-example b/01-discordjs/.env-example index d0fb119..886b3d9 100644 --- a/01-discordjs/.env-example +++ b/01-discordjs/.env-example @@ -1,4 +1,3 @@ SERVERID=1234 CLIENTID=1234 TOKEN=abcd1234 -TENORKEY=abcd2345 \ No newline at end of file diff --git a/01-discordjs/README.md b/01-discordjs/README.md new file mode 100644 index 0000000..99ca517 --- /dev/null +++ b/01-discordjs/README.md @@ -0,0 +1,39 @@ +# Episode 1 + +## Steps to deploy your bot! + +Make sure you first follow all the steps in the main README file of this repository before trying to deploy the bot. These include some steps on creating a Discord application in case you don't have that yet! + +### 1. Set up your project + +Make sure you open a terminal inside this directory! Next, execute the following code to install all the required dependencies: + +```sh +$ npm install +``` + +### 2. Deploy the commands + +Deploy the slash commands so Discord knows about them and can show them to your Discord users! Use the following command to deploy the commands: + +```sh +node deploy-commands.js +``` + +You only have to do this once. If you change the command (altering descriptions, changing options, etc.), then you do need to re-run `deploy-commands.js`. + +### 10. Start the bot + +Now start the bot using the following command: + +```sh +node bot.js +``` + +You should get a little message indicating the bot is ready! If you get an error, make sure you've entered the correct bot token in the `.env` file! + +### Recap of the code elements showcased in this episode + +- `commands/choochoo.js`: Defines a simple slash command. +- `bot.js`: Handles interactions with Discord and executes commands. +- `deploy-commands.js`: Script to register slash commands with Discord API. diff --git a/01-discordjs/bot.js b/01-discordjs/bot.js index 7cc420b..55cc775 100644 --- a/01-discordjs/bot.js +++ b/01-discordjs/bot.js @@ -2,10 +2,8 @@ import { Client, Events, GatewayIntentBits } from 'discord.js'; import { config } from 'dotenv'; +// Import everything the commands/choochoo.js file exports and store it inside the choochoo variable. import * as choochoo from './commands/choochoo.js'; -import * as gif from './commands/gif.js'; -import * as randomwalk from './commands/randomwalk.js'; -import * as roshambo from './commands/roshambo.js'; // Call the config() function on dotenv to load the environmental variables from the .env file config(); @@ -15,75 +13,31 @@ config(); const client = new Client({ intents: [ GatewayIntentBits.Guilds, - GatewayIntentBits.GuildMessages, - GatewayIntentBits.GuildMessageReactions, ], }); -// Event listener that executes once when the client successfully connects to Discord -client.once(Events.ClientReady, readyDiscord); - -// Login to Discord with your bot's token (stored in the .env file) -client.login(process.env.TOKEN); - // A function executed when the Discord client is ready and connected function readyDiscord() { - console.log('πŸ’– Logged in as', client.user.tag); - startTalking(); + console.log('πŸš‚ ', client.user.tag); } -// Event listener for when a slash command is executed -client.on(Events.InteractionCreate, async (interaction) => { +// A function executed when the Discord client receives an interaction +async function handleInteraction(interaction) { // Ensure interaction is a command before proceeding if (!interaction.isCommand()) return; // Command execution mapping if (interaction.commandName === 'choochoo') { await choochoo.execute(interaction); - } else if (interaction.commandName === 'gif') { - await gif.execute(interaction); - } else if (interaction.commandName === 'randomwalk') { - await randomwalk.execute(interaction); - } else if (interaction.commandName === 'roshambo') { - await roshambo.execute(interaction); } -}); - -// Function that sends a message to a specific channel every 60 minutes -function startTalking() { - // Retrieve the desired channel using its ID - const channel = client.channels.cache.get('1139569830761070651'); - - // Send a message to the channel every 60*60*1000 milliseconds (1 hour) - setInterval(() => { - channel.send('Hello, this is your bot speaking!'); - }, 60 * 60 * 1000); } -// Event listener for when a reaction is added to a message -client.on(Events.MessageReactionAdd, (reaction, user) => { - // Retrieve the emoji used for the reaction - let emoji = reaction.emoji.name; - - // If the emoji is custom, format it accordingly - if (reaction.emoji.id) { - emoji = `<:${reaction.emoji.name}:${reaction.emoji.id}>`; - } +// Event listener that executes once when the client successfully connects to Discord +client.once(Events.ClientReady, readyDiscord); - // Retrieve the channel using its ID and send a message indicating the user and emoji - const channel = client.channels.cache.get('1139569830761070651'); - channel.send(`${user.username} reacted with ${emoji}`); -}); +// Event listener for when a slash command is executed +client.on(Events.InteractionCreate, handleInteraction); -// Event listener for handling any received message -client.on(Events.MessageCreate, (message) => { - // If the message author is not a bot and the bot is mentioned in the message - if (!message.author.bot && message.mentions.has(client.user)) { - // Remove the bot mention from the message content - const mention = /<@.*?\s/; - const content = message.content.replace(mention, '').trim(); +// Login to Discord with your bot's token (stored in the .env file) +client.login(process.env.TOKEN); - // Respond to the message - message.reply(`How does ${content} make you feel?`); - } -}); diff --git a/01-discordjs/commands/choochoo.js b/01-discordjs/commands/choochoo.js index d28bcb6..bd5f390 100644 --- a/01-discordjs/commands/choochoo.js +++ b/01-discordjs/commands/choochoo.js @@ -1,16 +1,12 @@ // Importing modules using ES6 syntax import { SlashCommandBuilder } from 'discord.js'; -// Replies array -const replies = ['πŸš‚πŸŒˆπŸ’–', 'Choo choo!', 'Ding! πŸ›Ž', 'Never forget this dot!']; - // Command Builder export export const data = new SlashCommandBuilder() .setName('choochoo') - .setDescription('Replies with a random phrase!'); + .setDescription('This is a demo choo choo!'); // Execute function export export async function execute(interaction) { - const index = Math.floor(Math.random() * replies.length); - await interaction.reply(replies[index]); + await interaction.reply('choo choo!'); } diff --git a/01-discordjs/commands/gif.js b/01-discordjs/commands/gif.js deleted file mode 100644 index d020363..0000000 --- a/01-discordjs/commands/gif.js +++ /dev/null @@ -1,48 +0,0 @@ -// Importing modules using ES6 syntax -import { SlashCommandBuilder, EmbedBuilder } from 'discord.js'; - -export const data = new SlashCommandBuilder() - .setName('gif') - .setDescription('Searches Tenor for gifs!') - .addStringOption((option) => - option.setName('keywords').setDescription('The keywords to search Tenor with') - ); - -// Execute function to interact with Tenor API and reply with a GIF -export async function execute(interaction) { - // Initially acknowledging the command interaction - // can use { ephemeral: true } for reply to be seen by user only - await interaction.deferReply(); - - // Default keyword set to 'kitten' if none provided - let defaultKeyword = 'kitten'; - const keywords = interaction.options.getString('keywords') ?? defaultKeyword; - - // URL constructed with the provided or default keyword - let url = `https://tenor.googleapis.com/v2/search?q=${keywords}&key=${process.env.TENORKEY}&client_key=a2z_discord_bot&contentfilter=high`; - - // Fetching data from Tenor API - let response = await fetch(url); - let json = await response.json(); - console.log(json); - console.log(json.results[0].media_formats); - - // Randomly select a GIF from the response - const index = Math.floor(Math.random() * json.results.length); - - // Creating an embed to display the GIF in the Discord message - const embed = new EmbedBuilder() - .setColor('#0099ff') - .setTitle(`GIF from Tenor: ${keywords}`) - .setURL(json.results[index].url) - .setImage(json.results[index].media_formats.gif.url) - .setFooter({ text: 'Powered by Tenor' }) - .setAuthor({ name: 'A2Z Bot' }) - .setThumbnail(json.results[index].media_formats.tinygif.url); // 5. Thumbnail - - // Following up with the selected GIF embedded in the message - await interaction.followUp({ - embeds: [embed], - content: 'GIF from Tenor: ' + keywords, - }); -} diff --git a/01-discordjs/commands/randomwalk.js b/01-discordjs/commands/randomwalk.js deleted file mode 100644 index 61cca0b..0000000 --- a/01-discordjs/commands/randomwalk.js +++ /dev/null @@ -1,52 +0,0 @@ -// Importing modules using ES6 syntax -import { SlashCommandBuilder, AttachmentBuilder } from 'discord.js'; -import { createCanvas } from 'canvas'; - -// Command Builder export -export const data = new SlashCommandBuilder() - .setName('randomwalk') - .setDescription('Generates a random walk image!'); - -// Execute function export -export async function execute(interaction) { - console.log('generating...'); - const buffer = generateImage(); - const attachment = new AttachmentBuilder(buffer, { name: 'randomwalk.png' }); - await interaction.reply({ content: 'Here is your random walk!', files: [attachment] }); -} - -// Generates random walk image and returns buffer -function generateImage() { - const width = 1280; - const height = 720; - const canvas = createCanvas(width, height); - const ctx = canvas.getContext('2d'); - - ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, width, height); - - let x = width / 2; - let y = height / 2; - const stepSize = 1; - for (let i = 0; i < 500000; i++) { - ctx.fillStyle = 'black'; - ctx.fillRect(x, y, stepSize, stepSize); - const r = Math.floor(Math.random() * 4); - switch (r) { - case 0: - x = x + stepSize; - break; - case 1: - x = x - stepSize; - break; - case 2: - y = y + stepSize; - break; - case 3: - y = y - stepSize; - break; - } - } - const buffer = canvas.toBuffer('image/png'); - return buffer; -} diff --git a/01-discordjs/commands/roshambo.js b/01-discordjs/commands/roshambo.js deleted file mode 100644 index f5e7cbc..0000000 --- a/01-discordjs/commands/roshambo.js +++ /dev/null @@ -1,104 +0,0 @@ -// Importing necessary classes and methods from the Discord.js library -import { - SlashCommandBuilder, - ButtonBuilder, - ButtonStyle, - ActionRowBuilder, - ComponentType, -} from 'discord.js'; - -// Define the slash command using SlashCommandBuilder -export const data = new SlashCommandBuilder() - .setName('roshambo') // Command name that users will type - .setDescription('Play a game of rock paper scissors!'); // Description of the command - -// Function to execute when the slash command is called -export async function execute(interaction) { - console.log('starting'); - - // Creating button components for the rock-paper-scissors game - const rockButton = new ButtonBuilder() - .setCustomId('rock') // Identifier for this button - .setStyle(ButtonStyle.Primary) // Button color/style - .setEmoji('πŸͺ¨'); // Emoji displayed on the button - - const paperButton = new ButtonBuilder() - .setCustomId('paper') - .setStyle(ButtonStyle.Primary) - .setEmoji('πŸ“„'); - - const scissorsButton = new ButtonBuilder() - .setCustomId('scissors') - .setStyle(ButtonStyle.Primary) - .setEmoji('βœ‚οΈ'); - - // Organizing buttons in a row using ActionRowBuilder - const row = new ActionRowBuilder().addComponents( - rockButton, - paperButton, - scissorsButton - ); - - // Sending the initial interaction message with attached buttons - await interaction.reply({ - content: 'Roshambo!', // Message content - components: [row], // Attaching the button row to the message - }); - - // Filter function to ensure only the user who initiated the interaction can respond - const filter = (i) => { - return i.user.id === interaction.user.id; - }; - - // Awaiting user's button interaction (waiting max 10 seconds) - const buttonInteraction = await interaction.channel - .awaitMessageComponent({ - filter, - componentType: ComponentType.Button, - time: 10000, // Timeout period in milliseconds - }) - .catch((err) => { - // Handling the scenario where user doesn’t respond in time - interaction.followUp('You took too long! Game over.'); - }); - if (!buttonInteraction) return; // Exit function if no valid interaction is collected - - // Game logic follows... - const userChoice = buttonInteraction.customId; - const botChoice = ['rock', 'paper', 'scissors'][Math.floor(Math.random() * 3)]; - await buttonInteraction.reply(`You chose ${userChoice} and I chose ${botChoice}!`); - - // Outcome responses... - if (userChoice === botChoice) { - return await buttonInteraction.followUp("It's a tie!"); - } - if ( - (userChoice === 'rock' && botChoice === 'scissors') || - (userChoice === 'paper' && botChoice === 'rock') || - (userChoice === 'scissors' && botChoice === 'paper') - ) { - return await buttonInteraction.followUp('You won!'); - } - return await buttonInteraction.followUp('I won!'); -} - -// Note: An alternative to using awaitMessageComponent is a MessageComponentCollector. -// The MessageComponentCollector allows the bot to collect multiple button interactions over a specified -// period of time or until certain conditions are met. This would be useful if you wanted to allow -// the user to play multiple rounds without sending a new command, for example. -// -// Example of creating a collector (not implemented in this function): -// const collector = interaction.channel.createMessageComponentCollector({ -// filter, -// componentType: ComponentType.Button, -// time: 30000, // Time in milliseconds collector will run for; here, 30 seconds -// }); -// -// Example of how the collector can be used: -// collector.on('collect', (buttonInteraction) => { -// // Logic to handle button interaction -// }); -// -// collector.on('end', (collected) => { -// // Logic for when the collector stops collecting interactions -// }); diff --git a/README.md b/README.md index e291b2f..2c1fdf7 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,34 @@ # Discord Bot Examples -This repository provides examples and a step-by-step guide on how to create a simple Discord bot using [discord.js](https://discord.js.org/#/). +This repository provides the source code used throughout the Discord bot tutorial series of [TheCodingTrain](https://www.youtube.com/@TheCodingTrain). Each folder corresponds to the final code showcased in that episode of the tutorial series. -## Steps to Create Your Bot! +## General steps to follow when setting up your bot -### 1. Set Up Your Project +### 1. Create a Discord application -Create a new Node.js project and install necessary dependencies. +- Navigate to the [Discord Developer Portal](https://discord.com/developers/applications/) and create a new application. +- Optionally, set the application name, description, and avatar. +- Note down the "Application ID" (also known as "Client ID"). -```sh -$ npm init -$ npm install discord.js dotenv -``` -Add a property `"type": "module"` in your `package.json` file in order to use ES6 module import syntax. - -### 2. Create a Discord Application - -- Navigate to the [Discord Developer Portal](https://discord.com/developers/applications/) and create a new application. -- Optionally, set the application name, description, and avatar. -- Note down the "Application ID" (also known as "Client ID"). +### 2. Create and configure your bot -### 3. Create and Configure Your Bot +- In the Discord Developer Portal, select "Bot" from the left navigation. +- Set a name and icon for your bot. +- Note down the "Bot Token" (keep this secret). -- In the Discord Developer Portal, select "Bot" from the left navigation. -- Set a name and icon for your bot. -- Note down the "Bot Token" (keep this secret). +### 3. Add bot to a server -### 4. Add Bot to a Server +- Go to your application page in the Discord developer portal. +- Navigate to "OAuth" -> "URL Generator". +- Check "application.commands" and "bot". +- Open the URL that populates at the bottom and authorize the bot to access your server. -- Go to your application page in the Discord developer portal. -- Navigate to "OAuth" -> "URL Generator". -- Check "application.commands" and "bot". -- Open the URL that populates at the bottom and authorize the bot to access your server. +### 4. Enable developer mode in Discord -### 5. Enable Developer Mode in Discord +- Enable "Developer Mode" under the "Advanced" settings tab on your Discord client. +- Right-click on the server icon, and select "Copy ID" to get the server ID. -- Enable "Developer Mode" under the "Advanced" settings tab on your Discord client. -- Right-click on the server icon, and select "Copy ID" to get the server ID. - -### 6. Configure Environment Variables +### 5. Configure environment variables Create a `.env` file in your project root and add your client ID, server ID, and bot token: @@ -48,99 +38,20 @@ SERVERID=1234 TOKEN=1234 ``` -These environment variables are used to keep sensitive data, like your bot token, out of your code. This is especially important if you're sharing your code with others or storing your code publicly on GitHub. (Notice how `.env` is included in `.gitignore`.) - -### 7. Create the bot code! - -Create `bot.js` (or `index.js`) and paste this code: - -```javascript -import { Client, Events, GatewayIntentBits } from 'discord.js'; -import { config } from 'dotenv'; - -config(); - -// 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, readyDiscord); - -// Login to Discord with your client's token -client.login(process.env.TOKEN); - -function readyDiscord() { - console.log('πŸ’–'); -} -``` - -Run to see if it works! (If you see the πŸ’– it's working!) - -```sh -$ node bot.js -``` - -## 8. Create a Command +> `⚠️` **Note**: Some of the examples here require additional values in the `.env` files to function. You can always find a `.env-example` alongside the files. This contains all the environmental variables that need to be configured! -Each command should be handled in a separate JS file, there are many ways you can manage this, but I suggest putting them in a folder called commands: - -```javascript -import { SlashCommandBuilder } from 'discord.js'; - -// Command Builder export -export const data = new SlashCommandBuilder() - .setName('choochoo') - .setDescription('Replies choo choo!'); - -// Execute function export -export async function execute(interaction) { - await interaction.reply('Choo choo!'); -} -``` - -## 9. Deploy the commands - -Create `deploy-commands.js` and copy the [example code](/01-discordjs/deploy-commands.js). Then run it! - -```sh -node deploy-commands.js -``` - -You only have to do this once. If you change the command (altering descriptions, changing options, etc.), then you do need to re-run `deploy-commands.js`. - -## 10. Add the code to handle the command - -You also need to handle the command in bot.js, add the equivalent code: - -```javascript -import * as choochoo from './commands/choochoo.js'; - -client.on(Events.InteractionCreate, handleInteraction); - -async function handleInteraction(interaction) { - if (!interaction.isCommand()) return; - if (interaction.commandName === 'choochoo') { - await choochoo.execute(interaction); - } -} -``` +These environment variables are used to keep sensitive data, like your bot token, out of your code. This is especially important if you're sharing your code with others or storing your code publicly on GitHub. (Notice how `.env` is included in `.gitignore`.) -Then run the bot again! +### 6. Deploy the code! -```sh -node bot.js -``` +Follow the `README.md` files inside if each episode to deploy and run the Discord bot! -## Recap of the code elements +## Additional resources -- `commands/choochoo.js`: Defines a simple slash command. -- `index.js`: Handles interactions with Discord and executes commands. -- `deploy-commands.js`: Script to register slash commands with Discord API. +- [Discord.js Guide](https://discordjs.guide/) +- [Discord.js Documentation](https://discord.js.org/#/docs/main/stable/general/welcome) +- [Discord Developer Portal](https://discord.com/developers/applications/) -## Additional Resources +## Get help! -- [Discord.js Guide](https://discordjs.guide/) -- [Discord.js Documentation](https://discord.js.org/#/docs/main/stable/general/welcome) -- [Discord Developer Portal](https://discord.com/developers/applications/) +Stuck on an issue that you can't figure out how to fix? Do you want to create a new feature but don't know how to tackle it? The amazing [Coding Train Discord community](https://discord.gg/codingtrain) is always prepared to help you with any issue you're having! From 5ce825023db5d911f3b3f129ddd24b6365704351 Mon Sep 17 00:00:00 2001 From: Supercrafter100 <58982133+supercrafter100@users.noreply.github.com> Date: Mon, 23 Oct 2023 21:37:13 +0200 Subject: [PATCH 2/3] Modify readme's to align with discussed points --- 01-discordjs/README.md | 126 +++++++++++++++++++++++++++++++++++++---- README.md | 48 +--------------- 2 files changed, 116 insertions(+), 58 deletions(-) diff --git a/01-discordjs/README.md b/01-discordjs/README.md index 99ca517..ee2da1b 100644 --- a/01-discordjs/README.md +++ b/01-discordjs/README.md @@ -1,20 +1,109 @@ # Episode 1 -## Steps to deploy your bot! +In this episode, we make a new Discord bot from scratch and create a simple slash command! -Make sure you first follow all the steps in the main README file of this repository before trying to deploy the bot. These include some steps on creating a Discord application in case you don't have that yet! +## Steps to Create Your Bot! -### 1. Set up your project +### 1. Set Up Your Project -Make sure you open a terminal inside this directory! Next, execute the following code to install all the required dependencies: +Create a new Node.js project and install necessary dependencies. ```sh -$ npm install +$ npm init +$ npm install discord.js dotenv ``` -### 2. Deploy the commands +Add a property `"type": "module"` in your `package.json` file in order to use ES6 module import syntax. -Deploy the slash commands so Discord knows about them and can show them to your Discord users! Use the following command to deploy the commands: +### 2. Create a Discord Application + +- Navigate to the [Discord Developer Portal](https://discord.com/developers/applications/) and create a new application. +- Optionally, set the application name, description, and avatar. +- Note down the "Application ID" (also known as "Client ID"). + +### 3. Create and Configure Your Bot + +- In the Discord Developer Portal, select "Bot" from the left navigation. +- Set a name and icon for your bot. +- Note down the "Bot Token" (keep this secret). + +### 4. Add Bot to a Server + +- Go to your application page in the Discord developer portal. +- Navigate to "OAuth" -> "URL Generator". +- Check "application.commands" and "bot". +- Open the URL that populates at the bottom and authorize the bot to access your server. + +### 5. Enable Developer Mode in Discord + +- Enable "Developer Mode" under the "Advanced" settings tab on your Discord client. +- Right-click on the server icon, and select "Copy ID" to get the server ID. + +### 6. Configure Environment Variables + +Create a `.env` file in your project root and add your client ID, server ID, and bot token: + +```plaintext +CLIENTID=1234 +SERVERID=1234 +TOKEN=1234 +``` + +These environment variables are used to keep sensitive data, like your bot token, out of your code. This is especially important if you're sharing your code with others or storing your code publicly on GitHub. (Notice how `.env` is included in `.gitignore`.) + +### 7. Create the bot code! + +Create `bot.js` (or `index.js`) and paste this code: + +```javascript +import { Client, Events, GatewayIntentBits } from 'discord.js'; +import { config } from 'dotenv'; + +config(); + +// 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, readyDiscord); + +// Login to Discord with your client's token +client.login(process.env.TOKEN); + +function readyDiscord() { + console.log('πŸ’–'); +} +``` + +Run to see if it works! (If you see the πŸ’– it's working!) + +```sh +$ node bot.js +``` + +## 8. Create a Command + +Each command should be handled in a separate JS file, there are many ways you can manage this, but I suggest putting them in a folder called commands: + +```javascript +import { SlashCommandBuilder } from 'discord.js'; + +// Command Builder export +export const data = new SlashCommandBuilder() + .setName('choochoo') + .setDescription('Replies choo choo!'); + +// Execute function export +export async function execute(interaction) { + await interaction.reply('Choo choo!'); +} +``` + +## 9. Deploy the commands + +Create `deploy-commands.js` and copy the [example code](/01-discordjs/deploy-commands.js). Then run it! ```sh node deploy-commands.js @@ -22,17 +111,30 @@ node deploy-commands.js You only have to do this once. If you change the command (altering descriptions, changing options, etc.), then you do need to re-run `deploy-commands.js`. -### 10. Start the bot +## 10. Add the code to handle the command + +You also need to handle the command in bot.js, add the equivalent code: + +```javascript +import * as choochoo from './commands/choochoo.js'; -Now start the bot using the following command: +client.on(Events.InteractionCreate, handleInteraction); + +async function handleInteraction(interaction) { + if (!interaction.isCommand()) return; + if (interaction.commandName === 'choochoo') { + await choochoo.execute(interaction); + } +} +``` + +Then run the bot again! ```sh node bot.js ``` -You should get a little message indicating the bot is ready! If you get an error, make sure you've entered the correct bot token in the `.env` file! - -### Recap of the code elements showcased in this episode +## Recap of the code elements - `commands/choochoo.js`: Defines a simple slash command. - `bot.js`: Handles interactions with Discord and executes commands. diff --git a/README.md b/README.md index 2c1fdf7..25b1951 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,6 @@ # Discord Bot Examples -This repository provides the source code used throughout the Discord bot tutorial series of [TheCodingTrain](https://www.youtube.com/@TheCodingTrain). Each folder corresponds to the final code showcased in that episode of the tutorial series. - -## General steps to follow when setting up your bot - -### 1. Create a Discord application - -- Navigate to the [Discord Developer Portal](https://discord.com/developers/applications/) and create a new application. -- Optionally, set the application name, description, and avatar. -- Note down the "Application ID" (also known as "Client ID"). - -### 2. Create and configure your bot - -- In the Discord Developer Portal, select "Bot" from the left navigation. -- Set a name and icon for your bot. -- Note down the "Bot Token" (keep this secret). - -### 3. Add bot to a server - -- Go to your application page in the Discord developer portal. -- Navigate to "OAuth" -> "URL Generator". -- Check "application.commands" and "bot". -- Open the URL that populates at the bottom and authorize the bot to access your server. - -### 4. Enable developer mode in Discord - -- Enable "Developer Mode" under the "Advanced" settings tab on your Discord client. -- Right-click on the server icon, and select "Copy ID" to get the server ID. - -### 5. Configure environment variables - -Create a `.env` file in your project root and add your client ID, server ID, and bot token: - -```plaintext -CLIENTID=1234 -SERVERID=1234 -TOKEN=1234 -``` - -> `⚠️` **Note**: Some of the examples here require additional values in the `.env` files to function. You can always find a `.env-example` alongside the files. This contains all the environmental variables that need to be configured! - -These environment variables are used to keep sensitive data, like your bot token, out of your code. This is especially important if you're sharing your code with others or storing your code publicly on GitHub. (Notice how `.env` is included in `.gitignore`.) - -### 6. Deploy the code! - -Follow the `README.md` files inside if each episode to deploy and run the Discord bot! +This repository provides the source code used throughout the Discord bot tutorial series of [TheCodingTrain](https://www.youtube.com/@TheCodingTrain). Each folder corresponds to the final code showcased in that episode of the tutorial series together with an explanation of what changes and additions were made during that episode. ## Additional resources @@ -54,4 +10,4 @@ Follow the `README.md` files inside if each episode to deploy and run the Discor ## Get help! -Stuck on an issue that you can't figure out how to fix? Do you want to create a new feature but don't know how to tackle it? The amazing [Coding Train Discord community](https://discord.gg/codingtrain) is always prepared to help you with any issue you're having! +Stuck on an issue that you can't figure out how to fix? Do you want to create a new feature but don't know how to tackle it? The amazing [Coding Train Discord community](https://discord.gg/codingtrain) is always prepared to help you with any issue or questions you're having! From 7cccf3f4262156255232c781e74d2eab02309735 Mon Sep 17 00:00:00 2001 From: Supercrafter100 <58982133+supercrafter100@users.noreply.github.com> Date: Mon, 23 Oct 2023 21:38:49 +0200 Subject: [PATCH 3/3] clarify that each episode builds ontop of the previous one --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 25b1951..79212fc 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ This repository provides the source code used throughout the Discord bot tutorial series of [TheCodingTrain](https://www.youtube.com/@TheCodingTrain). Each folder corresponds to the final code showcased in that episode of the tutorial series together with an explanation of what changes and additions were made during that episode. +Each episode builds ontop of the previous one. So if you've got questions on why some things are done the way they are in existing code, have a look at previous episodes! + ## Additional resources - [Discord.js Guide](https://discordjs.guide/)