Phantomstar
DIAdiscord.js - Imagine an app
•Created by Phantomstar on 2/2/2025 in #djs-questions
How to properly pass Sequelize table into command handler?
I am sure this is very straightforward and I am just missing the obvious, but I am using the discord.js walkthrough https://discordjs.guide/sequelize/#adding-a-tag to setup a keyword system using Sequelize. I have also configured the event handler and command handler setups as recommended previously in the guide, so all my events/commands are in unique files. The guide shows how to add sequelize data when done all directly in your index.js file, but if I am trying to make it a separate command how do I properly require the sequelize table I defined as "Keywords" in my "ready.js" event handler file when setting up the add command as a separate "keyadd.js" command file?
Any help greatly appreciated! Here is my current command file to add the keyword:
const { SlashCommandBuilder, MessageFlags } = require('discord.js');
const { modRoleID } = require('../../config.json');
const { Keywords } = require('../../index');
module.exports = {
data: new SlashCommandBuilder()
.setName('keyadd')
.setDescription('Adds a new trigger word to storage.')
.addStringOption(option =>
option
.setName('keyword')
.setDescription('The trigger word to add.')
.setRequired(true)
)
.addStringOption(option =>
option
.setName('response')
.setDescription('The response for this keyword.')
.setRequired(true)
),
async execute(interaction) {
// Check if the member has the required mod role (or higher)
const modRole = interaction.guild.roles.cache.get(modRoleID);
if (!modRole) {
return await interaction.reply({ content: 'Moderator role not found in this server.', flags: MessageFlags.Ephemeral });
}
if (interaction.member.roles.highest.position < modRole.position) {
return await interaction.reply({ content: 'You do not have permission to use this command.', flags: MessageFlags.Ephemeral });
}
const keyword = interaction.options.getString('keyword');
const response = interaction.options.getString('response');
const msgTime = new Date();
try {
const key = await Keywords.create({
name: keyword,
last: msgTime,
response: response
});
await interaction.reply(
Keyword `${key.name}` added at `${key.last}`.);
} catch (e) {
if (e.name === 'SequelizeUniqueConstraintError') {
return await interaction.reply({ content: 'That keyword already exists.', flags: MessageFlags.Ephemeral });
}
return await interaction.reply({ content:
Something went wrong with adding the keyword: ${e}, flags: MessageFlags.Ephemeral });
}
},
};
5 replies