From 4c8c06824564be339520ffe3f66be0a2fe8b10cf Mon Sep 17 00:00:00 2001
From: Slincnik <pattyshow21@mail.ru>
Date: Tue, 14 Jan 2025 22:20:22 +0300
Subject: [PATCH] fix: many times sending reminds

---
 src/helpers/tasks/checkReminds.ts | 58 +++++++++++++++++--------------
 1 file changed, 31 insertions(+), 27 deletions(-)

diff --git a/src/helpers/tasks/checkReminds.ts b/src/helpers/tasks/checkReminds.ts
index a59fed36..073da450 100644
--- a/src/helpers/tasks/checkReminds.ts
+++ b/src/helpers/tasks/checkReminds.ts
@@ -8,16 +8,18 @@ export const data: CronTaskData = {
 	task: 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);
+		const users = await client.adapter.find(UserModel, { reminds: { $gt: [] } });
 
-				client.cacheReminds.set(user.id, {
-					id: user.id,
-					reminds: user.reminds,
-				});
+		for (const user of users) {
+			if (!client.users.cache.has(user.id)) {
+				client.users.fetch(user.id);
 			}
-		});
+
+			client.cacheReminds.set(user.id, {
+				id: user.id,
+				reminds: user.reminds,
+			});
+		}
 
 		client.cacheReminds.forEach(async ({ id, reminds }) => {
 			const cachedUser = client.users.cache.get(id);
@@ -28,7 +30,7 @@ export const data: CronTaskData = {
 
 			if (!mustSent.length) return;
 
-			mustSent.forEach(r => {
+			mustSent.forEach(async r => {
 				const embed = createEmbed({
 					author: {
 						name: client.translate("general/remindme:EMBED_TITLE"),
@@ -51,28 +53,30 @@ export const data: CronTaskData = {
 					],
 				});
 
-				cachedUser
-					.send({
-						embeds: [embed],
-					})
-					.then(() => {
-						client.adapter.updateOne(
-							UserModel,
-							{ id },
-							{
-								$pull: {
-									reminds: {
-										sendAt: r.sendAt,
-									},
-								},
+				await cachedUser.send({
+					embeds: [embed],
+				});
+
+				await client.adapter.updateOne(
+					UserModel,
+					{ id },
+					{
+						$pull: {
+							reminds: {
+								sendAt: r.sendAt,
 							},
-						);
-					});
+						},
+					},
+				);
 			});
 
-			reminds = reminds.filter(r => r.sendAt >= Math.floor(Date.now() / 1000));
+			const updatedReminds = reminds.filter(r => r.sendAt >= Math.floor(Date.now() / 1000));
 
-			if (!reminds.length) client.cacheReminds.delete(id);
+			if (!updatedReminds.length) {
+				client.cacheReminds.delete(id);
+			} else {
+				client.cacheReminds.set(id, { id, reminds: updatedReminds });
+			}
 		});
 	},
 	schedule: "* * * * * *",