Getting Started
Learn how to write a Discord bot using Cord.js.
In Development
Cord.js is currently highly in development. A lot of stuff is missing and the documentation is incomplete.
A lot of APIs are subject to change, and the docs might not be up-to date.
Any bugs that you may find, please report them in the issue tracker.
Creating the bot
We first need to create the bot itself on the Discord Developer Portal.
Setting up the project
First, we need to initialize our project.
$ mkdir my-cool-bot && cd my-cool-bot # create a new folder and cd into it
$ npm init -y # create a package.json
Add the following to your package.json
to support ES Modules (import
/export
)
"type": "module"
Now, we'll need to install the required packages.
$ npm install @cordjs/bot @cordjs/gateway
The @cordjs/bot
package will manage our bot, middleware and plugins.
The @cordjs/gateway
package is what's known as a plugin, it will
handle connecting to the Discord gateway and
allow us to listen to events such as messageCreate
.
Coding the bot
Let's get coding!
Instantiating the bot instance
Create a file called index.js
with the following code:
import Cord from '@cordjs/bot'
import Gateway from '@cordjs/gateway'
const bot = Cord([
Gateway({
token: '<YOUR_TOKEN_HERE>',
}),
])
This code will create a Cord.js Bot with the Gateway
plugin.
Note
The token should be kept secret.
It is recommended to store your token in a .env
file and add it to your .gitignore
.
And use the dotenv
package to load your .env file.
Info
You might've noticed that we didn't pass any intents. This is because Cord.js will automatically detect the required intents for you.
Adding middleware
Now we need to use middleware so we can listen to new messages that are sent.
bot.gateway.messageCreate((context) => {
const { message } = context.data
if (message.content === 'hello cord.js') {
message.reply('Hello World! :wave:')
}
})
The context
parameter has information about the event.
The context.data
property has the data of the event,
such as the message.
It's an object containing the parameters from Discord.js, so we can
use destructuring to get the message.
Check the Discord.js documentation for a list of events and the parameters that are passed to them.
Starting the bot
We will need to start the bot in order for it to come online.
bot.start()
Running the bot
Lets run the bot!
$ node . # runs the index.js file
Add the bot to a server and say hello cord.js
.
If everything went well, it should respond with Hello World! 👋
.