- Question
Currently, I am developing a Discord bot to track messages using typescript and discord.js. I have included my code below. The issue I am facing is that the data is not being saved correctly. Each time a user sends messages, their message count is stored. However, if another user sends messages in the same channel, the database replaces the previous user's count with 0
.
- Code Snippet
// user-Schema.ts
import type { SapphireClient } from '@sapphire/framework';
import type { ModelStatic, Model } from 'sequelize';
import Sequelize from 'sequelize';
interface UserAttributes {
guild: string;
user: string;
msgs: number;
}
interface UserInstance extends Model<UserAttributes, UserAttributes>, UserAttributes {}
export class UserModel {
client: SapphireClient;
raw!: ModelStatic<UserInstance>;
constructor(client: SapphireClient) {
this.client = client;
}
async init() {
const db = this.client.sql.define<UserInstance>('electra.users', {
guild: {
type: Sequelize.STRING,
primaryKey: true,
unique: true
},
user: {
type: Sequelize.STRING,
primaryKey: true
},
msgs: {
type: Sequelize.INTEGER
}
});
this.raw = db;
await this.raw.sync();
this.client.logger.info(`Synced UserModel`);
}
}
// messageCreate.ts
const data = await this.container.client.userDB.raw.findOne({
where: {
guild: msg.guildId,
user: msg.author.id
}
});
const msgs = data === null ? 0 : data.msgs;
await this.container.client.userDB.raw.upsert({
guild: msg.guildId as string,
user: msg.author.id,
msgs: msgs + 1
});
// index.ts
import { UserModel } from './models/user-Schema';
const sequelize = new sql.Sequelize(process.env.DB_NAME!, process.env.DB_USER!, process.env.DB_PASS!, {
logging: false,
dialect: 'mysql'
});
client.sql = sequelize;
client.userDB = new UserModel(client);
// ready.ts
await this.container.client.userDB.init()
- Additional Information
I am utilizing @sapphire/framework as the framework for my bot. Any assistance or guidance would be greatly appreciated, and I am willing to provide more details upon request.
Thank you.