Sure! Below is an example of a simple Discord bot using discord.js v14 that responds to a !ping command with a message. Make sure you have v14 and the necessary dependencies installed.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
If you haven't done so yet, create a new directory for your bot and initialize a new Node.js project:
mkdir discord-bot
cd discord-bot
npm init -y
Then install discord.js:
npm install discord.js
Step 2: Create the bot script.
Create a file called index.js (or any name you prefer), and add the following code:
const { Client, GatewayIntentBits } = require('discord.js');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent] });
// When the client is ready, run this code (fires only once)
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// Listen for messages
client.on('messageCreate', (message) => {
// Ignore messages from the bot itself
if (message.author.bot) return;
// Check if the message content is "!ping"
if (message.content === '!ping') {
message.channel.send('Pong!');
}
});
// Log in to Discord with your client's token
client.login('YOUR_BOT_TOKEN');
Step 3: Set up your bot on Discord.
Create a new bot: Go to the Discord Developer Portal, create a new application, and then create a bot within that application.
Get the bot token: Copy the bot token from the bot settings, as you'll need it to connect the code with Discord.
Invite the bot to your server: You can generate an invite link in the OAuth2 section of your application settings. Make sure you give it appropriate permissions.
Step 4: Replace YOUR_BOT_TOKEN.
Replace 'YOUR_BOT_TOKEN' in the code with your actual bot token.
Step 5: Run your bot.
Now run your bot using Node.js:
node index.js
You should see Logged in as [Your Bot's Name]! in your console, indicating that your bot is running and connected to Discord.
Step 6: Test your bot.
Go to the Discord server where you invited your bot, and type !ping in any text channel. Your bot should reply with Pong!.
That's it! You have a simple Discord bot that responds to a ping command using discord.js v14.