Retrieving the Channel of the Message

Sometimes it's useful to retrieve the channel in which the message was sent.

For demonstrating how you can retrieve the channel from a Discord.js command we will code the ClearChannelCommand that will delete messages from the channel the message was sent.

Writing the ClearChannelCommand#

path/to/your/app/src/Commands/ClearChannelCommand.ts
import { BaseCommand, Channel, ChannelContract, Command } from "discapp";
@Command()
export class ClearChannelCommand extends BaseCommand {
@Channel()
public channel: ChannelContract;
public async execute() {
const allMessages = await this.channel.messages.fetch({
limit: 100,
});
let deletedMessages = 0;
await Promise.all(
allMessages.map(async (message) => {
if (message.deletable) {
++deletedMessages;
await message.delete();
}
})
);
return `Finished cleaning all the messages (${deletedMessages})`;
}
}

The ClearChannelCommand will try to delete all the latest 100 message (in parallel).

Testing the ClearChannelCommand#

You can test the command by sending:

!clear-channel

This should delete by arround 100 messages from the channel you send this command.