koishi-plugin-aakook 0.1.0 → 0.3.0
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.
- package/CHANGELOG.md +57 -24
- package/LICENSE +21 -21
- package/README.md +259 -198
- package/lib/card.d.ts +3 -0
- package/lib/card.js +28 -0
- package/lib/commands.js +3 -1
- package/lib/config.d.ts +19 -0
- package/lib/config.js +79 -3
- package/lib/corp.d.ts +102 -0
- package/lib/corp.js +90 -0
- package/lib/guard.d.ts +70 -0
- package/lib/guard.js +916 -12
- package/lib/index.js +4 -4
- package/lib/kook.d.ts +88 -1
- package/lib/kook.js +104 -2
- package/lib/link.d.ts +19 -1
- package/lib/link.js +85 -18
- package/lib/policy.d.ts +11 -0
- package/lib/policy.js +24 -4
- package/lib/store.d.ts +5 -0
- package/lib/store.js +8 -1
- package/lib/types.d.ts +50 -1
- package/package.json +62 -62
package/lib/guard.js
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
// ops reports and alerts. Rules live in policy.ts (pure); this file gathers the facts, calls policy.planBatch and
|
|
4
4
|
// carries out the plan. Everything that must survive a reload is in the database (see store.ts).
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.Guard = void 0;
|
|
6
|
+
exports.Guard = exports.emptyStats = void 0;
|
|
7
7
|
const aa_1 = require("./aa");
|
|
8
8
|
const config_1 = require("./config");
|
|
9
9
|
const kook_1 = require("./kook");
|
|
10
|
+
const card_1 = require("./card");
|
|
11
|
+
const corp_1 = require("./corp");
|
|
10
12
|
const link_1 = require("./link");
|
|
11
13
|
const notifier_1 = require("./notifier");
|
|
12
14
|
const policy_1 = require("./policy");
|
|
@@ -27,8 +29,32 @@ const NAME_FRESH_MS = 10 * MIN;
|
|
|
27
29
|
const REPORT_PROBLEM_LINES = 15;
|
|
28
30
|
const SAVE_EVERY = 10;
|
|
29
31
|
const NOTE_KEEP_MS = 30 * DAY;
|
|
32
|
+
/** Corp roles: at most this many new roles per run; the rest wait for the next one. */
|
|
33
|
+
const CORP_CREATES_PER_RUN = 10;
|
|
34
|
+
/** KOOK allows 100 roles per server: from this many on no corp role is made any more. */
|
|
35
|
+
const CORP_ROLE_STOP_AT = 95;
|
|
36
|
+
/** The "name card format changed?" check needs at least this many qualified people in one patrol, else it is just noise. */
|
|
37
|
+
const CORP_FORMAT_MIN_ALLOW = 10;
|
|
38
|
+
/** Corp roles made by events / ticks (not a patrol): at most this many in 24 hours; the rest wait for a patrol. */
|
|
39
|
+
const CORP_EVENT_CREATES_PER_DAY = 10;
|
|
40
|
+
/** Corp channel groups (军团分组): at most this many new groups per patrol; the rest wait for the next one. */
|
|
41
|
+
const CORP_GROUPS_PER_RUN = 3;
|
|
42
|
+
/** A half-made group is finished over at most this many later patrols, then it is left alone and ops are told. */
|
|
43
|
+
const CORP_GROUP_REPAIRS = 3;
|
|
44
|
+
/** KOOK permission bit 11: see the text / voice channels. */
|
|
45
|
+
const CHANNEL_VIEW = 2048;
|
|
46
|
+
/**
|
|
47
|
+
* KOOK permission bits that manage something (admin, server, roles, channels, invite, kick, ban, messages, nicknames, ...).
|
|
48
|
+
* A corp role holding any of them is never given out or taken back by the plugin.
|
|
49
|
+
*/
|
|
50
|
+
const CORP_MANAGE_BITS = [1, 2, 4, 16, 32, 64, 128, 256, 1024, 8192, 65536, 16777216, 33554432, 67108864];
|
|
51
|
+
const corpRolePrivileged = (role) => role.isAdmin || CORP_MANAGE_BITS.some((bit) => Math.floor(role.permissions / bit) % 2 === 1);
|
|
30
52
|
const PING_TEXT = '机器人没法私聊你。请在服务器任意频道发送「绑定」拿验证码,再用你自己的 QQ 在联盟 QQ 群里发出;限期内没有完成会被移出服务器。发送「状态」查看详情。';
|
|
31
|
-
const emptyStats = () => ({
|
|
53
|
+
const emptyStats = () => ({
|
|
54
|
+
grants: 0, revokes: 0, nicknames: 0, kicks: 0, reminders: 0, corpGrants: 0, corpRevokes: 0, corpCreates: 0, corpGroups: 0, corpDeferred: new Set(), corpSkip: new Set(),
|
|
55
|
+
problems: [], notes: [], alerts: [], aborted: false,
|
|
56
|
+
});
|
|
57
|
+
exports.emptyStats = emptyStats;
|
|
32
58
|
const unknownResult = (reason) => ({ decision: 'unknown', reason, card: null });
|
|
33
59
|
function toResult(verdict) {
|
|
34
60
|
if (verdict.decision === 'allow' || verdict.decision === 'deny') {
|
|
@@ -87,6 +113,7 @@ class Guard {
|
|
|
87
113
|
roleCache = null;
|
|
88
114
|
failures = new kook_1.FailureLog();
|
|
89
115
|
failuresSnapshot = '';
|
|
116
|
+
corpGroupReset = false;
|
|
90
117
|
notesSeen = null;
|
|
91
118
|
master = null;
|
|
92
119
|
notesDirty = false;
|
|
@@ -101,6 +128,14 @@ class Guard {
|
|
|
101
128
|
deferred = new Map();
|
|
102
129
|
names = new Map();
|
|
103
130
|
lastPatrolText = '';
|
|
131
|
+
/** Corp tickers whose role is being made right now (one creation per ticker at a time). */
|
|
132
|
+
corpCreating = new Map();
|
|
133
|
+
/** Serialises changes of the stored corp mapping. */
|
|
134
|
+
corpMapChain = Promise.resolve();
|
|
135
|
+
/** Corp roles are made / claimed one after the other (the role count and the 95 limit stay right). */
|
|
136
|
+
corpMakeChain = Promise.resolve();
|
|
137
|
+
/** When roles were made by a non-patrol path (last 24 hours). */
|
|
138
|
+
corpEventCreates = [];
|
|
104
139
|
constructor(ctx, config, options = {}) {
|
|
105
140
|
this.ctx = ctx;
|
|
106
141
|
this.config = config;
|
|
@@ -447,7 +482,7 @@ class Guard {
|
|
|
447
482
|
}
|
|
448
483
|
/** Judge these people and carry out what policy says. Never throws for a normal failure. */
|
|
449
484
|
async run(source, targets, options = {}) {
|
|
450
|
-
const none = { ran: false, aaFailed: false, result: null, stats: emptyStats(), people: 0 };
|
|
485
|
+
const none = { ran: false, aaFailed: false, result: null, stats: (0, exports.emptyStats)(), people: 0 };
|
|
451
486
|
await this.ready;
|
|
452
487
|
const blocked = this.blockedReason();
|
|
453
488
|
if (blocked) {
|
|
@@ -496,7 +531,7 @@ class Guard {
|
|
|
496
531
|
const { store, config } = this;
|
|
497
532
|
const guildId = config.guildId;
|
|
498
533
|
const now = this.now();
|
|
499
|
-
const none = { ran: false, aaFailed: false, result: null, stats: emptyStats(), people: 0 };
|
|
534
|
+
const none = { ran: false, aaFailed: false, result: null, stats: (0, exports.emptyStats)(), people: 0 };
|
|
500
535
|
if (this.stopped())
|
|
501
536
|
return none;
|
|
502
537
|
const policyConfig = (0, config_1.toPolicyConfig)(config);
|
|
@@ -557,7 +592,9 @@ class Guard {
|
|
|
557
592
|
hold: hold ?? null, activeSince: activeSince ?? null, enforceSince: enforceSince ?? null, resumedAt: resumedAt ?? null, guildId,
|
|
558
593
|
},
|
|
559
594
|
});
|
|
560
|
-
const stats = await this.execute(result, {
|
|
595
|
+
const stats = await this.execute(result, {
|
|
596
|
+
source, now, members: listing.members, inputs, links: current, hold: hold ?? null, memberCount: options.memberCount ?? storedCount ?? null,
|
|
597
|
+
});
|
|
561
598
|
return { ran: true, aaFailed: judgement.memberFailed, result, stats, people: result.counts.people };
|
|
562
599
|
}
|
|
563
600
|
async noteMode(now) {
|
|
@@ -665,7 +702,7 @@ class Guard {
|
|
|
665
702
|
const guildId = config.guildId;
|
|
666
703
|
const { now } = c;
|
|
667
704
|
const mode = config.mode;
|
|
668
|
-
const stats = emptyStats();
|
|
705
|
+
const stats = (0, exports.emptyStats)();
|
|
669
706
|
if (this.stopped())
|
|
670
707
|
return stats;
|
|
671
708
|
// alerts first: they are about the decision, not about the writes
|
|
@@ -691,6 +728,7 @@ class Guard {
|
|
|
691
728
|
}
|
|
692
729
|
const api = this.kookApi();
|
|
693
730
|
const canWrite = !!api && (mode === 'sync' || mode === 'enforce');
|
|
731
|
+
const corp = await this.prepareCorp(result, c, stats, canWrite);
|
|
694
732
|
const toSave = new Map();
|
|
695
733
|
const unsaved = new Set();
|
|
696
734
|
const pings = new Map();
|
|
@@ -739,6 +777,12 @@ class Guard {
|
|
|
739
777
|
stats.revokes += plan.revoke.length;
|
|
740
778
|
if (plan.nickname !== null)
|
|
741
779
|
stats.nicknames++;
|
|
780
|
+
const wouldCorp = corp?.actions.get(plan.kookId);
|
|
781
|
+
if (wouldCorp) {
|
|
782
|
+
if (wouldCorp.grant)
|
|
783
|
+
stats.corpGrants++;
|
|
784
|
+
stats.corpRevokes += wouldCorp.revoke.length;
|
|
785
|
+
}
|
|
742
786
|
await flush();
|
|
743
787
|
continue;
|
|
744
788
|
}
|
|
@@ -779,6 +823,9 @@ class Guard {
|
|
|
779
823
|
if (ok)
|
|
780
824
|
stats.nicknames++;
|
|
781
825
|
}
|
|
826
|
+
const corpAction = corp?.actions.get(plan.kookId);
|
|
827
|
+
if (corp && corpAction)
|
|
828
|
+
await this.applyCorp(corpAction, plan, tag, stats, corp);
|
|
782
829
|
if (plan.countdown === 'started')
|
|
783
830
|
await store.audit('countdown-start', plan.kookId, qq, `${record.deadlineWhy},到期 ${record.deadline ? (0, util_1.formatBeijing)(record.deadline) : ''}`, 'bot');
|
|
784
831
|
else if (plan.countdown === 'cleared')
|
|
@@ -834,6 +881,11 @@ class Guard {
|
|
|
834
881
|
}
|
|
835
882
|
}
|
|
836
883
|
}
|
|
884
|
+
if (corp && !this.stopped() && !stats.aborted)
|
|
885
|
+
await this.prepareCorpChannels(result, c, corp, stats);
|
|
886
|
+
if (stats.corpDeferred.size) {
|
|
887
|
+
stats.problems.push(`还有 ${stats.corpDeferred.size} 个军团身份组留到下一轮再建(每轮最多新建 ${CORP_CREATES_PER_RUN} 个):${[...stats.corpDeferred].map((t) => `[${t}]`).join('、')}`);
|
|
888
|
+
}
|
|
837
889
|
await this.saveFailures();
|
|
838
890
|
await this.saveNotes();
|
|
839
891
|
// outside a patrol only new write failures are pushed; everything else is in the next patrol summary
|
|
@@ -890,15 +942,18 @@ class Guard {
|
|
|
890
942
|
stats.problems.push(`${tag}:踢人前确认失败,这次不踢(${(0, util_1.errorText)(error)})`);
|
|
891
943
|
return false;
|
|
892
944
|
}
|
|
893
|
-
if (!view)
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
if (view.isMaster || view.isAdmin || view.isBot || whitelisted) {
|
|
897
|
-
this.logger.warn('%s:踢人前确认发现是受保护的人,不踢', tag);
|
|
945
|
+
if (!view) {
|
|
946
|
+
// getMember also returns null when KOOK sends no roles for the person: either way nobody is kicked on a guess
|
|
947
|
+
this.logger.info('%s:踢人前读不到成员或身份组(已离开,或 KOOK 没给身份组),不踢', tag);
|
|
898
948
|
return false;
|
|
899
949
|
}
|
|
900
950
|
// the link is read once more: someone who linked (or changed QQ) after the judgement is not kicked on old facts
|
|
901
951
|
const nowLink = await this.store.linkByKook(plan.kookId);
|
|
952
|
+
const hit = (0, policy_1.whitelistHit)((0, config_1.toPolicyConfig)(this.config), plan.kookId, view.roles, nowLink?.qq ?? null);
|
|
953
|
+
if (view.isMaster || view.isAdmin || view.isBot || hit) {
|
|
954
|
+
this.logger.warn('%s:踢人前确认发现是受保护的人%s,不踢', tag, hit ? `(白名单:${hit.kind === 'kook' ? 'KOOK ID' : hit.kind === 'role' ? '身份组' : 'QQ'})` : '');
|
|
955
|
+
return false;
|
|
956
|
+
}
|
|
902
957
|
if ((nowLink?.qq ?? '') !== qq) {
|
|
903
958
|
this.logger.info('%s:踢人前发现关联变了,不踢,留给下一轮', tag);
|
|
904
959
|
return false;
|
|
@@ -910,6 +965,747 @@ class Guard {
|
|
|
910
965
|
await this.store.audit(record.releasedKick ? 'kick-released' : 'kick', plan.kookId, qq, `到期未通过(${record.deadlineWhy},${(0, texts_1.reasonShort)(record.reason || 'NOT_LINKED')})`, 'bot');
|
|
911
966
|
return ok;
|
|
912
967
|
}
|
|
968
|
+
// ---------------------------------------------------------------- corp roles (军团身份组)
|
|
969
|
+
async readCorpMap() {
|
|
970
|
+
const stored = (await this.store.getKv(store_1.kvKeys.corpRoles(this.config.guildId))) ?? {};
|
|
971
|
+
const map = {};
|
|
972
|
+
for (const [ticker, id] of Object.entries(stored)) {
|
|
973
|
+
const roleId = (0, util_1.normalizeKookId)(id);
|
|
974
|
+
if (ticker && roleId)
|
|
975
|
+
map[ticker] = roleId;
|
|
976
|
+
}
|
|
977
|
+
return map;
|
|
978
|
+
}
|
|
979
|
+
/** Change the stored mapping one change at a time (read, change, write), so two tickers never overwrite each other. */
|
|
980
|
+
updateCorpMap(change) {
|
|
981
|
+
const result = this.corpMapChain.then(async () => {
|
|
982
|
+
const map = await this.readCorpMap();
|
|
983
|
+
change(map);
|
|
984
|
+
await this.store.setKv(store_1.kvKeys.corpRoles(this.config.guildId), map);
|
|
985
|
+
return map;
|
|
986
|
+
});
|
|
987
|
+
this.corpMapChain = result.catch(() => undefined);
|
|
988
|
+
return result;
|
|
989
|
+
}
|
|
990
|
+
/** Role ids the plugin manages in other ways (never claimed as a corp role). */
|
|
991
|
+
otherManagedRoleIds() {
|
|
992
|
+
const policy = (0, config_1.toPolicyConfig)(this.config);
|
|
993
|
+
return new Set([policy.memberRoleId, ...policy.roleMap.map((e) => e.roleId), ...policy.whitelistRoles, '0']);
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Decide the corp role work of one `execute` call: read the mapping, drop mapped roles that are gone (patrol only: the
|
|
997
|
+
* role list is read again to be sure, and a big "everything vanished" is not believed), leave out mapped roles that
|
|
998
|
+
* became unsafe, work out per person what to give / take back, and stop everything (alert) when the AA name card
|
|
999
|
+
* format looks changed or too many corp roles would be taken back at once. Null = corp roles are off or could not be prepared.
|
|
1000
|
+
* In report mode nothing is written; the counts and the lines about roles that would be made / claimed go into `stats`.
|
|
1001
|
+
*/
|
|
1002
|
+
async prepareCorp(result, c, stats, canWrite) {
|
|
1003
|
+
const { config } = this;
|
|
1004
|
+
if (!config.corpRoles)
|
|
1005
|
+
return null;
|
|
1006
|
+
const report = config.mode === 'report';
|
|
1007
|
+
if (!report && !canWrite)
|
|
1008
|
+
return null;
|
|
1009
|
+
let roles;
|
|
1010
|
+
try {
|
|
1011
|
+
roles = await this.getRoles();
|
|
1012
|
+
}
|
|
1013
|
+
catch (error) {
|
|
1014
|
+
this.logger.warn('军团身份组:读取身份组列表失败,这一轮不处理:%s', (0, util_1.errorText)(error));
|
|
1015
|
+
stats.problems.push(`军团身份组:读取身份组列表失败(${(0, util_1.errorText)(error)}),这一轮没有处理`);
|
|
1016
|
+
return null;
|
|
1017
|
+
}
|
|
1018
|
+
let mapping = await this.readCorpMap();
|
|
1019
|
+
if (c.source === 'patrol') {
|
|
1020
|
+
const missing = (list) => Object.entries(mapping).filter(([, id]) => !list.some((r) => r.id === id));
|
|
1021
|
+
let gone = missing(roles);
|
|
1022
|
+
if (gone.length) {
|
|
1023
|
+
// the list may have been read before a role was made (events run during a patrol): look again before believing it
|
|
1024
|
+
try {
|
|
1025
|
+
roles = await this.getRoles(true);
|
|
1026
|
+
}
|
|
1027
|
+
catch (error) {
|
|
1028
|
+
this.logger.warn('军团身份组:再读身份组列表失败,这一轮不处理:%s', (0, util_1.errorText)(error));
|
|
1029
|
+
stats.problems.push(`军团身份组:读取身份组列表失败(${(0, util_1.errorText)(error)}),这一轮没有处理`);
|
|
1030
|
+
return null;
|
|
1031
|
+
}
|
|
1032
|
+
gone = missing(roles);
|
|
1033
|
+
}
|
|
1034
|
+
const total = Object.keys(mapping).length;
|
|
1035
|
+
const listLooksWrong = gone.length > 0 && (!roles.some((r) => r.id === String(config.memberRoleId)) || (gone.length > 2 && gone.length * 5 > total));
|
|
1036
|
+
if (listLooksWrong) {
|
|
1037
|
+
const text = `⚠️ 军团身份组:映射里 ${total} 个身份组有 ${gone.length} 个在服务器的身份组列表里找不到,像是身份组列表不全,没有清理映射,这些军团身份组本轮也不发放;如果真的是被删了,请手动清掉映射`;
|
|
1038
|
+
this.board.raise('corp-roles-list', text);
|
|
1039
|
+
stats.problems.push(text);
|
|
1040
|
+
for (const [ticker] of gone)
|
|
1041
|
+
stats.corpSkip.add(ticker);
|
|
1042
|
+
mapping = Object.fromEntries(Object.entries(mapping).filter(([ticker]) => !stats.corpSkip.has(ticker)));
|
|
1043
|
+
}
|
|
1044
|
+
else {
|
|
1045
|
+
this.board.resolve('corp-roles-list', '身份组列表');
|
|
1046
|
+
if (gone.length) {
|
|
1047
|
+
for (const [ticker, id] of gone)
|
|
1048
|
+
this.logger.warn('军团身份组 [%s](%s)在服务器里已不存在,从映射里移除,需要时会重建', ticker, id);
|
|
1049
|
+
mapping = await this.updateCorpMap((map) => { for (const [ticker] of gone)
|
|
1050
|
+
delete map[ticker]; });
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
// mapped roles that must not be touched any more: now used as the member / roleMap / whitelist role, or given management rights
|
|
1055
|
+
const managed = this.otherManagedRoleIds();
|
|
1056
|
+
for (const [ticker, id] of Object.entries(mapping)) {
|
|
1057
|
+
const role = roles.find((r) => r.id === id);
|
|
1058
|
+
const reason = managed.has(id) ? '它现在被用作「成员」/ roleMap / 白名单身份组' : role && corpRolePrivileged(role) ? '它现在有管理类权限' : '';
|
|
1059
|
+
if (reason) {
|
|
1060
|
+
const text = `⚠️ 军团身份组 [${ticker}](${id}):${reason},权限不是 0 的军团身份组不会再发放或收回;请检查它`;
|
|
1061
|
+
this.board.raise(`corp-unsafe:${ticker}`, text);
|
|
1062
|
+
stats.problems.push(text);
|
|
1063
|
+
stats.corpSkip.add(ticker);
|
|
1064
|
+
}
|
|
1065
|
+
else {
|
|
1066
|
+
this.board.resolve(`corp-unsafe:${ticker}`, `军团身份组 [${ticker}]`);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
mapping = Object.fromEntries(Object.entries(mapping).filter(([ticker]) => !stats.corpSkip.has(ticker)));
|
|
1070
|
+
const memberRoleId = String(config.memberRoleId);
|
|
1071
|
+
const people = result.people
|
|
1072
|
+
.filter((plan) => plan.outcome !== 'absent' && !plan.kick)
|
|
1073
|
+
.flatMap((plan) => {
|
|
1074
|
+
const member = c.members.get(plan.kookId);
|
|
1075
|
+
const input = c.inputs.get(plan.kookId);
|
|
1076
|
+
if (!member || member.isBot || !input)
|
|
1077
|
+
return [];
|
|
1078
|
+
const verdict = input.memberResult;
|
|
1079
|
+
// not linked and losing the member role in this very run: counts as "no" (else the corp role would outlive the member role)
|
|
1080
|
+
const unlinkedRevoked = input.qq === null && plan.revoke.map(String).includes(memberRoleId);
|
|
1081
|
+
// linked once, no link now, and the member role is already gone (taken back earlier): the corp role must not outlive it either.
|
|
1082
|
+
// Someone who never had a link, and protected people (whose roles are left alone without an AA answer), stay untouched.
|
|
1083
|
+
const lostMember = input.qq === null && plan.outcome !== 'protected' && plan.record.everLinked && !member.roles.map(String).includes(memberRoleId);
|
|
1084
|
+
return [{ kookId: plan.kookId, roles: member.roles, decision: verdict?.decision ?? (unlinkedRevoked || lostMember ? 'deny' : 'unknown'), card: verdict?.card ?? null }];
|
|
1085
|
+
});
|
|
1086
|
+
const plan = (0, corp_1.planCorp)(people, mapping);
|
|
1087
|
+
const withheld = new Set(result.people.filter((p) => p.withheld.includes('breaker-revoke')).map((p) => p.kookId));
|
|
1088
|
+
const actions = new Map(plan.actions.map((a) => [a.kookId, withheld.has(a.kookId) ? { ...a, revoke: [] } : a]));
|
|
1089
|
+
// 1. the name card format changed? (only a full patrol sees enough people)
|
|
1090
|
+
const formatBroken = c.source === 'patrol' && plan.allowCount >= CORP_FORMAT_MIN_ALLOW && plan.unparsedCount * 2 > plan.allowCount;
|
|
1091
|
+
if (formatBroken) {
|
|
1092
|
+
const text = `⚠️ AA 名片格式可能变了:合格成员 ${plan.allowCount} 人里有 ${plan.unparsedCount} 人读不到军团简称,本轮军团身份组都没有动`;
|
|
1093
|
+
this.board.raise('corp-format', text);
|
|
1094
|
+
stats.problems.push(text);
|
|
1095
|
+
}
|
|
1096
|
+
else if (c.source === 'patrol') {
|
|
1097
|
+
this.board.resolve('corp-format', '军团简称');
|
|
1098
|
+
}
|
|
1099
|
+
// 2. too many corp roles to take back at once? (same threshold as the breaker)
|
|
1100
|
+
const revokeCount = [...actions.values()].filter((a) => a.revoke.length > 0).length;
|
|
1101
|
+
const threshold = c.memberCount === null ? Math.max(1, config.breakerCount) : (0, policy_1.breakerThreshold)(c.memberCount, (0, config_1.toPolicyConfig)(config));
|
|
1102
|
+
const tooMany = revokeCount > threshold;
|
|
1103
|
+
if (tooMany) {
|
|
1104
|
+
const text = `⚠️ 军团身份组收回熔断:本轮有 ${revokeCount} 人要收回军团身份组,阈值 ${threshold},本轮军团身份组都没有动;如果是真的(例如军团合并),调大 breakerCount 或 breakerPercent 后再巡检`;
|
|
1105
|
+
this.board.raise('corp-revoke', text);
|
|
1106
|
+
stats.problems.push(text);
|
|
1107
|
+
}
|
|
1108
|
+
else if (c.source === 'patrol') {
|
|
1109
|
+
this.board.resolve('corp-revoke', '军团身份组收回');
|
|
1110
|
+
}
|
|
1111
|
+
if (formatBroken || tooMany)
|
|
1112
|
+
return { source: c.source, mapping, actions: new Map(), held: true };
|
|
1113
|
+
if (report)
|
|
1114
|
+
this.reportCorp(actions, people, mapping, roles, managed, stats);
|
|
1115
|
+
return { source: c.source, mapping, actions };
|
|
1116
|
+
}
|
|
1117
|
+
/** Report mode: say what sync would do about roles (claim a same-name role, make a new one, hit the limit). */
|
|
1118
|
+
reportCorp(actions, people, mapping, roles, managed, stats) {
|
|
1119
|
+
const mappedIds = new Set(Object.values(mapping));
|
|
1120
|
+
const wouldMake = [];
|
|
1121
|
+
const blocked = [];
|
|
1122
|
+
let capped = 0;
|
|
1123
|
+
let total = roles.length;
|
|
1124
|
+
const seen = new Set();
|
|
1125
|
+
for (const action of actions.values()) {
|
|
1126
|
+
const ticker = action.grant;
|
|
1127
|
+
if (!ticker || mapping[ticker] || stats.corpSkip.has(ticker) || seen.has(ticker))
|
|
1128
|
+
continue;
|
|
1129
|
+
seen.add(ticker);
|
|
1130
|
+
const name = (0, corp_1.renderCorpRoleName)(this.config.corpRoleName, ticker);
|
|
1131
|
+
const same = roles.find((r) => r.name === name && !managed.has(r.id) && !mappedIds.has(r.id));
|
|
1132
|
+
if (same) {
|
|
1133
|
+
if (corpRolePrivileged(same) || same.permissions !== 0) {
|
|
1134
|
+
blocked.push(ticker);
|
|
1135
|
+
continue;
|
|
1136
|
+
}
|
|
1137
|
+
const holders = people.filter((p) => p.roles.includes(same.id));
|
|
1138
|
+
const losing = holders.filter((p) => {
|
|
1139
|
+
if (p.decision === 'deny')
|
|
1140
|
+
return true;
|
|
1141
|
+
const own = p.decision === 'allow' ? (0, corp_1.parseTicker)(p.card) : null;
|
|
1142
|
+
return own !== null && (0, corp_1.tickerKey)(own) !== ticker;
|
|
1143
|
+
});
|
|
1144
|
+
stats.problems.push(`将沿用身份组 [${ticker}](现有 ${holders.length} 人持有,其中 ${losing.length} 人不属于该军团或不合格,之后会被收回)`);
|
|
1145
|
+
continue;
|
|
1146
|
+
}
|
|
1147
|
+
if (total >= CORP_ROLE_STOP_AT) {
|
|
1148
|
+
capped++;
|
|
1149
|
+
continue;
|
|
1150
|
+
}
|
|
1151
|
+
total++;
|
|
1152
|
+
wouldMake.push(ticker);
|
|
1153
|
+
}
|
|
1154
|
+
stats.corpCreates += wouldMake.length;
|
|
1155
|
+
if (wouldMake.length) {
|
|
1156
|
+
const shown = wouldMake.slice(0, CORP_CREATES_PER_RUN).map((t) => `[${t}]`).join('、');
|
|
1157
|
+
stats.problems.push(`将建身份组 ${shown}${wouldMake.length > CORP_CREATES_PER_RUN ? `等 ${wouldMake.length} 个(每轮最多新建 ${CORP_CREATES_PER_RUN} 个)` : ''}`);
|
|
1158
|
+
}
|
|
1159
|
+
if (blocked.length)
|
|
1160
|
+
stats.problems.push(`同名身份组有权限,不会沿用也不会新建:${blocked.map((t) => `[${t}]`).join('、')};请改名,或把它的权限清成 0`);
|
|
1161
|
+
if (capped)
|
|
1162
|
+
stats.problems.push(`服务器身份组已有 ${roles.length} 个,另有 ${capped} 个军团身份组因接近 KOOK 上限(${CORP_ROLE_STOP_AT})不会新建`);
|
|
1163
|
+
}
|
|
1164
|
+
/** Take back old corp roles, then give the right one (made first when it does not exist yet). */
|
|
1165
|
+
async applyCorp(action, plan, tag, stats, corp) {
|
|
1166
|
+
const { guildId } = this.config;
|
|
1167
|
+
const api = this.kookClient;
|
|
1168
|
+
const label = (roleId) => {
|
|
1169
|
+
const ticker = Object.entries(corp.mapping).find(([, id]) => id === roleId)?.[0];
|
|
1170
|
+
return ticker ? `军团身份组「${ticker}」` : `军团身份组 ${roleId}`;
|
|
1171
|
+
};
|
|
1172
|
+
let target = null;
|
|
1173
|
+
if (action.grant) {
|
|
1174
|
+
target = corp.mapping[action.grant] ?? (await this.ensureCorpRole(action.grant, stats, corp.source));
|
|
1175
|
+
if (target)
|
|
1176
|
+
corp.mapping[action.grant] = target;
|
|
1177
|
+
// the new role cannot be had now (limit, failure): keep the old corp roles until it can be given in one go
|
|
1178
|
+
else
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
for (const roleId of action.revoke) {
|
|
1182
|
+
const ok = await this.attempt(plan.kookId, tag, `revoke:${roleId}`, 'revoke', `收回${label(roleId)}`, stats, () => api.revokeRole(guildId, plan.kookId, roleId));
|
|
1183
|
+
if (ok)
|
|
1184
|
+
stats.corpRevokes++;
|
|
1185
|
+
}
|
|
1186
|
+
if (target) {
|
|
1187
|
+
const roleId = target;
|
|
1188
|
+
const ok = await this.attempt(plan.kookId, tag, `grant:${roleId}`, 'grant', `给${label(roleId)}`, stats, () => api.grantRole(guildId, plan.kookId, roleId));
|
|
1189
|
+
if (ok)
|
|
1190
|
+
stats.corpGrants++;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
/** The role id for a corp ticker: from the mapping, a same-name role claimed, or a new one. Null when it cannot be had now. */
|
|
1194
|
+
ensureCorpRole(ticker, stats, source = 'patrol') {
|
|
1195
|
+
if (stats.corpSkip.has(ticker))
|
|
1196
|
+
return Promise.resolve(null);
|
|
1197
|
+
const running = this.corpCreating.get(ticker);
|
|
1198
|
+
if (running)
|
|
1199
|
+
return running;
|
|
1200
|
+
const made = this.corpMakeChain.then(() => this.makeCorpRole(ticker, stats, source)).finally(() => this.corpCreating.delete(ticker));
|
|
1201
|
+
this.corpMakeChain = made.catch(() => undefined);
|
|
1202
|
+
this.corpCreating.set(ticker, made);
|
|
1203
|
+
return made;
|
|
1204
|
+
}
|
|
1205
|
+
async makeCorpRole(ticker, stats, source) {
|
|
1206
|
+
const { config } = this;
|
|
1207
|
+
const existing = (await this.readCorpMap())[ticker];
|
|
1208
|
+
if (existing)
|
|
1209
|
+
return stats.corpSkip.has(ticker) ? null : existing;
|
|
1210
|
+
if (this.stopped() || stats.aborted)
|
|
1211
|
+
return null;
|
|
1212
|
+
const name = (0, corp_1.renderCorpRoleName)(config.corpRoleName, ticker);
|
|
1213
|
+
let roles;
|
|
1214
|
+
try {
|
|
1215
|
+
// always a fresh list: a role made by hand a minute ago, or made by a request that timed out, must be found (not made twice)
|
|
1216
|
+
roles = await this.getRoles(true);
|
|
1217
|
+
}
|
|
1218
|
+
catch (error) {
|
|
1219
|
+
this.logger.warn('军团身份组 [%s]:读取身份组列表失败:%s', ticker, (0, util_1.errorText)(error));
|
|
1220
|
+
stats.problems.push(`军团身份组 [${ticker}]:读取身份组列表失败(${(0, util_1.errorText)(error)}),下一轮再试`);
|
|
1221
|
+
stats.corpSkip.add(ticker);
|
|
1222
|
+
return null;
|
|
1223
|
+
}
|
|
1224
|
+
// a role with exactly this name is used as it is (claimed), unless the plugin manages it in another way or it has any permission
|
|
1225
|
+
const managed = this.otherManagedRoleIds();
|
|
1226
|
+
for (const id of Object.values(await this.readCorpMap()))
|
|
1227
|
+
managed.add(id);
|
|
1228
|
+
const claim = roles.find((r) => r.name === name && !managed.has(r.id));
|
|
1229
|
+
if (claim) {
|
|
1230
|
+
if (claim.permissions !== 0 || corpRolePrivileged(claim)) {
|
|
1231
|
+
const text = `⚠️ 军团身份组 [${ticker}]:服务器里已有同名身份组「${name}」,但它有权限${claim.isAdmin ? '(含管理员权限)' : ''},同名身份组有权限不能沿用;请改名,或把它的权限清成 0,之后会自动处理`;
|
|
1232
|
+
this.board.raise(`corp-claim:${ticker}`, text);
|
|
1233
|
+
stats.problems.push(text);
|
|
1234
|
+
stats.corpSkip.add(ticker);
|
|
1235
|
+
return null;
|
|
1236
|
+
}
|
|
1237
|
+
this.board.resolve(`corp-claim:${ticker}`, `军团身份组 [${ticker}]`);
|
|
1238
|
+
await this.updateCorpMap((map) => { map[ticker] = claim.id; });
|
|
1239
|
+
this.logger.info('军团身份组 [%s]:沿用服务器里已有的同名身份组 %s', ticker, claim.id);
|
|
1240
|
+
return claim.id;
|
|
1241
|
+
}
|
|
1242
|
+
if (source !== 'patrol') {
|
|
1243
|
+
// events and ticks may only make a few roles a day: a wrong card format would otherwise fill the server with junk roles
|
|
1244
|
+
const dayAgo = this.now() - 24 * HOUR;
|
|
1245
|
+
this.corpEventCreates = this.corpEventCreates.filter((at) => at > dayAgo);
|
|
1246
|
+
if (this.corpEventCreates.length >= CORP_EVENT_CREATES_PER_DAY) {
|
|
1247
|
+
stats.corpDeferred.add(ticker);
|
|
1248
|
+
stats.corpSkip.add(ticker);
|
|
1249
|
+
return null;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
if (stats.corpCreates >= CORP_CREATES_PER_RUN) {
|
|
1253
|
+
stats.corpDeferred.add(ticker);
|
|
1254
|
+
stats.corpSkip.add(ticker);
|
|
1255
|
+
return null;
|
|
1256
|
+
}
|
|
1257
|
+
if (roles.length >= CORP_ROLE_STOP_AT) {
|
|
1258
|
+
const text = `⚠️ 服务器身份组已有 ${roles.length} 个(KOOK 上限 100),不再新建军团身份组 [${ticker}];请清理不用的身份组`;
|
|
1259
|
+
this.board.raise('corp-limit', text);
|
|
1260
|
+
stats.problems.push(text);
|
|
1261
|
+
stats.corpSkip.add(ticker);
|
|
1262
|
+
return null;
|
|
1263
|
+
}
|
|
1264
|
+
this.board.resolve('corp-limit', '身份组数量');
|
|
1265
|
+
let created = null;
|
|
1266
|
+
const ok = await this.attempt('corp', '军团身份组', `create:${ticker}`, ticker, `新建身份组「${name}」`, stats, async () => {
|
|
1267
|
+
const role = await this.kookClient.createRole(config.guildId, name);
|
|
1268
|
+
created = role;
|
|
1269
|
+
// KOOK gives a new role its default permissions (not 0): clear them before anyone gets the role
|
|
1270
|
+
try {
|
|
1271
|
+
await this.kookClient.resetRole(config.guildId, role.id);
|
|
1272
|
+
}
|
|
1273
|
+
catch (error) {
|
|
1274
|
+
if (error instanceof kook_1.KookOfflineError)
|
|
1275
|
+
throw error;
|
|
1276
|
+
throw new Error(`身份组「${name}」已建(${role.id})但没能把权限设成 0:${(0, util_1.errorText)(error)};没有发放,请手动把它的权限清成 0 或删掉`);
|
|
1277
|
+
}
|
|
1278
|
+
});
|
|
1279
|
+
if (!ok || !created) {
|
|
1280
|
+
stats.corpSkip.add(ticker);
|
|
1281
|
+
return null;
|
|
1282
|
+
}
|
|
1283
|
+
const role = created;
|
|
1284
|
+
// read the list again: only a role that really has permissions 0 is recorded and given out
|
|
1285
|
+
let seen;
|
|
1286
|
+
try {
|
|
1287
|
+
seen = (await this.getRoles(true)).find((r) => r.id === role.id);
|
|
1288
|
+
}
|
|
1289
|
+
catch (error) {
|
|
1290
|
+
this.logger.warn('军团身份组 [%s]:确认新身份组权限时读取列表失败:%s', ticker, (0, util_1.errorText)(error));
|
|
1291
|
+
}
|
|
1292
|
+
if (!seen || seen.permissions !== 0) {
|
|
1293
|
+
const text = `⚠️ 军团身份组 [${ticker}]:新建的身份组「${name}」(${role.id})读回的权限不是 0(或读不到),没有发放;请手动把它的权限清成 0 或删掉它`;
|
|
1294
|
+
this.board.raise(`corp-claim:${ticker}`, text);
|
|
1295
|
+
stats.problems.push(text);
|
|
1296
|
+
stats.alerts.push(text);
|
|
1297
|
+
stats.corpSkip.add(ticker);
|
|
1298
|
+
return null;
|
|
1299
|
+
}
|
|
1300
|
+
await this.updateCorpMap((map) => { map[ticker] = role.id; });
|
|
1301
|
+
if (source !== 'patrol')
|
|
1302
|
+
this.corpEventCreates.push(this.now());
|
|
1303
|
+
stats.corpCreates++;
|
|
1304
|
+
await this.store.audit('corp-create', '', '', `新建军团身份组「${name}」(${role.id})`, 'bot');
|
|
1305
|
+
return role.id;
|
|
1306
|
+
}
|
|
1307
|
+
// ---------------------------------------------------------------- corp channel groups (军团分组)
|
|
1308
|
+
async readCorpChannels() {
|
|
1309
|
+
const stored = (await this.store.getKv(store_1.kvKeys.corpChannels(this.config.guildId))) ?? {};
|
|
1310
|
+
const entries = {};
|
|
1311
|
+
for (const [ticker, entry] of Object.entries(stored)) {
|
|
1312
|
+
if (ticker && entry && typeof entry.categoryId === 'string' && (entry.categoryId || entry.pending))
|
|
1313
|
+
entries[ticker] = { ...entry, channelIds: entry.channelIds ?? {}, secured: entry.secured ?? [] };
|
|
1314
|
+
}
|
|
1315
|
+
return entries;
|
|
1316
|
+
}
|
|
1317
|
+
corpGroupSummary(entries) {
|
|
1318
|
+
const live = entries.filter((e) => !e.deleted && e.categoryId);
|
|
1319
|
+
const parts = [`已建 ${live.filter((e) => e.done).length} 个`];
|
|
1320
|
+
const unfinished = live.filter((e) => !e.done && !e.stopped).length;
|
|
1321
|
+
const stopped = live.filter((e) => e.stopped).length;
|
|
1322
|
+
if (unfinished)
|
|
1323
|
+
parts.push(`没建全 ${unfinished} 个`);
|
|
1324
|
+
if (stopped)
|
|
1325
|
+
parts.push(`已停止补建 ${stopped} 个`);
|
|
1326
|
+
const gone = entries.filter((e) => e.deleted).length;
|
|
1327
|
+
if (gone)
|
|
1328
|
+
parts.push(`已被删除 ${gone} 个`);
|
|
1329
|
+
return parts.join('|');
|
|
1330
|
+
}
|
|
1331
|
+
/** Linked members per ticker who hold the corp role now or are about to (this run's decision). */
|
|
1332
|
+
corpHolders(result, c, corp) {
|
|
1333
|
+
const byRole = new Map(Object.entries(corp.mapping).map(([ticker, id]) => [id, ticker]));
|
|
1334
|
+
const holders = {};
|
|
1335
|
+
for (const plan of result.people) {
|
|
1336
|
+
const member = c.members.get(plan.kookId);
|
|
1337
|
+
const input = c.inputs.get(plan.kookId);
|
|
1338
|
+
if (!member || member.isBot || !input || input.qq === null || plan.kick)
|
|
1339
|
+
continue;
|
|
1340
|
+
const action = corp.actions.get(plan.kookId);
|
|
1341
|
+
const tickers = new Set();
|
|
1342
|
+
for (const id of member.roles) {
|
|
1343
|
+
const ticker = byRole.get(id);
|
|
1344
|
+
if (ticker && !action?.revoke.includes(id))
|
|
1345
|
+
tickers.add(ticker);
|
|
1346
|
+
}
|
|
1347
|
+
if (action?.grant)
|
|
1348
|
+
tickers.add(action.grant);
|
|
1349
|
+
for (const ticker of tickers)
|
|
1350
|
+
holders[ticker] = (holders[ticker] ?? 0) + 1;
|
|
1351
|
+
}
|
|
1352
|
+
return holders;
|
|
1353
|
+
}
|
|
1354
|
+
/** A "no" from KOOK on a channel call most likely means the bot lacks a permission: say which. */
|
|
1355
|
+
async channelCall(fn) {
|
|
1356
|
+
try {
|
|
1357
|
+
return await fn();
|
|
1358
|
+
}
|
|
1359
|
+
catch (error) {
|
|
1360
|
+
if ((0, kook_1.isExplicitRejection)(error))
|
|
1361
|
+
throw new Error(`${(0, util_1.errorText)(error)}(请给机器人的身份组开「频道管理」和「管理角色权限」)`);
|
|
1362
|
+
throw error;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Corp channel groups: one category per corp (hidden from everyone but the corp role and the bot) with the template's
|
|
1367
|
+
* channels in it. Patrol only. Never deletes anything. In report mode it only says what would be made.
|
|
1368
|
+
* Nothing is written when the channel list could not be read (an unreadable list is not "the owner deleted it").
|
|
1369
|
+
* While the bot cannot set permissions (or a group is not hidden yet) no new group is made: a new category is
|
|
1370
|
+
* visible to everybody until its permissions are set.
|
|
1371
|
+
*/
|
|
1372
|
+
async prepareCorpChannels(result, c, corp, stats) {
|
|
1373
|
+
const { config } = this;
|
|
1374
|
+
if (!(0, config_1.corpChannelsOn)(config) || c.source !== 'patrol' || !(0, config_1.normalizedCorpTemplate)(config).length)
|
|
1375
|
+
return;
|
|
1376
|
+
const guildId = config.guildId;
|
|
1377
|
+
const report = config.mode === 'report';
|
|
1378
|
+
const holders = this.corpHolders(result, c, corp);
|
|
1379
|
+
const exclude = new Set(config.corpChannelExclude.map((t) => (0, corp_1.tickerKey)(String(t).trim())).filter(Boolean));
|
|
1380
|
+
const entries = await this.readCorpChannels();
|
|
1381
|
+
const wanted = Object.keys(corp.mapping).some((t) => !exclude.has(t) && !(t in entries) && (holders[t] ?? 0) >= config.corpChannelMinMembers);
|
|
1382
|
+
const list = (tickers) => tickers.map((t) => `[${t}]`).join('、');
|
|
1383
|
+
if (corp.held) {
|
|
1384
|
+
// the corp roles were not touched this run (some may still sit on people who should not have them): a private group now would show them its content
|
|
1385
|
+
if (wanted)
|
|
1386
|
+
stats.problems.push('军团分组:这一轮军团身份组没有动(名片格式或收回熔断),不新建分组');
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
if (!wanted && !Object.keys(entries).length)
|
|
1390
|
+
return;
|
|
1391
|
+
let channels;
|
|
1392
|
+
try {
|
|
1393
|
+
channels = await this.kookClient.listChannels(guildId);
|
|
1394
|
+
}
|
|
1395
|
+
catch (error) {
|
|
1396
|
+
if (error instanceof kook_1.KookOfflineError)
|
|
1397
|
+
this.kookWasOffline = true;
|
|
1398
|
+
this.logger.warn('军团分组:读取频道列表失败,这一轮不处理:%s', (0, util_1.errorText)(error));
|
|
1399
|
+
stats.problems.push(`军团分组:读取频道列表失败(${(0, util_1.errorText)(error)}),这一轮没有处理`);
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
const save = () => this.store.setKv(store_1.kvKeys.corpChannels(guildId), entries);
|
|
1403
|
+
let changed = false;
|
|
1404
|
+
// a category that was asked for but whose answer was lost: found again by its name and finished as our own
|
|
1405
|
+
for (const [ticker, entry] of Object.entries(entries)) {
|
|
1406
|
+
if (entry.categoryId || !entry.pending)
|
|
1407
|
+
continue;
|
|
1408
|
+
const claimed = new Set(Object.values(entries).map((e) => e.categoryId));
|
|
1409
|
+
const found = channels.find((ch) => ch.isCategory && ch.name === entry.pending.name && !claimed.has(ch.id));
|
|
1410
|
+
if (found) {
|
|
1411
|
+
entry.categoryId = found.id;
|
|
1412
|
+
entry.done = false;
|
|
1413
|
+
this.logger.info('军团分组 [%s]:上一轮建分类没收到答复,在频道列表里找到了(%s),按自己建的补完权限', ticker, found.id);
|
|
1414
|
+
}
|
|
1415
|
+
else
|
|
1416
|
+
delete entries[ticker];
|
|
1417
|
+
delete entry.pending;
|
|
1418
|
+
changed = true;
|
|
1419
|
+
}
|
|
1420
|
+
if (!report) {
|
|
1421
|
+
for (const [ticker, entry] of Object.entries(entries)) {
|
|
1422
|
+
if (entry.deleted || entry.adopted || !entry.roleId || !corp.mapping[ticker] || entry.roleId === corp.mapping[ticker])
|
|
1423
|
+
continue;
|
|
1424
|
+
// the corp role was made again (the owner deleted it): the overwrites still name the old id
|
|
1425
|
+
entry.roleId = corp.mapping[ticker];
|
|
1426
|
+
entry.done = false;
|
|
1427
|
+
entry.stopped = false;
|
|
1428
|
+
entry.attempts = 0;
|
|
1429
|
+
entry.secured = [];
|
|
1430
|
+
changed = true;
|
|
1431
|
+
this.logger.warn('军团分组 [%s]:军团身份组换了新的,分组的权限按新身份组重设', ticker);
|
|
1432
|
+
stats.problems.push(`军团分组 [${ticker}]:军团身份组换了新的,分组的权限会按新身份组重设`);
|
|
1433
|
+
}
|
|
1434
|
+
if (this.corpGroupReset) {
|
|
1435
|
+
this.corpGroupReset = false;
|
|
1436
|
+
for (const entry of Object.values(entries)) {
|
|
1437
|
+
if (entry.stopped || entry.attempts) {
|
|
1438
|
+
entry.stopped = false;
|
|
1439
|
+
entry.attempts = 0;
|
|
1440
|
+
changed = true;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
const plan = (0, corp_1.planCorpChannels)({
|
|
1446
|
+
holders, mapping: corp.mapping, entries, channels, minMembers: config.corpChannelMinMembers, exclude,
|
|
1447
|
+
categoryName: (ticker) => (0, corp_1.renderCorpRoleName)(config.corpCategoryName, ticker), limit: CORP_GROUPS_PER_RUN,
|
|
1448
|
+
});
|
|
1449
|
+
// a list that suddenly lacks many groups (or everything) is more likely a bad list / lost view than a clean-up by the owner
|
|
1450
|
+
const live = Object.values(entries).filter((e) => !e.deleted).length;
|
|
1451
|
+
if (plan.deleted.length && (channels.length === 0 || (plan.deleted.length > 2 && plan.deleted.length * 5 > live))) {
|
|
1452
|
+
const text = `⚠️ 军团分组:${live} 个分组里有 ${plan.deleted.length} 个在频道列表里找不到,像是列表不全或机器人看不到它们,没有标记为已删除:${list(plan.deleted)}`;
|
|
1453
|
+
this.logger.warn('%s', text);
|
|
1454
|
+
stats.problems.push(text);
|
|
1455
|
+
plan.deleted = [];
|
|
1456
|
+
}
|
|
1457
|
+
// written off only when missing in two patrols in a row (the list shows only what the bot can see)
|
|
1458
|
+
const missingNow = new Set(plan.deleted);
|
|
1459
|
+
const writeOff = plan.deleted.filter((t) => entries[t].missing);
|
|
1460
|
+
const firstMiss = plan.deleted.filter((t) => !entries[t].missing);
|
|
1461
|
+
plan.deleted = writeOff;
|
|
1462
|
+
if (report) {
|
|
1463
|
+
stats.corpGroups = plan.create.length;
|
|
1464
|
+
if (plan.create.length)
|
|
1465
|
+
stats.problems.push(`将建 ${plan.create.length} 个分组:${list(plan.create)}`);
|
|
1466
|
+
if (plan.adopt.length)
|
|
1467
|
+
stats.problems.push(`同名分组已存在,将沿用,权限不会动:${list(plan.adopt.map((a) => a.ticker))}`);
|
|
1468
|
+
if (writeOff.length)
|
|
1469
|
+
stats.problems.push(`分组已不在 KOOK(被删掉了?),sync 时会标记为已删除、不再重建:${list(writeOff)}`);
|
|
1470
|
+
if (firstMiss.length)
|
|
1471
|
+
stats.problems.push(`分组在频道列表里找不到(第 1 次):${list(firstMiss)}`);
|
|
1472
|
+
}
|
|
1473
|
+
else {
|
|
1474
|
+
for (const [ticker, entry] of Object.entries(entries)) {
|
|
1475
|
+
if (!entry.deleted && !missingNow.has(ticker) && entry.missing) {
|
|
1476
|
+
delete entry.missing;
|
|
1477
|
+
changed = true;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
for (const ticker of firstMiss) {
|
|
1481
|
+
entries[ticker].missing = true;
|
|
1482
|
+
changed = true;
|
|
1483
|
+
this.logger.warn('军团分组 [%s]:分类 %s 在频道列表里找不到(第 1 次),下一轮还找不到就标记为已删除', ticker, entries[ticker].categoryId);
|
|
1484
|
+
stats.problems.push(`军团分组 [${ticker}] 在频道列表里找不到(第 1 次),下一轮还找不到就标记为已删除、不再重建`);
|
|
1485
|
+
}
|
|
1486
|
+
for (const ticker of writeOff) {
|
|
1487
|
+
entries[ticker].deleted = true;
|
|
1488
|
+
delete entries[ticker].missing;
|
|
1489
|
+
changed = true;
|
|
1490
|
+
this.logger.warn('军团分组 [%s]:分类 %s 连续两轮不在 KOOK,标记为已删除,不再重建', ticker, entries[ticker].categoryId);
|
|
1491
|
+
stats.problems.push(`军团分组 [${ticker}] 已被删除,不再重建`);
|
|
1492
|
+
}
|
|
1493
|
+
for (const { ticker, categoryId } of plan.adopt) {
|
|
1494
|
+
entries[ticker] = { categoryId, channelIds: {}, secured: [], createdAt: this.now(), done: true, adopted: true };
|
|
1495
|
+
this.logger.info('军团分组 [%s]:沿用服务器里已有的同名分类 %s,权限没动', ticker, categoryId);
|
|
1496
|
+
stats.problems.push(`军团分组 [${ticker}]:同名分组已存在,已沿用,权限没动(它现在是什么权限就是什么权限,请自己看一下)`);
|
|
1497
|
+
changed = true;
|
|
1498
|
+
}
|
|
1499
|
+
if (changed)
|
|
1500
|
+
await save();
|
|
1501
|
+
let permFailed = false;
|
|
1502
|
+
let secured = 0;
|
|
1503
|
+
for (const ticker of plan.repair) {
|
|
1504
|
+
if (this.stopped() || stats.aborted)
|
|
1505
|
+
break;
|
|
1506
|
+
const res = await this.fillCorpGroup(ticker, entries, corp.mapping[ticker], channels, stats, save);
|
|
1507
|
+
permFailed ||= res.permFailed;
|
|
1508
|
+
secured += res.secured;
|
|
1509
|
+
}
|
|
1510
|
+
// a new category is visible to everybody until its permissions are set: nothing new while one is not hidden yet
|
|
1511
|
+
const unhidden = Object.entries(entries).filter(([, e]) => !e.deleted && !e.adopted && e.categoryId && !e.secured.includes(e.categoryId)).map(([t]) => t);
|
|
1512
|
+
const queue = [...plan.create, ...plan.deferred];
|
|
1513
|
+
const tried = new Set();
|
|
1514
|
+
let made = 0;
|
|
1515
|
+
if (!permFailed && !unhidden.length) {
|
|
1516
|
+
for (const ticker of queue) {
|
|
1517
|
+
if (made >= CORP_GROUPS_PER_RUN || this.stopped() || stats.aborted)
|
|
1518
|
+
break;
|
|
1519
|
+
tried.add(ticker);
|
|
1520
|
+
const res = await this.fillCorpGroup(ticker, entries, corp.mapping[ticker], channels, stats, save);
|
|
1521
|
+
if (res.made)
|
|
1522
|
+
made++;
|
|
1523
|
+
secured += res.secured;
|
|
1524
|
+
if (res.permFailed) {
|
|
1525
|
+
permFailed = true;
|
|
1526
|
+
break;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
if (permFailed) {
|
|
1531
|
+
this.board.raise('corp-channel-perm', '⚠️ 军团分组:机器人建频道或设权限被 KOOK 拒绝,已暂停新建分组;请给机器人的身份组开「频道管理」和「管理角色权限」,开好后发 kookaa.patrol');
|
|
1532
|
+
}
|
|
1533
|
+
else if (secured > 0 && !unhidden.length) {
|
|
1534
|
+
this.board.resolve('corp-channel-perm', '军团分组的建频道 / 设权限');
|
|
1535
|
+
}
|
|
1536
|
+
plan.deferred = queue.filter((t) => !tried.has(t) && !(t in entries));
|
|
1537
|
+
if (plan.deferred.length && (permFailed || unhidden.length)) {
|
|
1538
|
+
stats.problems.push(`还有 ${plan.deferred.length} 个军团分组没建:有分组的权限还没设好,先补好再建新的${unhidden.length ? `(${list(unhidden)})` : ''}`);
|
|
1539
|
+
plan.deferred = [];
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
if (plan.deferred.length)
|
|
1543
|
+
stats.problems.push(`还有 ${plan.deferred.length} 个军团分组留到下一轮再建(每轮最多新建 ${CORP_GROUPS_PER_RUN} 个):${list(plan.deferred)}`);
|
|
1544
|
+
const empty = [];
|
|
1545
|
+
for (const ticker of plan.empty)
|
|
1546
|
+
if (await this.noteOnce('corp', `empty:${ticker}`, 7 * DAY))
|
|
1547
|
+
empty.push(ticker);
|
|
1548
|
+
if (empty.length)
|
|
1549
|
+
stats.problems.push(`这些军团现在没有成员,分组保留没动:${list(empty)}`);
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* Make (or finish) one group: the category, its permissions, then every template channel with its permissions.
|
|
1553
|
+
* Every id is saved as soon as it exists, so a reload or a failure in the middle never leads to a second group;
|
|
1554
|
+
* a later patrol only makes what is missing. The category is hidden before any channel is made in it.
|
|
1555
|
+
* Before asking for a category a `pending` note is saved, and a channel is looked for by name in its category first,
|
|
1556
|
+
* so an answer that got lost (timeout) does not lead to a duplicate or to a "same name, hands off" take-over.
|
|
1557
|
+
* A round counts against the repair limit only when something was really sent to KOOK.
|
|
1558
|
+
*/
|
|
1559
|
+
async fillCorpGroup(ticker, entries, roleId, channels, stats, save) {
|
|
1560
|
+
const { config } = this;
|
|
1561
|
+
const { guildId } = config;
|
|
1562
|
+
const api = this.kookClient;
|
|
1563
|
+
const tag = `军团分组 [${ticker}]`;
|
|
1564
|
+
const res = { made: false, permFailed: false, secured: 0 };
|
|
1565
|
+
let sent = false;
|
|
1566
|
+
/** One write to KOOK: tells whether anything was really sent, and whether KOOK said no. */
|
|
1567
|
+
const write = async (action, target, label, fn, perm = true) => {
|
|
1568
|
+
let ran = false;
|
|
1569
|
+
let rejected = false;
|
|
1570
|
+
const ok = await this.attempt('corp', '军团分组', action, target, label, stats, async () => {
|
|
1571
|
+
ran = true;
|
|
1572
|
+
try {
|
|
1573
|
+
await this.channelCall(fn);
|
|
1574
|
+
}
|
|
1575
|
+
catch (error) {
|
|
1576
|
+
rejected = (0, kook_1.isExplicitRejection)(error);
|
|
1577
|
+
throw error;
|
|
1578
|
+
}
|
|
1579
|
+
});
|
|
1580
|
+
if (ran)
|
|
1581
|
+
sent = true;
|
|
1582
|
+
if (rejected && perm)
|
|
1583
|
+
res.permFailed = true; // a refused category / permission call means the bot lacks a permission; a refused channel may be just that channel
|
|
1584
|
+
return { ok, ran, rejected };
|
|
1585
|
+
};
|
|
1586
|
+
let entry = entries[ticker];
|
|
1587
|
+
const repairing = !!entry;
|
|
1588
|
+
if (entry) {
|
|
1589
|
+
if ((entry.attempts ?? 0) >= CORP_GROUP_REPAIRS) {
|
|
1590
|
+
entry.stopped = true;
|
|
1591
|
+
await save();
|
|
1592
|
+
const text = `⚠️ ${tag}:补了 ${CORP_GROUP_REPAIRS} 轮还没建全或没设好权限,已停止,不再尝试(没有删任何东西);请手动检查,它可能对所有人可见。补好机器人的权限后发 kookaa.patrol 可重新补建`;
|
|
1593
|
+
this.logger.warn('%s', text);
|
|
1594
|
+
stats.problems.push(text);
|
|
1595
|
+
return res;
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
else {
|
|
1599
|
+
// the 24 h pause after a refusal is shared by all groups: while it runs nothing is even written down
|
|
1600
|
+
if (!this.failures.shouldTry('corp', 'category', 'perm', this.now()))
|
|
1601
|
+
return res;
|
|
1602
|
+
const name = (0, corp_1.renderCorpRoleName)(config.corpCategoryName, ticker);
|
|
1603
|
+
entries[ticker] = { categoryId: '', channelIds: {}, secured: [], createdAt: this.now(), done: false, roleId, pending: { name, at: this.now() } };
|
|
1604
|
+
await save();
|
|
1605
|
+
let made = null;
|
|
1606
|
+
const out = await write('category', 'perm', `新建分类「${name}」`, async () => {
|
|
1607
|
+
made = await api.createChannel(guildId, name, { category: true });
|
|
1608
|
+
});
|
|
1609
|
+
if (!out.ok || !made) {
|
|
1610
|
+
// refused / not sent: nothing exists. A lost answer (timeout, 5xx) keeps the note: the next patrol looks for the name.
|
|
1611
|
+
if (!out.ran || out.rejected) {
|
|
1612
|
+
delete entries[ticker];
|
|
1613
|
+
await save();
|
|
1614
|
+
}
|
|
1615
|
+
return res;
|
|
1616
|
+
}
|
|
1617
|
+
entry = entries[ticker];
|
|
1618
|
+
delete entry.pending;
|
|
1619
|
+
entry.categoryId = made.id;
|
|
1620
|
+
res.made = true;
|
|
1621
|
+
stats.corpGroups++;
|
|
1622
|
+
await save();
|
|
1623
|
+
await this.store.audit('corp-channel', '', '', `新建军团分组「${name}」(${entry.categoryId})`, 'bot');
|
|
1624
|
+
}
|
|
1625
|
+
const group = entry;
|
|
1626
|
+
group.roleId = roleId;
|
|
1627
|
+
const secure = async (channelId) => {
|
|
1628
|
+
if (group.secured.includes(channelId))
|
|
1629
|
+
return true;
|
|
1630
|
+
const botId = config.kookBotId.trim();
|
|
1631
|
+
// the bot first (it must keep seeing what it made), then the corp, then everyone else is shut out
|
|
1632
|
+
const out = await write('secure', 'perm', `设置${tag}的权限`, async () => {
|
|
1633
|
+
await api.setChannelRole(channelId, { type: 'user_id', value: botId }, CHANNEL_VIEW, 0);
|
|
1634
|
+
await api.setChannelRole(channelId, { type: 'role_id', value: roleId }, CHANNEL_VIEW, 0);
|
|
1635
|
+
await api.setChannelRole(channelId, { type: 'role_id', value: '0' }, 0, CHANNEL_VIEW);
|
|
1636
|
+
});
|
|
1637
|
+
if (!out.ok)
|
|
1638
|
+
return false;
|
|
1639
|
+
// read back all three: @全体成员 cannot see, the corp role and the bot can
|
|
1640
|
+
let confirmed = false;
|
|
1641
|
+
try {
|
|
1642
|
+
const roles = await api.getChannelRoles(channelId);
|
|
1643
|
+
const can = (v) => !!v && Math.floor(v.allow / CHANNEL_VIEW) % 2 === 1;
|
|
1644
|
+
const everyone = roles.roles.find((r) => r.id === '0');
|
|
1645
|
+
confirmed = !!everyone && Math.floor(everyone.deny / CHANNEL_VIEW) % 2 === 1
|
|
1646
|
+
&& can(roles.roles.find((r) => r.id === roleId)) && can(roles.users.find((u) => u.id === botId));
|
|
1647
|
+
}
|
|
1648
|
+
catch (error) {
|
|
1649
|
+
this.logger.warn('%s:读回频道 %s 的权限失败:%s', tag, channelId, (0, util_1.errorText)(error));
|
|
1650
|
+
}
|
|
1651
|
+
if (!confirmed) {
|
|
1652
|
+
res.permFailed = true;
|
|
1653
|
+
const text = `⚠️ ${tag}:频道 ${channelId} 的权限没能确认(读回时 @全体成员 没有「不可查看」,或军团身份组 / 机器人没有「可查看」),它可能对所有人可见,请马上手动检查;没有删任何东西,下一轮会再试`;
|
|
1654
|
+
this.logger.warn('%s', text);
|
|
1655
|
+
stats.problems.push(text);
|
|
1656
|
+
return false;
|
|
1657
|
+
}
|
|
1658
|
+
group.secured.push(channelId);
|
|
1659
|
+
res.secured++;
|
|
1660
|
+
await save();
|
|
1661
|
+
return true;
|
|
1662
|
+
};
|
|
1663
|
+
// nothing is made inside a category that is not hidden yet
|
|
1664
|
+
if (await secure(group.categoryId)) {
|
|
1665
|
+
const seen = new Set();
|
|
1666
|
+
for (const item of (0, config_1.normalizedCorpTemplate)(config)) {
|
|
1667
|
+
if (this.stopped() || stats.aborted)
|
|
1668
|
+
break;
|
|
1669
|
+
const key = `${item.type}:${item.name}`;
|
|
1670
|
+
if (seen.has(key))
|
|
1671
|
+
continue;
|
|
1672
|
+
seen.add(key);
|
|
1673
|
+
let channelId = group.channelIds[key];
|
|
1674
|
+
if (!channelId) {
|
|
1675
|
+
const name = (0, corp_1.renderCorpRoleName)(item.name, ticker);
|
|
1676
|
+
const known = new Set(Object.values(group.channelIds));
|
|
1677
|
+
const existing = channels.find((ch) => !ch.isCategory && ch.parentId === group.categoryId && ch.name === name && !known.has(ch.id));
|
|
1678
|
+
if (existing) {
|
|
1679
|
+
// made before but the answer was lost: use it, do not make a second one
|
|
1680
|
+
channelId = group.channelIds[key] = existing.id;
|
|
1681
|
+
await save();
|
|
1682
|
+
}
|
|
1683
|
+
else {
|
|
1684
|
+
let made = null;
|
|
1685
|
+
const out = await write(`channel:${ticker}:${key}`, key, `新建频道「${name}」(${tag})`, async () => {
|
|
1686
|
+
made = await api.createChannel(guildId, name, { parentId: group.categoryId, voice: item.type === 'voice' });
|
|
1687
|
+
}, false);
|
|
1688
|
+
if (!out.ok || !made) {
|
|
1689
|
+
if (res.permFailed)
|
|
1690
|
+
break;
|
|
1691
|
+
continue;
|
|
1692
|
+
}
|
|
1693
|
+
channelId = group.channelIds[key] = made.id;
|
|
1694
|
+
await save();
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
await secure(channelId);
|
|
1698
|
+
if (res.permFailed)
|
|
1699
|
+
break;
|
|
1700
|
+
}
|
|
1701
|
+
const ids = [...seen].map((key) => group.channelIds[key]);
|
|
1702
|
+
group.done = !res.permFailed && ids.every((id) => !!id && group.secured.includes(id)) && group.secured.includes(group.categoryId);
|
|
1703
|
+
}
|
|
1704
|
+
if (repairing && sent && !group.done)
|
|
1705
|
+
group.attempts = (group.attempts ?? 0) + 1;
|
|
1706
|
+
await save();
|
|
1707
|
+
return res;
|
|
1708
|
+
}
|
|
913
1709
|
// ---------------------------------------------------------------- patrol
|
|
914
1710
|
/** Patrol now, or after the one that is running. Resolves with the summary text. */
|
|
915
1711
|
requestPatrol() {
|
|
@@ -982,6 +1778,7 @@ class Guard {
|
|
|
982
1778
|
}
|
|
983
1779
|
if (this.stopped())
|
|
984
1780
|
return '没有巡检:插件已暂停或重载';
|
|
1781
|
+
this.checkWhitelistRoles(roles);
|
|
985
1782
|
this.learnMaster(list.members);
|
|
986
1783
|
const members = (0, kook_1.markAdmins)(list.members, roles);
|
|
987
1784
|
const listing = { members: new Map(members.map((m) => [m.id, m])), complete: list.complete, error: list.error };
|
|
@@ -1017,6 +1814,14 @@ class Guard {
|
|
|
1017
1814
|
this.notifier.push(text);
|
|
1018
1815
|
return text;
|
|
1019
1816
|
}
|
|
1817
|
+
/** A whitelist role that does not exist (typo, other server, deleted and recreated) protects nobody: say so. */
|
|
1818
|
+
checkWhitelistRoles(roles) {
|
|
1819
|
+
const missing = (0, config_1.toPolicyConfig)(this.config).whitelistRoles.filter((id) => !roles.some((r) => r.id === id));
|
|
1820
|
+
if (missing.length)
|
|
1821
|
+
this.board.raise('whitelist-roles', `⚠️ 白名单身份组 ${missing.join('、')} 在服务器里不存在,这些身份组里的人不会免检,请改成正确的身份组 ID`);
|
|
1822
|
+
else
|
|
1823
|
+
this.board.resolve('whitelist-roles', '白名单身份组');
|
|
1824
|
+
}
|
|
1020
1825
|
patrolSummary(outcome, size) {
|
|
1021
1826
|
const mode = this.config.mode;
|
|
1022
1827
|
if (!outcome.ran || !outcome.result) {
|
|
@@ -1026,7 +1831,10 @@ class Guard {
|
|
|
1026
1831
|
const { counts } = outcome.result;
|
|
1027
1832
|
const would = mode === 'report';
|
|
1028
1833
|
const s = outcome.stats;
|
|
1029
|
-
const
|
|
1834
|
+
const corp = this.config.corpRoles
|
|
1835
|
+
? `|军团身份组:${would ? `将给 ${s.corpGrants} / 将收 ${s.corpRevokes} / 将建 ${s.corpCreates}` : `给 ${s.corpGrants} / 收 ${s.corpRevokes} / 新建 ${s.corpCreates}`}${(0, config_1.corpChannelsOn)(this.config) ? `|军团分组:${would ? '将建' : '新建'} ${s.corpGroups}` : ''}`
|
|
1836
|
+
: '';
|
|
1837
|
+
const head = `KOOK 巡检${would ? '(report 模式,下面是「将会」做的)' : ''}:服务器 ${size} 人|已关联 ${counts.linked}|合格 ${counts.qualified}|给身份组 ${would ? counts.grants : s.grants}|收身份组 ${would ? counts.revokes : s.revokes}|改昵称 ${would ? counts.nicknames : s.nicknames}|倒计时中 ${counts.counting}|本轮踢出 ${s.kicks}${corp}`;
|
|
1030
1838
|
const lines = [...s.problems, ...s.notes];
|
|
1031
1839
|
if (lines.length === 0)
|
|
1032
1840
|
return head;
|
|
@@ -1227,6 +2035,25 @@ class Guard {
|
|
|
1227
2035
|
this.notifier.push('⚠️ 机器人被移出了本服务器,已自动暂停(不再改身份组、昵称,不提醒、不踢人)');
|
|
1228
2036
|
return '已暂停:不再改身份组、昵称,不提醒、不踢人。发送 kookaa.resume 恢复。';
|
|
1229
2037
|
}
|
|
2038
|
+
async postCard(actor) {
|
|
2039
|
+
const channel = (0, util_1.normalizeKookId)(this.config.verifyChannelId);
|
|
2040
|
+
if (!channel)
|
|
2041
|
+
return '没有发出卡片:插件配置里的「验证」频道 ID(verifyChannelId)是空的。请填上频道 ID 后再发 kookaa.card。';
|
|
2042
|
+
const api = this.kookApi();
|
|
2043
|
+
if (!api)
|
|
2044
|
+
return '没有发出卡片:KOOK 机器人不在线。等它上线后再发 kookaa.card。';
|
|
2045
|
+
if (this.config.mode === 'off')
|
|
2046
|
+
this.logger.info('模式是 off,但运维 %s 要求发卡片,照发', actor);
|
|
2047
|
+
try {
|
|
2048
|
+
const id = await api.sendCard(channel, (0, card_1.buildCard)(this.config));
|
|
2049
|
+
this.logger.info('运维 %s 在验证频道发出了绑定卡片(消息 ID %s)', actor, id || '未知');
|
|
2050
|
+
return `✅ 已在验证频道发出卡片,请手动置顶;旧卡片可以删掉。${id ? `(消息 ID:${id})` : ''}`;
|
|
2051
|
+
}
|
|
2052
|
+
catch (error) {
|
|
2053
|
+
this.logger.warn('发卡片失败:%s', (0, util_1.errorText)(error));
|
|
2054
|
+
return `❌ 没有发出卡片:${(0, util_1.errorText)(error)}。请确认机器人在验证频道有「发送消息」权限。`;
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
1230
2057
|
async resume(actor) {
|
|
1231
2058
|
await this.ready;
|
|
1232
2059
|
if (!this._paused)
|
|
@@ -1240,6 +2067,7 @@ class Guard {
|
|
|
1240
2067
|
}
|
|
1241
2068
|
async patrolNow() {
|
|
1242
2069
|
this.failures = new kook_1.FailureLog(); // an operator who runs a patrol has probably fixed a permission: try everything again
|
|
2070
|
+
this.corpGroupReset = true; // ... and half-made groups that were given up on are tried again
|
|
1243
2071
|
await this.saveFailures();
|
|
1244
2072
|
return this.requestPatrol();
|
|
1245
2073
|
}
|
|
@@ -1274,6 +2102,30 @@ class Guard {
|
|
|
1274
2102
|
const removed = await this.link.forceUnlink(kookId, actor);
|
|
1275
2103
|
return removed ? `已解除 ${await this.displayName(kookId)} 和 QQ ${(0, notifier_1.maskQq)(removed.qq)} 的关联,身份组按「失去关联」处理。` : '没有找到这个关联。';
|
|
1276
2104
|
}
|
|
2105
|
+
/** One line saying which whitelist the person is on (nothing when none). Roles come from a live lookup. */
|
|
2106
|
+
async whitelistLine(kookId, qq) {
|
|
2107
|
+
const pc = (0, config_1.toPolicyConfig)(this.config);
|
|
2108
|
+
if (pc.whitelist.includes(kookId))
|
|
2109
|
+
return '白名单:KOOK ID';
|
|
2110
|
+
let roles = null;
|
|
2111
|
+
let failed = false; // only a failed lookup is worth a hint: null means the person is not in the server
|
|
2112
|
+
if (pc.whitelistRoles.length) {
|
|
2113
|
+
try {
|
|
2114
|
+
roles = (await this.kookApi()?.getMember(this.config.guildId, kookId))?.roles ?? null;
|
|
2115
|
+
}
|
|
2116
|
+
catch {
|
|
2117
|
+
failed = true;
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
const hit = (0, policy_1.whitelistHit)(pc, kookId, roles ?? [], qq);
|
|
2121
|
+
if (hit?.kind === 'qq')
|
|
2122
|
+
return '白名单:QQ 白名单';
|
|
2123
|
+
if (hit?.kind === 'role') {
|
|
2124
|
+
const name = (await this.getRoles().catch(() => [])).find((r) => r.id === hit.roleId)?.name;
|
|
2125
|
+
return `白名单:身份组「${name || hit.roleId}」`;
|
|
2126
|
+
}
|
|
2127
|
+
return failed ? '白名单:读不到身份组,没法核对身份组白名单' : null;
|
|
2128
|
+
}
|
|
1277
2129
|
async inspect(target, options = {}) {
|
|
1278
2130
|
await this.ready;
|
|
1279
2131
|
const showQq = (qq) => (options.full ? qq : (0, notifier_1.maskQq)(qq)); // a group may read along: only a private chat gets the full number
|
|
@@ -1283,14 +2135,21 @@ class Guard {
|
|
|
1283
2135
|
const record = await this.store.member(this.config.guildId, kookId);
|
|
1284
2136
|
const lines = [`KOOK:${await this.displayName(kookId)}(${kookId})`];
|
|
1285
2137
|
lines.push(link ? `关联的 QQ:${showQq(link.qq)}(${(0, util_1.formatBeijing)(link.linkedAt)} 关联)` : '关联的 QQ:没有');
|
|
2138
|
+
const whitelistLine = await this.whitelistLine(kookId, link?.qq ?? null);
|
|
2139
|
+
if (whitelistLine)
|
|
2140
|
+
lines.push(whitelistLine);
|
|
2141
|
+
let memberResult;
|
|
1286
2142
|
if (link && (await this.ensureGroups())) {
|
|
1287
2143
|
const judgement = await this.judge([link.qq]);
|
|
2144
|
+
memberResult = judgement.member.get(link.qq);
|
|
1288
2145
|
const show = (name, r) => `- ${name}:${r ? (r.decision === 'allow' ? '合格' : r.decision === 'deny' ? `不合格(${(0, texts_1.reasonShort)(r.reason)})` : `无法判断(${r.reason})`) : '没有结果'}`;
|
|
1289
2146
|
lines.push('现在向 AA 问到的结果:');
|
|
1290
2147
|
lines.push(show('成员', judgement.member.get(link.qq)));
|
|
1291
2148
|
for (const [roleId, results] of judgement.roles)
|
|
1292
2149
|
lines.push(show(this.roleName(roleId), results.get(link.qq)));
|
|
1293
2150
|
}
|
|
2151
|
+
if (this.config.corpRoles)
|
|
2152
|
+
lines.push(...(await this.corpInspectLines(kookId, memberResult)));
|
|
1294
2153
|
if (record) {
|
|
1295
2154
|
lines.push(record.deadline
|
|
1296
2155
|
? `倒计时:${(0, util_1.formatBeijing)(record.deadline)} 到期(${record.deadlineWhy},${(0, texts_1.reasonShort)(record.reason || 'NOT_LINKED')})|最后提醒:${record.finalRemindedAt ? (0, util_1.formatBeijing)(record.finalRemindedAt) : '还没发'}${record.releasedKick || record.releasedRevoke ? '|已放行' : ''}`
|
|
@@ -1302,6 +2161,38 @@ class Guard {
|
|
|
1302
2161
|
}
|
|
1303
2162
|
return lines.join('\n');
|
|
1304
2163
|
}
|
|
2164
|
+
/** Lines for kookaa.check: the corp ticker from the card, and the corp roles the person holds (live lookup). */
|
|
2165
|
+
async corpInspectLines(kookId, result) {
|
|
2166
|
+
const ticker = result?.decision === 'allow' ? (0, corp_1.parseTicker)(result.card) : null;
|
|
2167
|
+
const lines = [`军团简称:${ticker ?? (result?.decision === 'allow' ? '没解析到' : '没有(成员判定不是合格,或没有结果)')}`];
|
|
2168
|
+
const mapping = await this.readCorpMap();
|
|
2169
|
+
let held;
|
|
2170
|
+
try {
|
|
2171
|
+
const member = await this.kookApi()?.getMember(this.config.guildId, kookId);
|
|
2172
|
+
if (!member)
|
|
2173
|
+
return [...lines, '军团身份组:读不到这个人在服务器里的身份组'];
|
|
2174
|
+
held = member.roles;
|
|
2175
|
+
}
|
|
2176
|
+
catch {
|
|
2177
|
+
return [...lines, '军团身份组:读不到这个人在服务器里的身份组'];
|
|
2178
|
+
}
|
|
2179
|
+
const heldTickers = Object.entries(mapping).filter(([, id]) => held.includes(id)).map(([t]) => t);
|
|
2180
|
+
const nameOf = (t) => (0, corp_1.renderCorpRoleName)(this.config.corpRoleName, t);
|
|
2181
|
+
if ((0, config_1.corpChannelsOn)(this.config) && ticker) {
|
|
2182
|
+
const entry = (await this.readCorpChannels())[(0, corp_1.tickerKey)(ticker)];
|
|
2183
|
+
lines.push(`军团分组:${!entry ? '还没建' : entry.deleted ? '已被删除,不再重建' : entry.adopted ? '沿用了服务器里已有的同名分组' : entry.stopped ? '没建全,已停止补建' : entry.done ? '已建' : '没建全,下一轮继续补'}`);
|
|
2184
|
+
}
|
|
2185
|
+
if (ticker) {
|
|
2186
|
+
lines.push(`军团身份组:${nameOf(ticker)}(${!mapping[ticker] ? '还没建' : held.includes(mapping[ticker]) ? '已持有' : '未持有'})`);
|
|
2187
|
+
const others = heldTickers.filter((t) => t !== ticker);
|
|
2188
|
+
if (others.length)
|
|
2189
|
+
lines.push(`持有的其他军团身份组:${others.map(nameOf).join('、')}`);
|
|
2190
|
+
}
|
|
2191
|
+
else {
|
|
2192
|
+
lines.push(`军团身份组:${heldTickers.length ? `持有 ${heldTickers.map(nameOf).join('、')}` : '没有'}`);
|
|
2193
|
+
}
|
|
2194
|
+
return lines;
|
|
2195
|
+
}
|
|
1305
2196
|
configErrorsText() {
|
|
1306
2197
|
return this.configErrors().join(';');
|
|
1307
2198
|
}
|
|
@@ -1330,6 +2221,19 @@ class Guard {
|
|
|
1330
2221
|
const cursor = await store.getKv(store_1.kvKeys.cursor(config.aaBaseUrl));
|
|
1331
2222
|
lines.push(`事件游标:${cursor ?? '还没有'}`);
|
|
1332
2223
|
lines.push(`本分钟 AA 调用:${this.aa.callsInWindow()} / ${config.aaPerMinute}`);
|
|
2224
|
+
const wl = (0, config_1.toPolicyConfig)(config);
|
|
2225
|
+
if (wl.whitelist.length || wl.whitelistRoles.length || wl.qqWhitelist.length) {
|
|
2226
|
+
lines.push(`白名单:KOOK ID ${wl.whitelist.length} 个|身份组 ${wl.whitelistRoles.length} 个|QQ ${wl.qqWhitelist.length} 个`);
|
|
2227
|
+
if (wl.whitelistRoles.length) {
|
|
2228
|
+
const known = await this.getRoles().catch(() => null);
|
|
2229
|
+
const names = wl.whitelistRoles.map((id) => (known ? known.find((r) => r.id === id)?.name ?? `${id}(不存在)` : id));
|
|
2230
|
+
lines.push(`白名单身份组:${names.join('、')}`);
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
if (config.corpRoles)
|
|
2234
|
+
lines.push(`军团身份组:已映射 ${Object.keys(await this.readCorpMap()).length} 个`);
|
|
2235
|
+
if (config.corpChannels)
|
|
2236
|
+
lines.push((0, config_1.corpChannelsOn)(config) ? `军团分组:${this.corpGroupSummary(Object.values(await this.readCorpChannels()))}` : '军团分组:没有生效(要同时打开 corpRoles)');
|
|
1333
2237
|
const counting = await store.countingMembers(guildId);
|
|
1334
2238
|
lines.push(`倒计时中:${counting.length} 人|服务器人数(上次完整巡检):${(await store.getKv(store_1.kvKeys.memberCount(guildId))) ?? '未知'}`);
|
|
1335
2239
|
return lines.join('\n');
|