Certainly! Below is a simple example of a Discord bot using Discord.js v14 that responds to a command with . Make sure you've installed Discord.js v14 and that you have your bot token handy.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
First, ensure you have a Node.js environment set up. If you haven’t already, create a new directory for your bot, and initialize a new Node.js project:
mkdir my-discord-bot
cd my-discord-bot
npm init -y
2. Install Discord.js
You can install Discord.js v14 with the following command:
npm install discord.js
3. Create the bot file
Create a new file named bot.js (or any name you prefer) in your project directory:
touch bot.js
4. Add the bot code
Open bot.js in your text editor and add the following code:
const { Client, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json'); // Make sure to create and fill this config file with your bot token
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent],
});
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', message => {
if (message.content === '!ping') {
message.channel.send('Pong!');
}
});
// Login to Discord with your app's token
client.login(token);
5. Create a config file
Create a config.json file in your project folder to securely store your bot's token:
touch config.json
Add your bot's token to config.json like this:
{
"token": "YOUR_BOT_TOKEN"
}
Replace YOUR_BOT_TOKEN with the actual token from your Discord Developer Portal.
6. Run your bot
Now you can run your bot using Node.js:
node bot.js
If everything is set up correctly, your bot should log in and respond to !ping with Pong! when you send that message in a server where your bot is present.
Additional Notes
Ensure your bot has permission to read messages and send messages in the server.
If you don't see your bot online, double-check your token and ensure the bot is invited to your server with the appropriate permissions.
For more functionality, consider implementing command handling, error handling, and other features as your bot grows!
Feel free to extend this code to add more commands or functionality as needed!