Creating your first component

What is a component?

A component is basically a command, but for message components. This makes it easier to handle buttons/context menus.

WARNING

Only use this when you want to have something like a button roles, giveaway system, ...etc but definitely don't use it when you only want it to be valid for a certain period of time, for the user. Then you can just use collectorsopen in new window

Creating a component

Remember the first command you created? We are going to modify its run function a little, and let it send an awesome button along with the message.

// Create a new action row with a button
const row = new ActionRowBuilder().addComponents([
	new ButtonBuilder()
		.setCustomId(customId('hello', ctx.userId))
		.setLabel('Click me!')
		.setStyle('SUCCESS')
	])

// Reply with the button
return ctx.reply({ content: `Hello ${ctx.user.username}!`, components: [row] });
1
2
3
4
5
6
7
8
9
10

Make sure to add the import statements for ActionRowBuilder, ButtonBuilder and CustomId at the top of the file.

const { ActionRowBuilder, ButtonBuilder } = require('discord.js');
const { customId } = require('gcommands');

// Other code
1
2
3
4

Great! When you use the command again you should see an awesome new button.

GCommands used /hello
Guide Bot Bot 10/02/2022
Hello S222em!

Now open or create the components folder and create a new file in it.

const { Component, ComponentType } = require('gcommands');

// Create a new component with the name "hello", this name is the first argument of CustomId: CustomId('hello')
new Component({
	name: 'hello',
	// Set the type of the component
	type: [ ComponentType.BUTTON ],
	// The function thats called when the button is pressed
	run: (ctx) => {
		return ctx.reply(`Hello again ${ctx.user.username}!`);
	}
});
1
2
3
4
5
6
7
8
9
10
11
12
const { Component, ComponentType } = require('gcommands');

// Create a new component with the name "hello", this name is the first argument of CustomId: CustomId('hello')
new class extends Component {
	constructor() {
		super({
			name: 'hello',
			// Set the type of the component
			type: [ ComponentType.BUTTON ],
		});
	}

	// The function thats called when the button is pressed
	run(ctx) {
		return ctx.reply(`Hello again ${ctx.user.username}!`);
	}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

After clicking on the button you will get a reply like this

Guide Bot Bot 10/02/2022
Hello again S222em!