Compare commits

..

1 commit

Author SHA1 Message Date
Slincnik
4593f2804d
Merge c7ebdb78d4 into 12054c35c5 2024-12-21 11:25:43 +05:00
4 changed files with 101 additions and 156 deletions

View file

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

View file

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

View file

@ -1,59 +1,66 @@
import UserModel from "../models/UserModel"; /**
import useClient from "../utils/use-client"; *
* @param {import("../base/Client")} client
const checkReminds = async () => { */
const client = useClient(); async function checkReminds(client) {
client.usersData.find({ reminds: { $gt: [] } }).then(users => {
client.adapter.find(UserModel, { reminds: { $gt: [] } }).then(users => {
for (const user of users) { for (const user of users) {
if (!client.users.cache.has(user.id)) client.users.fetch(user.id); if (!client.users.cache.has(user.id)) client.users.fetch(user.id);
client.cacheReminds.set(user.id, user); client.databaseCache.usersReminds.set(user.id, user);
} }
}); });
client.cacheReminds.forEach(async user => { client.databaseCache.usersReminds.forEach(async user => {
const cachedUser = client.users.cache.get(user.id); const cachedUser = client.users.cache.get(user.id);
if (!cachedUser) return; if (cachedUser) {
const dateNow = Math.floor(Date.now() / 1000),
reminds = user.reminds,
mustSent = reminds.filter(r => r.sendAt < dateNow);
const reminds = user.reminds, if (mustSent.length > 0) {
mustSent = reminds.filter(r => r.sendAt < Math.floor(Date.now() / 1000)); 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,
},
],
});
if (!mustSent.length) return; cachedUser.send({
embeds: [embed],
});
});
mustSent.forEach(r => { user.reminds = user.reminds.filter(r => r.sendAt >= dateNow);
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,
},
],
});
cachedUser.send({ embeds: [embed] }).then(() => { await user.save();
client.adapter.updateOne(UserModel, { id: user.id }, { $pull: { reminds: { _id: r._id } } });
});
});
if (!user.reminds.length) client.cacheReminds.delete(user.id); if (user.reminds.length === 0) client.databaseCache.usersReminds.delete(user.id);
}
}
}); });
}; }
export const init = async () => { export async function init(client) {
setInterval(async () => { setInterval(async () => {
await checkReminds(); await checkReminds(client);
}, 1000); }, 1000);
}; }
export async function run(client) {
await checkReminds(client);
}

View file

@ -7,9 +7,6 @@ import logger from "../helpers/logger.js";
import ConfigService from "../services/config/index.js"; import ConfigService from "../services/config/index.js";
import InternationalizationService from "../services/languages/index.js"; import InternationalizationService from "../services/languages/index.js";
import { SUPER_CONTEXT } from "../constants/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 { export class ExtendedClient extends Client {
/** /**
@ -24,7 +21,6 @@ export class ExtendedClient extends Client {
this.configService = new ConfigService(); this.configService = new ConfigService();
this.adapter = new MongooseAdapter(this.configService.get("mongoDB")); this.adapter = new MongooseAdapter(this.configService.get("mongoDB"));
this.i18n = new InternationalizationService(this); this.i18n = new InternationalizationService(this);
this.cacheReminds = new Map();
new Player(this); new Player(this);
SUPER_CONTEXT.enterWith(this); SUPER_CONTEXT.enterWith(this);
@ -41,60 +37,4 @@ export class ExtendedClient extends Client {
logger.error(error); 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;
}
} }