levix-bot 4.7.0 → 4.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +21 -7
  2. package/SETUP.md +21 -2
  3. package/app.cjs +69 -23
  4. package/package.json +3 -2
  5. package/public/dashboard/assets/index-B1sOW2VX.js +561 -0
  6. package/public/dashboard/assets/index-CK8osB4o.css +2 -0
  7. package/public/dashboard/index.html +2 -2
  8. package/public/dashboard.css +50 -0
  9. package/public/dashboard.js +25 -2
  10. package/public/gateway-i18n.js +26 -0
  11. package/src/bootstrap/session-startup-policy.js +6 -6
  12. package/src/commands/group/antilink.cjs +82 -59
  13. package/src/commands/group/antispam.cjs +112 -0
  14. package/src/commands/group/clearwarns.cjs +6 -6
  15. package/src/commands/group/demote.cjs +11 -13
  16. package/src/commands/group/flagged.cjs +52 -0
  17. package/src/commands/group/kick.cjs +25 -15
  18. package/src/commands/group/media.cjs +65 -29
  19. package/src/commands/group/policy.cjs +215 -0
  20. package/src/commands/group/promote.cjs +11 -12
  21. package/src/commands/group/rules.cjs +9 -6
  22. package/src/commands/group/setwarn.cjs +17 -27
  23. package/src/commands/group/warn.cjs +13 -63
  24. package/src/commands/group.cjs +5 -2
  25. package/src/commands/md.cjs +44 -0
  26. package/src/commands/mod.cjs +101 -26
  27. package/src/commands/translate.cjs +585 -0
  28. package/src/config/ai-identity.cjs +53 -1
  29. package/src/config/ai-persona.md +32 -73
  30. package/src/config/defaults.cjs +3 -0
  31. package/src/config/secrets.cjs +71 -3
  32. package/src/config/settings.cjs +22 -1
  33. package/src/core/socket.js +27 -5
  34. package/src/db/db.cjs +66 -0
  35. package/src/db/store.cjs +264 -16
  36. package/src/diagnostics/crashReports.cjs +35 -9
  37. package/src/diagnostics/debugLog.cjs +405 -0
  38. package/src/handlers/command.handler.js +3 -1
  39. package/src/handlers/group.handler.js +32 -1
  40. package/src/handlers/message.handler.js +53 -17
  41. package/src/middleware/antispam.middleware.js +95 -48
  42. package/src/panel/feedback.cjs +32 -5
  43. package/src/panel/one-time-code.cjs +156 -0
  44. package/src/panel/password-reset.cjs +187 -91
  45. package/src/panel/recovery-email.cjs +333 -0
  46. package/src/routes/dashboard.api.esm.js +341 -29
  47. package/src/services/aiAgent.cjs +25 -3
  48. package/src/services/moderationPolicy.cjs +895 -0
  49. package/src/services/settingsTransfer.cjs +4 -2
  50. package/src/utils/linkedCreds.cjs +22 -0
  51. package/src/utils/logger.cjs +93 -34
  52. package/src/utils/markdownParser.cjs +208 -136
  53. package/src/utils/moderationAction.cjs +637 -0
  54. package/src/utils/moderationSummary.cjs +225 -0
  55. package/src/utils/permissions.cjs +70 -0
  56. package/src/utils/permissions.esm.js +48 -8
  57. package/src/utils/storage.cjs +8 -0
  58. package/src/utils/storage.esm.js +4 -0
  59. package/views/login.ejs +100 -28
  60. package/public/dashboard/assets/index-RnT7DAde.js +0 -540
  61. package/public/dashboard/assets/index-UcqCdCvG.css +0 -2
  62. package/src/commands/group/antiSpam.cjs +0 -97
@@ -0,0 +1,637 @@
1
+ // Shared group-moderation enforcement: identity-stable warnings, roster JID
2
+ // for kicks, FLAG records for admin review, bot-admin gating, and the
3
+ // bilingual "rule broken" notice.
4
+ //
5
+ // Warn is counted before delete/kick so a failed delete cannot skip the limit.
6
+
7
+ const {
8
+ getGroupSettings,
9
+ getUserWarnings,
10
+ saveUserWarnings,
11
+ clearUserWarnings,
12
+ upsertModerationFlag,
13
+ clearModerationFlag,
14
+ listModerationFlags,
15
+ getModerationFlag,
16
+ commitModerationDecision,
17
+ markModerationNotice,
18
+ markModerationKicked,
19
+ getPnForLid,
20
+ getLidForPn,
21
+ getLidsForPn,
22
+ } = require("./storage.cjs");
23
+ const normalizeJid = require("./normalizeJid.cjs");
24
+ const { isLidJid } = normalizeJid;
25
+ const {
26
+ getSenderCandidatesSync,
27
+ hasBotPrivilegesSync,
28
+ isAdminInGroupSync,
29
+ isBotAdminInGroupSync,
30
+ isOwnerJidSync,
31
+ primePermissions,
32
+ rosterJidForSync,
33
+ sameUserSync,
34
+ } = require("./permissions.cjs");
35
+ const { resolveGroupMetadata } = require("./groupMetadataCache.cjs");
36
+ const { unwrapMessage } = require("./messageContent.cjs");
37
+ const { mediaLabel } = require("./moderationSummary.cjs");
38
+ const { resolveModerationPolicy, effectivePoints } = require("../services/moderationPolicy.cjs");
39
+ const logger = require("./logger.cjs");
40
+ const { tr } = require("./i18n.cjs");
41
+
42
+ const MAX_POINTS_PER_MESSAGE = 50;
43
+ const RULE_FEATURE = {
44
+ forbidden: "forbidden",
45
+ link: "antilink",
46
+ media: "media",
47
+ spam: "antispam",
48
+ warn: "manual",
49
+ };
50
+ const ACTION_RANK = { DELETE: 1, WARN: 2, KICK: 3 };
51
+
52
+ function commandContextInfo(msg) {
53
+ const inner = unwrapMessage(msg?.message) || {};
54
+ return (
55
+ inner.extendedTextMessage?.contextInfo ||
56
+ inner.imageMessage?.contextInfo ||
57
+ inner.videoMessage?.contextInfo ||
58
+ inner.documentMessage?.contextInfo ||
59
+ inner.contextInfo ||
60
+ {}
61
+ );
62
+ }
63
+
64
+ function identityAliases(jid) {
65
+ const ids = [];
66
+ const add = (value) => {
67
+ const norm = normalizeJid(value);
68
+ if (norm && !ids.includes(norm)) ids.push(norm);
69
+ };
70
+ add(jid);
71
+ const norm = ids[0];
72
+ if (!norm) return ids;
73
+ const phones = [];
74
+ const addPhone = (value) => {
75
+ const phone = normalizeJid(value);
76
+ if (!phone || isLidJid(phone) || phones.includes(phone)) return;
77
+ phones.push(phone);
78
+ };
79
+ if (isLidJid(norm)) addPhone(getPnForLid(norm));
80
+ else addPhone(norm);
81
+ for (const phone of phones) {
82
+ add(phone);
83
+ add(getLidForPn(phone));
84
+ for (const lid of getLidsForPn(phone) || []) add(lid);
85
+ }
86
+ return ids;
87
+ }
88
+
89
+ function targetFromCommand(msg) {
90
+ const ctx = commandContextInfo(msg);
91
+ const mentioned = (ctx.mentionedJid || []).filter((jid) => typeof jid === "string" && jid);
92
+ if (mentioned.length) {
93
+ const jid = mentioned[0];
94
+ return { jid, candidates: identityAliases(jid) };
95
+ }
96
+ const quoted = [ctx.participant, ctx.participantAlt, ctx.participantPn].filter(
97
+ (jid) => typeof jid === "string" && jid,
98
+ );
99
+ if (ctx.quotedMessage || quoted.length) {
100
+ const jid = quoted[0];
101
+ if (!jid) return null;
102
+ const candidates = [];
103
+ for (const value of quoted) {
104
+ for (const alias of identityAliases(value)) {
105
+ if (!candidates.includes(alias)) candidates.push(alias);
106
+ }
107
+ }
108
+ return { jid, candidates };
109
+ }
110
+ return null;
111
+ }
112
+
113
+ function senderCandidates(msg, sock) {
114
+ return getSenderCandidatesSync(msg, sock);
115
+ }
116
+
117
+ function isProtectedMember(sock, groupMetadata, candidates) {
118
+ const botIds = [sock?.user?.id, sock?.user?.lid].filter(Boolean);
119
+ return (candidates || []).some(
120
+ (candidate) =>
121
+ isOwnerJidSync(candidate) ||
122
+ hasBotPrivilegesSync(candidate) ||
123
+ isAdminInGroupSync(groupMetadata, candidate) ||
124
+ botIds.some((botId) => sameUserSync(candidate, botId)),
125
+ );
126
+ }
127
+
128
+ function groupAdminJids(meta, sock) {
129
+ const botIds = [sock?.user?.id, sock?.user?.lid].filter(Boolean);
130
+ const jids = [];
131
+ for (const participant of meta?.participants || []) {
132
+ if (participant.admin !== "admin" && participant.admin !== "superadmin") continue;
133
+ if (!participant.id) continue;
134
+ if (botIds.some((botId) => sameUserSync(participant.id, botId))) continue;
135
+ if (!jids.includes(participant.id)) jids.push(participant.id);
136
+ }
137
+ return jids;
138
+ }
139
+
140
+ function ruleNotice({
141
+ rule,
142
+ detail,
143
+ mentionTag,
144
+ count,
145
+ limit,
146
+ announceKick,
147
+ announceFlag,
148
+ announceNeedAdmin,
149
+ adminTags,
150
+ }) {
151
+ const lines = [];
152
+ if (rule === "warn") {
153
+ lines.push(
154
+ tr(
155
+ `✅ ${mentionTag} has been warned.\n*Reason:* ${detail || ""}`,
156
+ `✅ تم توجيه تحذير إلى ${mentionTag}.\n*السبب:* ${detail || ""}`,
157
+ ),
158
+ );
159
+ } else {
160
+ lines.push(mentionTag);
161
+ if (rule === "link") {
162
+ lines.push(
163
+ tr("Links are not allowed in this group.", "الروابط غير مسموحة في هذه المجموعة."),
164
+ );
165
+ } else if (rule === "spam") {
166
+ lines.push(tr("Spam is not allowed in this group.", "الإزعاج غير مسموح في هذه المجموعة."));
167
+ } else if (rule === "media") {
168
+ const label = mediaLabel(detail);
169
+ lines.push(
170
+ tr(
171
+ `${label} are not allowed in this group.`,
172
+ `يُمنع إرسال ${label} في هذه المجموعة.`,
173
+ ),
174
+ );
175
+ } else if (rule === "forbidden") {
176
+ lines.push(
177
+ tr(
178
+ "Forbidden words are not allowed in this group.",
179
+ "الكلمات الممنوعة غير مسموحة في هذه المجموعة.",
180
+ ),
181
+ );
182
+ }
183
+ }
184
+ if (count && limit) {
185
+ lines.push(tr(`Warnings: ${count}/${limit}`, `الإنذارات: ${count}/${limit}`));
186
+ }
187
+ if (announceKick) {
188
+ lines.push(tr("The member will be removed.", "سيتم حذف العضو."));
189
+ }
190
+ if (announceNeedAdmin) {
191
+ lines.push(
192
+ tr(
193
+ "I am not a group admin, so an admin must act.",
194
+ "لست مشرفًا في المجموعة، لذلك يجب أن يتصرف أحد المشرفين.",
195
+ ),
196
+ );
197
+ }
198
+ if (announceFlag) {
199
+ lines.push(
200
+ tr(
201
+ "The member reached the warning limit. Admins have been notified.",
202
+ "بلغ العضو حد الإنذارات. تم إشعار المشرفين.",
203
+ ),
204
+ );
205
+ }
206
+ if (adminTags) lines.push(adminTags);
207
+ return lines.join("\n");
208
+ }
209
+
210
+ function systemActor(sock) {
211
+ return sock?.user?.id || sock?.user?.lid || "system";
212
+ }
213
+
214
+ function flagMemberForReview(groupId, userId, fields) {
215
+ const payload = {
216
+ warnCount: fields.warnCount,
217
+ lastRule: fields.lastRule,
218
+ reasons: fields.reasons,
219
+ flaggedAt: fields.flaggedAt || Date.now(),
220
+ };
221
+ if (fields.repeatPoints != null) payload.repeatPoints = fields.repeatPoints;
222
+ if ("lastNotifiedAt" in fields) payload.lastNotifiedAt = fields.lastNotifiedAt;
223
+ return upsertModerationFlag(groupId, userId, payload);
224
+ }
225
+
226
+ function clearMemberModeration(groupId, userId) {
227
+ clearUserWarnings(groupId, userId);
228
+ clearModerationFlag(groupId, userId);
229
+ }
230
+
231
+ function dismissMemberFlag(groupId, userId) {
232
+ clearModerationFlag(groupId, userId);
233
+ }
234
+
235
+ /**
236
+ * Remove a member on WhatsApp and drop their warnings + flag.
237
+ * Used by !kick and the panel.
238
+ */
239
+ async function kickGroupMember(sock, opts) {
240
+ await primePermissions();
241
+ const groupId = opts.groupId;
242
+ if (!groupId?.endsWith("@g.us")) return { kicked: false, error: "not-group" };
243
+ const meta = opts.groupMetadata || (await resolveGroupMetadata(sock, groupId));
244
+ const candidates = (opts.targetCandidates || []).filter(Boolean);
245
+ if (!candidates.length) return { kicked: false, error: "no-target" };
246
+ if (isProtectedMember(sock, meta, candidates)) return { kicked: false, error: "protected" };
247
+ if (!isBotAdminInGroupSync(meta, sock)) return { kicked: false, error: "bot-not-admin" };
248
+ const kickJid = rosterJidForSync(meta, candidates) || candidates[0];
249
+ const updated = await sock.groupParticipantsUpdate(groupId, [kickJid], "remove");
250
+ if (!removalSucceeded(updated)) return { kicked: false, error: "rejected", kickJid };
251
+ clearMemberModeration(groupId, candidates[0]);
252
+ logger.info({ group: groupId, user: kickJid }, "moderation kicked member");
253
+ return { kicked: true, kickJid };
254
+ }
255
+
256
+ function removalSucceeded(result) {
257
+ if (result == null) return true;
258
+ const items = Array.isArray(result) ? result : [result];
259
+ if (!items.length) return false;
260
+ return items.every((item) => item && typeof item === "object" && String(item.status) === "200");
261
+ }
262
+
263
+ function idleResult() {
264
+ return {
265
+ acted: false,
266
+ duplicate: false,
267
+ points: 0,
268
+ effective: 0,
269
+ decision: "none",
270
+ kicked: false,
271
+ flagged: false,
272
+ count: 0,
273
+ willKick: false,
274
+ };
275
+ }
276
+
277
+ function assignHitActions(hits, policy) {
278
+ return hits.map((hit) => {
279
+ const next = { ...hit };
280
+ if (!next.action) {
281
+ if (next.rule === "warn") next.action = "WARN";
282
+ else next.action = policy.features[RULE_FEATURE[next.rule]] || "WARN";
283
+ } else next.action = String(next.action).toUpperCase();
284
+ if (!next.reason) next.reason = next.detail || next.rule || "moderation";
285
+ return next;
286
+ });
287
+ }
288
+
289
+ function strongestHit(hits) {
290
+ let best = hits[0];
291
+ for (const hit of hits.slice(1)) {
292
+ if ((ACTION_RANK[hit.action] || 0) > (ACTION_RANK[best.action] || 0)) best = hit;
293
+ }
294
+ return best;
295
+ }
296
+
297
+ function pointsForHits(hits, policy) {
298
+ const primary = strongestHit(hits);
299
+ const counting = hits.filter((hit) => hit.action === "WARN" || hit.action === "KICK");
300
+ if (primary.action === "DELETE" || counting.length === 0) return { points: 0, primary };
301
+ if (policy.mode !== "severity") return { points: 1, primary };
302
+ const weights = counting.map((hit) => policy.weights[RULE_FEATURE[hit.rule]] || 1);
303
+ if (policy.hitMerge === "sum") {
304
+ return {
305
+ points: Math.min(MAX_POINTS_PER_MESSAGE, weights.reduce((total, weight) => total + weight, 0)),
306
+ primary,
307
+ };
308
+ }
309
+ return { points: Math.max(...weights), primary };
310
+ }
311
+
312
+ function decideOutcome({ policy, immediate, effective, flagWasOpen, repeatPoints }) {
313
+ if (immediate === "KICK") return "kick";
314
+ if (policy.mode !== "severity") {
315
+ if (effective >= policy.limit && policy.limitAction === "KICK") return "kick";
316
+ if (
317
+ flagWasOpen &&
318
+ policy.flag.whileFlagged === "escalate" &&
319
+ repeatPoints >= policy.flag.escalateAfter
320
+ ) {
321
+ return "kick";
322
+ }
323
+ if (effective >= policy.limit && policy.limitAction === "FLAG") return "flag";
324
+ return immediate === "DELETE" ? "delete" : "warn";
325
+ }
326
+ if (effective >= policy.kickAt) return "kick";
327
+ if (effective >= policy.flagAt) return "flag";
328
+ return immediate === "DELETE" ? "delete" : "warn";
329
+ }
330
+
331
+ async function performKick(sock, ctx) {
332
+ try {
333
+ const result = await kickGroupMember(sock, {
334
+ groupId: ctx.groupId,
335
+ groupMetadata: ctx.meta,
336
+ targetCandidates: ctx.candidates,
337
+ });
338
+ if (result.kicked) {
339
+ markModerationKicked(ctx.groupId, ctx.messageId);
340
+ return true;
341
+ }
342
+ logger.warn(
343
+ { group: ctx.groupId, user: ctx.mentionJid, rule: ctx.rule, error: result.error },
344
+ "moderation kick skipped",
345
+ );
346
+ flagMemberForReview(ctx.groupId, ctx.mentionJid, {
347
+ warnCount: ctx.effective,
348
+ lastRule: ctx.rule,
349
+ reasons: ctx.reasons,
350
+ repeatPoints: ctx.repeatPoints,
351
+ });
352
+ return false;
353
+ } catch (err) {
354
+ logger.error(
355
+ { err, group: ctx.groupId, user: ctx.mentionJid, rule: ctx.rule },
356
+ "moderation kick failed",
357
+ );
358
+ flagMemberForReview(ctx.groupId, ctx.mentionJid, {
359
+ warnCount: ctx.effective,
360
+ lastRule: ctx.rule,
361
+ reasons: ctx.reasons,
362
+ repeatPoints: ctx.repeatPoints,
363
+ });
364
+ try {
365
+ await sock.sendMessage(ctx.groupId, {
366
+ text: tr(
367
+ "I tried to remove the member, but I don't have enough permissions.",
368
+ "حاولت حذف العضو ولكني لا أملك صلاحية كافية لذلك.",
369
+ ),
370
+ });
371
+ } catch (noticeErr) {
372
+ logger.error({ err: noticeErr, group: ctx.groupId }, "moderation kick-failure notice failed");
373
+ }
374
+ return false;
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Apply every hit from one message in a single transaction.
380
+ * Returns { acted, duplicate, points, effective, decision, kicked, flagged }.
381
+ */
382
+ async function enforceHits(sock, opts) {
383
+ const msg = opts.msg;
384
+ const groupId = opts.groupId || msg?.key?.remoteJid;
385
+ if (!groupId?.endsWith("@g.us")) return idleResult();
386
+ const incoming = (opts.hits || []).filter(Boolean);
387
+ if (!incoming.length) return idleResult();
388
+
389
+ const meta = opts.groupMetadata || (await resolveGroupMetadata(sock, groupId));
390
+ const candidates = (opts.targetCandidates?.length
391
+ ? opts.targetCandidates
392
+ : senderCandidates(msg, sock)
393
+ ).filter(Boolean);
394
+ if (!candidates.length) return idleResult();
395
+ // Detectors skip the linked account. A manual warn is an admin action, so
396
+ // immunity is the target's (bot, owners, bot admins, group admins).
397
+ const manualWarn = incoming.every((hit) => hit.rule === "warn");
398
+ if ((!manualWarn && msg?.key?.fromMe) || isProtectedMember(sock, meta, candidates)) return idleResult();
399
+
400
+ const settings = getGroupSettings(groupId) || {};
401
+ const policy = resolveModerationPolicy(settings);
402
+ const hits = assignHitActions(incoming, policy);
403
+ const { points, primary } = pointsForHits(hits, policy);
404
+ const messageId = msg?.key?.id || null;
405
+ const now = Date.now();
406
+ const mentionJid = candidates[0];
407
+ const botAdmin = isBotAdminInGroupSync(meta, sock);
408
+ const actor = opts.actorJid || systemActor(sock);
409
+ const shouldDelete = hits.some(
410
+ (hit) => hit.rule === "link" || hit.rule === "media" || hit.rule === "forbidden",
411
+ );
412
+
413
+ const committed = commitModerationDecision(groupId, messageId, () => {
414
+ const existingEvents = getUserWarnings(groupId, mentionJid);
415
+ const flag = getModerationFlag(groupId, mentionJid);
416
+ const flagWasOpen = Boolean(flag);
417
+ let added = points;
418
+ if (flagWasOpen && policy.flag.whileFlagged === "hold" && primary.action !== "KICK") added = 0;
419
+ if (messageId && existingEvents.some((event) => event.messageId === messageId)) added = 0;
420
+
421
+ const events = existingEvents.slice();
422
+ if (added > 0) {
423
+ events.push({
424
+ messageId,
425
+ points: added,
426
+ rules: hits.map((hit) => hit.rule),
427
+ reason: primary.reason,
428
+ by: actor,
429
+ date: new Date(now).toISOString(),
430
+ });
431
+ saveUserWarnings(groupId, mentionJid, events);
432
+ }
433
+
434
+ let repeatPoints = flag?.repeat_points || 0;
435
+ if (
436
+ flagWasOpen &&
437
+ (policy.flag.whileFlagged === "record" || policy.flag.whileFlagged === "escalate")
438
+ ) {
439
+ repeatPoints += added;
440
+ }
441
+ const effective = effectivePoints(events, policy, now);
442
+ const decision = decideOutcome({
443
+ policy,
444
+ immediate: primary.action,
445
+ effective,
446
+ flagWasOpen,
447
+ repeatPoints,
448
+ });
449
+ const wantKick = decision === "kick";
450
+ const opening = !flagWasOpen && (decision === "flag" || (wantKick && !botAdmin));
451
+ if (opening) repeatPoints = 0;
452
+ const reasons = events.map((event) => event?.reason).filter(Boolean);
453
+ if (decision === "flag" || (wantKick && !botAdmin) || (flagWasOpen && !wantKick)) {
454
+ flagMemberForReview(groupId, mentionJid, {
455
+ warnCount: effective,
456
+ lastRule: primary.rule,
457
+ reasons,
458
+ repeatPoints,
459
+ flaggedAt: flag?.flagged_at || now,
460
+ });
461
+ }
462
+ const cooldownMs = (policy.flag.cooldownMinutes || 0) * 60 * 1000;
463
+ const lastNotified = flag?.last_notified_at || 0;
464
+ return {
465
+ outcome: decision,
466
+ points: added,
467
+ effective,
468
+ decision,
469
+ lastRule: primary.rule,
470
+ rule: primary.rule,
471
+ detail: primary.detail,
472
+ shouldDelete,
473
+ wantKick,
474
+ botAdmin,
475
+ hitLimit: policy.mode !== "severity" && effective >= policy.limit,
476
+ canFlagNotice:
477
+ policy.flag.notify === "group" && (cooldownMs === 0 || now - lastNotified >= cooldownMs),
478
+ mentionAdmins: policy.flag.mentionAdmins !== false,
479
+ mentionJid,
480
+ candidates,
481
+ reasons,
482
+ repeatPoints,
483
+ limit: policy.mode === "severity" ? policy.kickAt : policy.limit,
484
+ };
485
+ });
486
+
487
+ if (committed?.duplicate) {
488
+ let kicked = Boolean(committed.kicked);
489
+ if (!kicked && committed.outcome === "kick") {
490
+ const flag = getModerationFlag(groupId, mentionJid);
491
+ const events = getUserWarnings(groupId, mentionJid);
492
+ kicked = await performKick(sock, {
493
+ groupId,
494
+ meta,
495
+ candidates,
496
+ mentionJid,
497
+ rule: flag?.last_rule || "moderation",
498
+ messageId,
499
+ effective: flag?.warn_count || effectivePoints(events, policy, now),
500
+ reasons: events.map((event) => event?.reason).filter(Boolean),
501
+ repeatPoints: flag?.repeat_points || 0,
502
+ });
503
+ }
504
+ return {
505
+ acted: true,
506
+ duplicate: true,
507
+ points: 0,
508
+ effective: null,
509
+ decision: committed.outcome,
510
+ kicked,
511
+ flagged: !kicked && (committed.outcome === "flag" || committed.outcome === "kick"),
512
+ lastRule: null,
513
+ count: null,
514
+ willKick: committed.outcome === "kick",
515
+ };
516
+ }
517
+
518
+ if (committed.shouldDelete) {
519
+ if (!committed.botAdmin) {
520
+ logger.warn(
521
+ { group: groupId, rule: committed.rule },
522
+ "moderation delete skipped: bot is not a group admin",
523
+ );
524
+ } else {
525
+ try {
526
+ await sock.sendMessage(groupId, { delete: msg.key });
527
+ } catch (err) {
528
+ logger.error({ err, group: groupId, rule: committed.rule }, "moderation delete failed");
529
+ }
530
+ }
531
+ }
532
+
533
+ const converted = committed.wantKick && !committed.botAdmin;
534
+ const normalFlag = committed.decision === "flag";
535
+ const announceFlag =
536
+ committed.canFlagNotice && (normalFlag || (converted && committed.hitLimit));
537
+ const sendNeedAdmin = converted;
538
+ const sendRule =
539
+ committed.decision === "warn" ||
540
+ committed.decision === "delete" ||
541
+ (committed.wantKick && committed.botAdmin) ||
542
+ announceFlag ||
543
+ sendNeedAdmin;
544
+ if (sendRule) {
545
+ const mentionAdmins =
546
+ sendNeedAdmin || (announceFlag && committed.mentionAdmins && !sendNeedAdmin) || (announceFlag && committed.mentionAdmins);
547
+ const adminJids = mentionAdmins ? groupAdminJids(meta, sock) : [];
548
+ const text = ruleNotice({
549
+ rule: committed.rule,
550
+ detail: committed.detail,
551
+ mentionTag: `@${String(committed.mentionJid).split("@")[0]}`,
552
+ count: committed.decision === "delete" ? 0 : committed.effective,
553
+ limit: committed.limit,
554
+ announceKick: committed.wantKick && committed.botAdmin,
555
+ announceFlag,
556
+ announceNeedAdmin: sendNeedAdmin,
557
+ adminTags: adminJids.map((jid) => `@${String(jid).split("@")[0]}`).join(" "),
558
+ });
559
+ try {
560
+ await sock.sendMessage(groupId, { text, mentions: [committed.mentionJid, ...adminJids] });
561
+ markModerationNotice(groupId, messageId, committed.mentionJid, {
562
+ flagNotice: announceFlag,
563
+ at: now,
564
+ });
565
+ } catch (err) {
566
+ logger.error({ err, group: groupId, rule: committed.rule }, "moderation notice failed");
567
+ }
568
+ }
569
+ if (converted) {
570
+ logger.warn(
571
+ { group: groupId, user: mentionJid, rule: committed.rule },
572
+ "moderation kick skipped: bot is not a group admin; flagged instead",
573
+ );
574
+ }
575
+
576
+ let kicked = false;
577
+ if (committed.wantKick && committed.botAdmin) {
578
+ kicked = await performKick(sock, {
579
+ groupId,
580
+ meta,
581
+ candidates,
582
+ mentionJid,
583
+ rule: committed.rule,
584
+ messageId,
585
+ effective: committed.effective,
586
+ reasons: committed.reasons,
587
+ repeatPoints: committed.repeatPoints,
588
+ });
589
+ }
590
+
591
+ return {
592
+ acted: true,
593
+ duplicate: false,
594
+ points: committed.points,
595
+ effective: committed.effective,
596
+ decision: committed.decision,
597
+ kicked,
598
+ flagged: (committed.decision === "flag" || converted || (committed.wantKick && !kicked)) && !kicked,
599
+ lastRule: committed.lastRule,
600
+ count: committed.effective,
601
+ willKick: committed.wantKick,
602
+ };
603
+ }
604
+
605
+ async function enforceGroupRule(sock, opts) {
606
+ const action = opts.kickImmediately ? "KICK" : opts.recordWarning === false ? "DELETE" : "WARN";
607
+ return enforceHits(sock, {
608
+ msg: opts.msg,
609
+ groupId: opts.groupId,
610
+ groupMetadata: opts.groupMetadata,
611
+ hits: [
612
+ {
613
+ rule: opts.rule || "moderation",
614
+ action,
615
+ reason: opts.warningReason || opts.detail || opts.rule || "moderation",
616
+ detail: opts.detail,
617
+ },
618
+ ],
619
+ actorJid: opts.actorJid,
620
+ targetCandidates: opts.targetCandidates,
621
+ });
622
+ }
623
+
624
+ module.exports = {
625
+ enforceHits,
626
+ enforceGroupRule,
627
+ kickGroupMember,
628
+ clearMemberModeration,
629
+ dismissMemberFlag,
630
+ flagMemberForReview,
631
+ listModerationFlags,
632
+ targetFromCommand,
633
+ senderCandidates,
634
+ isProtectedMember,
635
+ commandContextInfo,
636
+ groupAdminJids,
637
+ };