Compare commits

...

4 commits

Author SHA1 Message Date
Slincnik
2fd25f074d
Merge b45f3dcc35 into 12054c35c5 2024-12-25 19:13:40 +03:00
Slincnik
b45f3dcc35
feat: rewritten two helpers, birthdays and checkreminds 2024-12-25 19:13:34 +03:00
Slincnik
823aea886f
feat: added data from database 2024-12-25 19:11:49 +03:00
Slincnik
c2d1c85696
fix: fixing error when import module 2024-12-21 10:24:25 +03:00
4 changed files with 155 additions and 100 deletions

View file

@ -1,4 +1,4 @@
import ICacheAdapter from "./ICacheAdapter";
import ICacheAdapter from "./ICacheAdapter.js";
export default class MapCache extends ICacheAdapter {
constructor() {

View file

@ -1,69 +1,71 @@
import { CronJob } from "cron";
import useClient from "../utils/use-client.js";
import UserModel from "../models/UserModel.js";
import { createEmbed } from "../utils/create-embed.js";
import logger from "./logger.js";
import { getNoun } from "./functions.js";
/**
*
* @param {import("../base/Client")} client
*/
async function checkBirthdays(client) {
for (const guild of client.guilds.cache.values()) {
const checkBirthdays = async () => {
const client = useClient();
const guilds = client.guilds.cache.values();
const users = await client.adapter.find(UserModel, { birthdate: { $gt: 1 } });
const currentData = new Date();
const currentYear = currentData.getFullYear();
const currentMonth = currentData.getMonth();
const currentDate = currentData.getDate();
for (const guild of guilds) {
try {
const guildData = await client.getGuildData(guild.id);
const channel = guildData.plugins.birthdays ? await client.channels.fetch(guildData.plugins.birthdays) : null;
const data = await client.getGuildData(guild.id);
const channel = data.plugins.birthdays ? await client.channels.fetch(data.plugins.birthdays) : null;
if (channel) {
const date = new Date();
const currentDay = date.getDate();
const currentMonth = date.getMonth() + 1;
const currentYear = date.getFullYear();
if (!channel) return;
const users = await client.usersData.find({ birthdate: { $gt: 1 } });
const userIDs = users.filter(u => guild.members.cache.has(u.id)).map(u => u.id);
for (const user of users) {
if (!guild.members.cache.has(user.id)) continue;
await Promise.all(
userIDs.map(async userID => {
const user = users.find(u => u.id === userID);
const userData = new Date(user.birthdate).getFullYear() <= 1970 ? new Date(user.birthdate * 1000) : new Date(user.birthdate);
const userYear = userData.getFullYear();
const userMonth = userData.getMonth();
const userDate = userData.getDate();
const userDate = new Date(user.birthdate).getFullYear() <= 1970 ? new Date(user.birthdate * 1000) : new Date(user.birthdate);
const day = userDate.getDate();
const month = userDate.getMonth() + 1;
const year = userDate.getFullYear();
const age = currentYear - year;
const age = currentYear - userYear;
if (currentMonth === month && currentDay === day) {
const embed = client.embed({
author: client.user.getUsername(),
if (userDate === currentDate && userMonth === currentMonth) {
const embed = createEmbed({
author: client.user.username,
fields: [
{
name: client.translate("economy/birthdate:HAPPY_BIRTHDAY", null, guildData.language),
value: client.translate(
"economy/birthdate:HAPPY_BIRTHDAY_MESSAGE",
{
user: user.id,
age: `**${age}** ${client.functions.getNoun(
age,
client.translate("misc:NOUNS:AGE:1", null, guildData.language),
client.translate("misc:NOUNS:AGE:2", null, guildData.language),
client.translate("misc:NOUNS:AGE:5", null, guildData.language),
)}`,
},
guildData.language,
),
name: client.translate("economy/birthdate:HAPPY_BIRTHDAY", {
lng: data.language,
}),
value: client.translate("economy/birthdate:HAPPY_BIRTHDAY_MESSAGE", {
lng: data.language,
user: user.id,
age: `**${age}** ${getNoun(age, [
client.translate("misc:NOUNS:AGE:1", null, data.language),
client.translate("misc:NOUNS:AGE:2", null, data.language),
client.translate("misc:NOUNS:AGE:5", null, data.language),
])}`,
}),
},
],
});
await channel.send({ embeds: [embed] }).then(m => m.react("🎉"));
await channel.send({ embeds: [embed] }).then(m => m.react(" "));
}
}
}
} catch (e) {
if (e.code === 10003) console.log(`No channel found for ${guild.name}`);
else console.error(`Error processing birthdays for guild "${guild.name}":`, e);
}),
);
} catch (error) {
logger.error(error);
}
}
}
};
export async function init(client) {
new CronJob("0 5 * * *", checkBirthdays(client), null, true, "Europe/Moscow");
}
export async function run(client) {
await checkBirthdays(client);
export async function init() {
new CronJob("0 5 * * *", checkBirthdays(), null, true, "Europe/Moscow");
}

View file

@ -1,66 +1,59 @@
/**
*
* @param {import("../base/Client")} client
*/
async function checkReminds(client) {
client.usersData.find({ reminds: { $gt: [] } }).then(users => {
import UserModel from "../models/UserModel";
import useClient from "../utils/use-client";
const checkReminds = async () => {
const client = useClient();
client.adapter.find(UserModel, { reminds: { $gt: [] } }).then(users => {
for (const user of users) {
if (!client.users.cache.has(user.id)) client.users.fetch(user.id);
client.databaseCache.usersReminds.set(user.id, user);
client.cacheReminds.set(user.id, user);
}
});
client.databaseCache.usersReminds.forEach(async user => {
client.cacheReminds.forEach(async user => {
const cachedUser = client.users.cache.get(user.id);
if (cachedUser) {
const dateNow = Math.floor(Date.now() / 1000),
reminds = user.reminds,
mustSent = reminds.filter(r => r.sendAt < dateNow);
if (!cachedUser) return;
if (mustSent.length > 0) {
mustSent.forEach(r => {
const embed = client.embed({
author: client.translate("general/remindme:EMBED_TITLE"),
fields: [
{
name: client.translate("general/remindme:EMBED_CREATED"),
value: `<t:${r.createdAt}:f>`,
inline: true,
},
{
name: client.translate("general/remindme:EMBED_TIME"),
value: `<t:${r.sendAt}:f>`,
inline: true,
},
{
name: client.translate("common:MESSAGE"),
value: r.message,
},
],
});
const reminds = user.reminds,
mustSent = reminds.filter(r => r.sendAt < Math.floor(Date.now() / 1000));
cachedUser.send({
embeds: [embed],
});
});
if (!mustSent.length) return;
user.reminds = user.reminds.filter(r => r.sendAt >= dateNow);
mustSent.forEach(r => {
const embed = client.embed({
author: client.translate("general/remindme:EMBED_TITLE"),
fields: [
{
name: client.translate("general/remindme:EMBED_CREATED"),
value: `<t:${r.createdAt}:f>`,
inline: true,
},
{
name: client.translate("general/remindme:EMBED_TIME"),
value: `<t:${r.sendAt}:f>`,
inline: true,
},
{
name: client.translate("common:MESSAGE"),
value: r.message,
},
],
});
await user.save();
cachedUser.send({ embeds: [embed] }).then(() => {
client.adapter.updateOne(UserModel, { id: user.id }, { $pull: { reminds: { _id: r._id } } });
});
});
if (user.reminds.length === 0) client.databaseCache.usersReminds.delete(user.id);
}
}
if (!user.reminds.length) client.cacheReminds.delete(user.id);
});
}
};
export async function init(client) {
export const init = async () => {
setInterval(async () => {
await checkReminds(client);
await checkReminds();
}, 1000);
}
export async function run(client) {
await checkReminds(client);
}
};

View file

@ -7,6 +7,9 @@ import logger from "../helpers/logger.js";
import ConfigService from "../services/config/index.js";
import InternationalizationService from "../services/languages/index.js";
import { SUPER_CONTEXT } from "../constants/index.js";
import GuildModel from "../models/GuildModel.js";
import UserModel from "../models/UserModel.js";
import MemberModel from "../models/MemberModel.js";
export class ExtendedClient extends Client {
/**
@ -21,6 +24,7 @@ export class ExtendedClient extends Client {
this.configService = new ConfigService();
this.adapter = new MongooseAdapter(this.configService.get("mongoDB"));
this.i18n = new InternationalizationService(this);
this.cacheReminds = new Map();
new Player(this);
SUPER_CONTEXT.enterWith(this);
@ -37,4 +41,60 @@ export class ExtendedClient extends Client {
logger.error(error);
}
}
/**
* Retrieves a guild data object from the database.
* @param {string} guildId - The ID of the guild to find or create.
* @returns {Promise<GuildModel>} The guild data object, either retrieved from the database or newly created.
*/
async getGuildData(guildId) {
let guildData = await this.adapter.findOne(GuildModel, { id: guildId });
if (!guildData) {
guildData = new GuildModel({ id: guildId });
await guildData.save();
}
return guildData;
}
/**
* Returns a User data from the database.
* @param {string} userID - The ID of the user to find or create.
* @returns {Promise<UserModel>} The user data object, either retrieved from the database or newly created.
*/
async getUserData(userID) {
let userData = await this.adapter.findOne(UserModel, { id: userID });
if (!userData) {
userData = new UserModel({ id: userID });
await userData.save();
}
return userData;
}
/**
* Returns a Member data from the database.
* @param {string} memberId - The ID of the member to find or create.
* @param {string} guildId - The ID of the guild the member belongs to.
* @returns {Promise<MemberModel>} The member data object, either retrieved from the database or newly created.
*/
async getMemberData(memberId, guildId) {
let memberData = await this.adapter.findOne(MemberModel, { guildID: guildId, id: memberId });
if (!memberData) {
memberData = new MemberModel({ id: memberId, guildID: guildId });
await memberData.save();
const guildData = await this.getGuildData(guildId);
if (guildData) {
guildData.members.push(memberData._id);
await guildData.save();
}
}
return memberData;
}
}