我遇到了一个无法解决的问题。我目前正在使用 Sequelize 在discord.js 中开发一个机器人,并且我正在遵循discord.js.org 指南(因为我是v14 的新手)。不管怎样,我想要一个数据库,其中包含每个公会的每个用户的条目,现在我正在做:
现在问题来了。在命令中,我定义了模型,然后用它来创建一个条目,使用
model.create()
然而,当我运行它时,它说 model.create() isn't a function.
这是代码,你看一下。
命令代码:
const { SlashCommandBuilder } = require('discord.js');
const Users = require('../../models/user.js')
module.exports = {
data: new SlashCommandBuilder()
.setName('syncuserdata')
.setDescription('Syncs the member data with the db'),
async execute(interaction) {
const guild = interaction.guild
guild.members.cache.forEach(async (member) => {
if (member.user.bot) return
const memberId = member.id
try {
console.log(Users)
const userEntry = await Users.create({
user_id: memberId,
guild_id: member.guild.id
})
console.log(`[INFO] New user entry created for ${memberId}.`)
} catch (error) {
if (error.name === 'SequelizeUniqueConstraintError') {
const userEntryFetch = await Users.findOne({ where: { user_id: memberId } })
if (!userEntryFetch) console.error("[ERR] A user entry exists but could not be found.")
}
console.error(`[ERR] An error occured while creating a userEntry for ${memberId}: ${error}`)
interaction.channel.send(`Something went wrong while trying to sync for <@${memberId}>!`)
}
});
interaction.reply({
content: 'User data sync log:',
ephemeral: false,
})
},
};
数据库同步文件:
const Sequelize = require('sequelize');
const dbUserData = require('./events/dbUserData.js');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
storage: 'database.sqlite',
});
const User = require('./models/user.js')(sequelize, Sequelize.DataTypes);
const force = process.argv.includes('--force') || process.argv.includes('-f');
sequelize.sync({ force }).then(async () => {
console.log('[INFO] Database synced');
sequelize.close();
}).catch(console.error);
整个index.js:
// File handler init
const fs = require('node:fs');
// Path handler init
const path = require('node:path');
// Discord.js init
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
// Sequelize init
const Sequelize = require('sequelize')
// dotenv start and config
require('dotenv').config()
// Config file init
const { clientId, guildId, testPhase } = require('./config.json');
// Init both command deployments
require('./guilddeploycmd.js')
require('./globaldeploycmd.js')
const Users = require('./models/user.js')
// Create a new client instance
const client = new Client({ intents: 131071 });
const sequelize = new Sequelize('database', 'user', 'password', {
host: 'localhost',
dialect: 'sqlite',
logging: false,
// SQLite only
storage: 'database.sqlite',
});
// **Command collector**
client.commands = new Collection();
// Construct path into commands folder
const foldersPath = path.join(__dirname, 'commands');
// Gets all command subfolders
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
// ** END **
// When the client is ready, run this code (only once).
client.once(Events.ClientReady, readyClient => {
console.log(`[INFO] Logged in as ${readyClient.user.tag}`);
});
// Event handler
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// Log in to Discord with your client's token
client.login(process.env.TOKEN);
如果有人能帮助我,我将非常感激。预先感谢!
好吧,检查之后,似乎我必须先创建一个 Sequelize 客户端,并使用该客户端定义模型才能使用它。问题已解决!