Message Create Event
The messageCreate
event in Discord.js is triggered whenever a new message is created in a text channel. This event is useful for building features such as command handling, automated responses, and various message-based interactions. By listening to this event, you can execute specific code whenever a user sends a message in your Discord server.
Project Structure
Now inside the client
folder add our messageCreate.ts
file
- ready.ts
- messageCreate.ts
Create messageCreate.ts
Now, we have to write the logic for our message create
event. This file will contain the logic that should be executed whenever a new message is created. Typically, you will check if the message starts with a command prefix and then execute the corresponding command.
This message event handler comes with developer commands, bot permissions, and user permission checks built-in.
import { EmbedBuilder, Message, PermissionsBitField } from 'discord.js'
import { ExtendedClient } from '../../interfaces/ExtendedClient'
import { logger } from '../../utils/logger'
import { BOT } from '../../configs/metadata'
import config from '../../configs/botConfig'
import { COLORS } from '../../constants/botConst'
import { EMOJIS } from '../../constants/botConst'
export const eventHandlerMessage = (client: ExtendedClient) => {
client.on('messageCreate', async (message: Message) => {
if (message.author.bot || !message.guild) return
if (!message.content.startsWith(BOT.PREFIX)) return
const args = message.content.slice(BOT.PREFIX.length).trim().split(/ +/g)
const commandName = args.shift()?.toLowerCase()
if (!commandName) return
const command = client.messageCommands.get(commandName)
if (!command) {
logger.warn(`Command not found: ${commandName}`)
const unknownCommand = new EmbedBuilder()
.setColor(COLORS.red)
.setTitle(`You cannot use this command!`)
.setDescription(`${EMOJIS.failed} There is no command like this`)
.setTimestamp()
return message.reply({ embeds: [unknownCommand] })
}
if (
command.userPermissions &&
!message.member?.permissions.has(PermissionsBitField.resolve(command.userPermissions))
) {
const userPermEmbed = new EmbedBuilder()
.setColor(COLORS.yellow)
.setTitle(`You cannot use this command!`)
.setDescription(
`${EMOJIS.caution} You don't have the required permissions to use this command`,
)
.setTimestamp()
return message.reply({ embeds: [userPermEmbed] })
}
if (!client.user) {
logger.error('Client user is null')
return
}
if (
command.botPermissions &&
!message.guild.members.cache
.get(client.user.id)
?.permissions.has(PermissionsBitField.resolve(command.botPermissions))
) {
const botPermEmbed = new EmbedBuilder()
.setColor(COLORS.yellow)
.setTitle(`I cannot use this command!`)
.setDescription(
`${EMOJIS.caution} I don't have the required permissions to run this command`,
)
.setTimestamp()
return message.reply({ embeds: [botPermEmbed] })
}
if (command.devOnly && !config.DEVELOPER_IDS.includes(message.author.id)) {
const devOnlyEmbed = new EmbedBuilder()
.setColor(COLORS.yellow)
.setTitle(`You cannot use this command!`)
.setDescription(`${EMOJIS.caution} This command is only for developers`)
.setTimestamp()
return message.reply({ embeds: [devOnlyEmbed] })
}
try {
await command.executeMessage(message, args, client)
} catch (error) {
logger.error(`Error executing command: ${commandName}` + error)
console.log(error)
const eE = new EmbedBuilder()
.setColor(COLORS.red)
.setTitle('Opps!')
.setDescription(`${EMOJIS.failed} There was an error trying to run that command!`)
await message.reply({ embeds: [eE] })
}
})
}
At this moment, you may get some errors because we haven't created our logger
function yet! For
the logger
function, please refer to the logging guide.
Alright we have done, now let's go further!