@mushinjs/plugin-bots 0.0.0-stage → 0.2.0-next.20261113103537
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/LICENSE +21 -0
- package/dist/archive.d.ts +61 -0
- package/dist/archive.js +149 -0
- package/dist/archive.js.map +1 -0
- package/dist/bot.d.ts +183 -0
- package/dist/bot.js +552 -0
- package/dist/bot.js.map +1 -0
- package/dist/commands.d.ts +119 -0
- package/dist/commands.js +186 -0
- package/dist/commands.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/manager.d.ts +458 -0
- package/dist/manager.js +1144 -0
- package/dist/manager.js.map +1 -0
- package/dist/types.d.ts +161 -0
- package/dist/types.js +27 -0
- package/dist/types.js.map +1 -0
- package/package.json +57 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Setobox
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Context, MessageRecord } from "@mushinjs/core";
|
|
2
|
+
declare module 'minato' {
|
|
3
|
+
interface Tables {
|
|
4
|
+
bots_message: MessageRow;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
/** A message record as a row: the channel and user flattened so they can be filtered and indexed. */
|
|
8
|
+
export interface MessageRow {
|
|
9
|
+
id: string;
|
|
10
|
+
bot: string;
|
|
11
|
+
messageId: string;
|
|
12
|
+
direction: string;
|
|
13
|
+
channelType: string;
|
|
14
|
+
channelId: string;
|
|
15
|
+
channelName: string;
|
|
16
|
+
fromGroup: string;
|
|
17
|
+
userId: string;
|
|
18
|
+
userName: string;
|
|
19
|
+
userRole: string;
|
|
20
|
+
/** Plain text, for searching. */
|
|
21
|
+
text: string;
|
|
22
|
+
segments: any;
|
|
23
|
+
type: string;
|
|
24
|
+
platforms: any;
|
|
25
|
+
source: any;
|
|
26
|
+
replyTo: string;
|
|
27
|
+
timestamp: number;
|
|
28
|
+
}
|
|
29
|
+
export declare function toRow(record: MessageRecord): MessageRow;
|
|
30
|
+
export declare function fromRow(row: MessageRow): MessageRecord;
|
|
31
|
+
export interface MessageQuery {
|
|
32
|
+
limit: number;
|
|
33
|
+
channel?: string;
|
|
34
|
+
/** Only messages sent before this time (ms). */
|
|
35
|
+
before?: number;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Message records in the `bots_message` table, next to the daily JSONL files that are always
|
|
39
|
+
* written. Created when the database plugin runs; imports the JSONL lines it does not have yet.
|
|
40
|
+
*/
|
|
41
|
+
export declare class MessageArchive {
|
|
42
|
+
private ctx;
|
|
43
|
+
private onError;
|
|
44
|
+
/** False until the JSONL import is done; until then the JSONL files answer queries. */
|
|
45
|
+
ready: boolean;
|
|
46
|
+
private pending;
|
|
47
|
+
/** Records that arrived during the import, saved right after it. */
|
|
48
|
+
private queued;
|
|
49
|
+
constructor(ctx: Context, onError: (error: unknown) => void);
|
|
50
|
+
/** Imports the JSONL files, then saves what arrived meanwhile. Returns how many lines were imported. */
|
|
51
|
+
start(): Promise<number>;
|
|
52
|
+
add(record: MessageRecord): void;
|
|
53
|
+
/** The newest messages of a bot that match, oldest first. */
|
|
54
|
+
query(bot: string, options: MessageQuery): Promise<MessageRecord[]>;
|
|
55
|
+
/**
|
|
56
|
+
* Imports the daily JSONL files under `messages/<bot>/` that hold messages newer than the newest
|
|
57
|
+
* stored for that bot: everything the first time, then whatever was written while the database
|
|
58
|
+
* plugin was off. The files stay where they are.
|
|
59
|
+
*/
|
|
60
|
+
private importLogs;
|
|
61
|
+
}
|
package/dist/archive.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { messageType, segmentsToText } from "@mushinjs/core";
|
|
2
|
+
import { readdir } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { $ } from "minato";
|
|
5
|
+
// src/archive.ts
|
|
6
|
+
function toRow(record) {
|
|
7
|
+
return {
|
|
8
|
+
id: record.id,
|
|
9
|
+
bot: record.botId,
|
|
10
|
+
messageId: record.messageId ?? "",
|
|
11
|
+
direction: record.direction,
|
|
12
|
+
channelType: record.channel.type,
|
|
13
|
+
channelId: record.channel.id,
|
|
14
|
+
channelName: record.channel.name ?? "",
|
|
15
|
+
fromGroup: record.channel.fromGroup ?? "",
|
|
16
|
+
userId: record.user.id,
|
|
17
|
+
userName: record.user.name ?? "",
|
|
18
|
+
userRole: record.user.role ?? "",
|
|
19
|
+
text: segmentsToText(record.segments ?? []),
|
|
20
|
+
segments: record.segments ?? [],
|
|
21
|
+
type: record.type ?? messageType(record.segments ?? []),
|
|
22
|
+
platforms: record.platforms ?? [],
|
|
23
|
+
source: record.source ?? { kind: "user" },
|
|
24
|
+
replyTo: record.replyTo ?? "",
|
|
25
|
+
timestamp: record.timestamp
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function fromRow(row) {
|
|
29
|
+
return {
|
|
30
|
+
id: row.id,
|
|
31
|
+
botId: row.bot,
|
|
32
|
+
...row.messageId ? { messageId: row.messageId } : {},
|
|
33
|
+
direction: row.direction,
|
|
34
|
+
channel: {
|
|
35
|
+
type: row.channelType,
|
|
36
|
+
id: row.channelId,
|
|
37
|
+
...row.channelName ? { name: row.channelName } : {},
|
|
38
|
+
...row.fromGroup ? { fromGroup: row.fromGroup } : {}
|
|
39
|
+
},
|
|
40
|
+
user: {
|
|
41
|
+
id: row.userId,
|
|
42
|
+
...row.userName ? { name: row.userName } : {},
|
|
43
|
+
...row.userRole ? { role: row.userRole } : {}
|
|
44
|
+
},
|
|
45
|
+
segments: row.segments ?? [],
|
|
46
|
+
timestamp: row.timestamp,
|
|
47
|
+
...row.replyTo ? { replyTo: row.replyTo } : {},
|
|
48
|
+
type: row.type,
|
|
49
|
+
platforms: row.platforms ?? [],
|
|
50
|
+
source: row.source ?? { kind: "user" }
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
const IMPORT_BATCH = 500;
|
|
54
|
+
/**
|
|
55
|
+
* Message records in the `bots_message` table, next to the daily JSONL files that are always
|
|
56
|
+
* written. Created when the database plugin runs; imports the JSONL lines it does not have yet.
|
|
57
|
+
*/
|
|
58
|
+
var MessageArchive = class {
|
|
59
|
+
ctx;
|
|
60
|
+
onError;
|
|
61
|
+
/** False until the JSONL import is done; until then the JSONL files answer queries. */
|
|
62
|
+
ready = false;
|
|
63
|
+
pending = /* @__PURE__ */ new Set();
|
|
64
|
+
/** Records that arrived during the import, saved right after it. */
|
|
65
|
+
queued = [];
|
|
66
|
+
constructor(ctx, onError) {
|
|
67
|
+
this.ctx = ctx;
|
|
68
|
+
this.onError = onError;
|
|
69
|
+
ctx.model.extend("bots_message", {
|
|
70
|
+
id: "string",
|
|
71
|
+
bot: "string",
|
|
72
|
+
messageId: "string",
|
|
73
|
+
direction: "string",
|
|
74
|
+
channelType: "string",
|
|
75
|
+
channelId: "string",
|
|
76
|
+
channelName: "string",
|
|
77
|
+
fromGroup: "string",
|
|
78
|
+
userId: "string",
|
|
79
|
+
userName: "string",
|
|
80
|
+
userRole: "string",
|
|
81
|
+
text: "text",
|
|
82
|
+
segments: "json",
|
|
83
|
+
type: "string",
|
|
84
|
+
platforms: "json",
|
|
85
|
+
source: "json",
|
|
86
|
+
replyTo: "string",
|
|
87
|
+
timestamp: "double"
|
|
88
|
+
}, {
|
|
89
|
+
primary: "id",
|
|
90
|
+
indexes: [["bot", "timestamp"], [
|
|
91
|
+
"bot",
|
|
92
|
+
"channelId",
|
|
93
|
+
"timestamp"
|
|
94
|
+
]]
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** Imports the JSONL files, then saves what arrived meanwhile. Returns how many lines were imported. */
|
|
98
|
+
async start() {
|
|
99
|
+
const imported = await this.importLogs();
|
|
100
|
+
const queued = this.queued.splice(0);
|
|
101
|
+
if (queued.length) await this.ctx.database.upsert("bots_message", queued.map(toRow));
|
|
102
|
+
this.ready = true;
|
|
103
|
+
return imported;
|
|
104
|
+
}
|
|
105
|
+
add(record) {
|
|
106
|
+
if (!this.ready) {
|
|
107
|
+
this.queued.push(record);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const task = this.ctx.database.create("bots_message", toRow(record)).catch(this.onError);
|
|
111
|
+
this.pending.add(task);
|
|
112
|
+
task.finally(() => this.pending.delete(task));
|
|
113
|
+
}
|
|
114
|
+
/** The newest messages of a bot that match, oldest first. */
|
|
115
|
+
async query(bot, options) {
|
|
116
|
+
await Promise.all(this.pending);
|
|
117
|
+
return (await this.ctx.database.select("bots_message", {
|
|
118
|
+
bot,
|
|
119
|
+
...options.channel ? { channelId: options.channel } : {},
|
|
120
|
+
...options.before ? { timestamp: { $lt: options.before } } : {}
|
|
121
|
+
}).orderBy("timestamp", "desc").limit(options.limit).execute()).reverse().map(fromRow);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Imports the daily JSONL files under `messages/<bot>/` that hold messages newer than the newest
|
|
125
|
+
* stored for that bot: everything the first time, then whatever was written while the database
|
|
126
|
+
* plugin was off. The files stay where they are.
|
|
127
|
+
*/
|
|
128
|
+
async importLogs() {
|
|
129
|
+
const root = join(this.ctx.storage.dir, "messages");
|
|
130
|
+
let imported = 0;
|
|
131
|
+
for (const bot of await readdir(root).catch(() => [])) {
|
|
132
|
+
const newest = Number(await this.ctx.database.select("bots_message", { bot }).execute((row) => $.max(row.timestamp))) || 0;
|
|
133
|
+
const since = newest ? new Date(newest).toISOString().slice(0, 10) : "";
|
|
134
|
+
const days = (await readdir(join(root, bot)).catch(() => [])).filter((name) => name.endsWith(".jsonl") && name.slice(0, -6) >= since).sort();
|
|
135
|
+
for (const day of days) {
|
|
136
|
+
const records = (await this.ctx.storage.tail(`messages/${bot}/${day.slice(0, -6)}`, Infinity)).filter((record) => record?.id && record.timestamp > newest);
|
|
137
|
+
for (let i = 0; i < records.length; i += IMPORT_BATCH) await this.ctx.database.upsert("bots_message", records.slice(i, i + IMPORT_BATCH).map((record) => toRow({
|
|
138
|
+
...record,
|
|
139
|
+
botId: record.botId ?? bot
|
|
140
|
+
})));
|
|
141
|
+
imported += records.length;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return imported;
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
export { MessageArchive, fromRow, toRow };
|
|
148
|
+
|
|
149
|
+
//# sourceMappingURL=archive.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"archive.js","names":[],"sources":["../src/archive.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { type Context, type MessageRecord, messageType, segmentsToText } from '@mushinjs/core'\nimport type {} from '@mushinjs/plugin-database'\nimport type {} from '@mushinjs/plugin-storage'\nimport { $ } from 'minato'\n\ndeclare module 'minato' {\n interface Tables {\n bots_message: MessageRow\n }\n}\n\n/** A message record as a row: the channel and user flattened so they can be filtered and indexed. */\nexport interface MessageRow {\n id: string\n bot: string\n messageId: string\n direction: string\n channelType: string\n channelId: string\n channelName: string\n fromGroup: string\n userId: string\n userName: string\n userRole: string\n /** Plain text, for searching. */\n text: string\n segments: any\n type: string\n platforms: any\n source: any\n replyTo: string\n timestamp: number\n}\n\nexport function toRow(record: MessageRecord): MessageRow {\n return {\n id: record.id,\n bot: record.botId,\n messageId: record.messageId ?? '',\n direction: record.direction,\n channelType: record.channel.type,\n channelId: record.channel.id,\n channelName: record.channel.name ?? '',\n fromGroup: record.channel.fromGroup ?? '',\n userId: record.user.id,\n userName: record.user.name ?? '',\n userRole: record.user.role ?? '',\n text: segmentsToText(record.segments ?? []),\n segments: record.segments ?? [],\n type: record.type ?? messageType(record.segments ?? []),\n platforms: record.platforms ?? [],\n source: record.source ?? { kind: 'user' },\n replyTo: record.replyTo ?? '',\n timestamp: record.timestamp,\n }\n}\n\nexport function fromRow(row: MessageRow): MessageRecord {\n return {\n id: row.id,\n botId: row.bot,\n ...(row.messageId ? { messageId: row.messageId } : {}),\n direction: row.direction as MessageRecord['direction'],\n channel: {\n type: row.channelType as 'group' | 'private',\n id: row.channelId,\n ...(row.channelName ? { name: row.channelName } : {}),\n ...(row.fromGroup ? { fromGroup: row.fromGroup } : {}),\n },\n user: {\n id: row.userId,\n ...(row.userName ? { name: row.userName } : {}),\n ...(row.userRole ? { role: row.userRole as 'owner' | 'admin' | 'member' } : {}),\n },\n segments: row.segments ?? [],\n timestamp: row.timestamp,\n ...(row.replyTo ? { replyTo: row.replyTo } : {}),\n type: row.type as MessageRecord['type'],\n platforms: row.platforms ?? [],\n source: row.source ?? { kind: 'user' },\n }\n}\n\nconst IMPORT_BATCH = 500\n\nexport interface MessageQuery {\n limit: number\n channel?: string\n /** Only messages sent before this time (ms). */\n before?: number\n}\n\n/**\n * Message records in the `bots_message` table, next to the daily JSONL files that are always\n * written. Created when the database plugin runs; imports the JSONL lines it does not have yet.\n */\nexport class MessageArchive {\n /** False until the JSONL import is done; until then the JSONL files answer queries. */\n ready = false\n private pending = new Set<Promise<unknown>>()\n /** Records that arrived during the import, saved right after it. */\n private queued: MessageRecord[] = []\n\n constructor(private ctx: Context, private onError: (error: unknown) => void) {\n ctx.model.extend('bots_message', {\n id: 'string',\n bot: 'string',\n messageId: 'string',\n direction: 'string',\n channelType: 'string',\n channelId: 'string',\n channelName: 'string',\n fromGroup: 'string',\n userId: 'string',\n userName: 'string',\n userRole: 'string',\n text: 'text',\n segments: 'json',\n type: 'string',\n platforms: 'json',\n source: 'json',\n replyTo: 'string',\n timestamp: 'double',\n }, { primary: 'id', indexes: [['bot', 'timestamp'], ['bot', 'channelId', 'timestamp']] })\n }\n\n /** Imports the JSONL files, then saves what arrived meanwhile. Returns how many lines were imported. */\n async start() {\n const imported = await this.importLogs()\n const queued = this.queued.splice(0)\n if (queued.length) await this.ctx.database.upsert('bots_message', queued.map(toRow))\n this.ready = true\n return imported\n }\n\n add(record: MessageRecord) {\n if (!this.ready) {\n this.queued.push(record)\n return\n }\n const task = this.ctx.database.create('bots_message', toRow(record)).catch(this.onError)\n this.pending.add(task)\n void task.finally(() => this.pending.delete(task))\n }\n\n /** The newest messages of a bot that match, oldest first. */\n async query(bot: string, options: MessageQuery): Promise<MessageRecord[]> {\n await Promise.all(this.pending)\n const rows = await this.ctx.database\n .select('bots_message', {\n bot,\n ...(options.channel ? { channelId: options.channel } : {}),\n ...(options.before ? { timestamp: { $lt: options.before } } : {}),\n })\n .orderBy('timestamp', 'desc')\n .limit(options.limit)\n .execute()\n return rows.reverse().map(fromRow)\n }\n\n /**\n * Imports the daily JSONL files under `messages/<bot>/` that hold messages newer than the newest\n * stored for that bot: everything the first time, then whatever was written while the database\n * plugin was off. The files stay where they are.\n */\n private async importLogs() {\n const root = join(this.ctx.storage.dir, 'messages')\n let imported = 0\n for (const bot of await readdir(root).catch(() => [] as string[])) {\n const newest = Number(await this.ctx.database.select('bots_message', { bot }).execute((row) => $.max(row.timestamp))) || 0\n const since = newest ? new Date(newest).toISOString().slice(0, 10) : ''\n const days = (await readdir(join(root, bot)).catch(() => [] as string[]))\n .filter((name) => name.endsWith('.jsonl') && name.slice(0, -'.jsonl'.length) >= since)\n .sort()\n for (const day of days) {\n const records = (await this.ctx.storage.tail<MessageRecord>(`messages/${bot}/${day.slice(0, -'.jsonl'.length)}`, Infinity))\n .filter((record) => record?.id && record.timestamp > newest)\n for (let i = 0; i < records.length; i += IMPORT_BATCH) {\n await this.ctx.database.upsert('bots_message', records.slice(i, i + IMPORT_BATCH).map((record) => toRow({ ...record, botId: record.botId ?? bot })))\n }\n imported += records.length\n }\n }\n return imported\n }\n}\n"],"mappings":";;;;;AAoCA,SAAgB,MAAM,QAAmC;CACvD,OAAO;EACL,IAAI,OAAO;EACX,KAAK,OAAO;EACZ,WAAW,OAAO,aAAa;EAC/B,WAAW,OAAO;EAClB,aAAa,OAAO,QAAQ;EAC5B,WAAW,OAAO,QAAQ;EAC1B,aAAa,OAAO,QAAQ,QAAQ;EACpC,WAAW,OAAO,QAAQ,aAAa;EACvC,QAAQ,OAAO,KAAK;EACpB,UAAU,OAAO,KAAK,QAAQ;EAC9B,UAAU,OAAO,KAAK,QAAQ;EAC9B,MAAM,eAAe,OAAO,YAAY,CAAC,CAAC;EAC1C,UAAU,OAAO,YAAY,CAAC;EAC9B,MAAM,OAAO,QAAQ,YAAY,OAAO,YAAY,CAAC,CAAC;EACtD,WAAW,OAAO,aAAa,CAAC;EAChC,QAAQ,OAAO,UAAU,EAAE,MAAM,OAAO;EACxC,SAAS,OAAO,WAAW;EAC3B,WAAW,OAAO;CACpB;AACF;AAEA,SAAgB,QAAQ,KAAgC;CACtD,OAAO;EACL,IAAI,IAAI;EACR,OAAO,I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AAM,GAAG,EAAE,IAAI;GACrE,MAAM,QAAQ,MAAM,QAAQ,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,CAAa,EAAA,CACpE,QAAQ,SAAS,KAAK,SAAS,QAAQ,KAAK,KAAK,MAAM,GAAG,EAAgB,KAAK,KAAK,CAAC,CACrF,KAAK;GACR,KAAK,MAAM,OAAO,MAAM;IACtB,MAAM,WAAW,MAAM,KAAK,IAAI,QAAQ,KAAoB,YAAY,IAAI,GAAG,IAAI,MAAM,GAAG,EAAgB,KAAK,QAAQ,EAAA,CACtH,QAAQ,WAAW,QAAQ,MAAM,OAAO,YAAY,MAAM;IAC7D,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,cACvC,MAAM,KAAK,IAAI,SAAS,OAAO,gBAAgB,QAAQ,MAAM,GAAG,IAAI,YAAY,CAAC,CAAC,KAAK,WAAW,MAAM;KAAE,GAAG;KAAQ,OAAO,OAAO,SAAS;IAAI,CAAC,CAAC,CAAC;IAErJ,YAAY,QAAQ;GACtB;EACF;EACA,OAAO;CACT;AACF"}
|
package/dist/bot.d.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { BotEvent, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, ResolvedMedia, SourcedContent, Transport } from "./types.js";
|
|
2
|
+
import { ArgValue, CommandDef, CommandEntry, ParsedCommand } from "./commands.js";
|
|
3
|
+
import { ChannelInfo, Content, Context, MessageRecord, Provenance, Segment, Service, UsageScope, UserInfo } from "@mushinjs/core";
|
|
4
|
+
export type Sendable = Content | SourcedContent;
|
|
5
|
+
export type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void;
|
|
6
|
+
export interface MiddlewareOptions {
|
|
7
|
+
/** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */
|
|
8
|
+
priority?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */
|
|
11
|
+
export interface BotHooks {
|
|
12
|
+
record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord;
|
|
13
|
+
status(bot: Bot): void;
|
|
14
|
+
/** Every command registered on this bot, from flows, plugins and the built-in help. */
|
|
15
|
+
commands?(bot: Bot): CommandEntry[];
|
|
16
|
+
/** A message ran a registered command. */
|
|
17
|
+
commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void;
|
|
18
|
+
/** The answer to a built-in command such as `/help`. */
|
|
19
|
+
builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined;
|
|
20
|
+
/** The sender's role on this bot; nothing when the permissions plugin is not running. */
|
|
21
|
+
roleOf?(bot: Bot, userId: string): BotRole | undefined;
|
|
22
|
+
/** A command that an app plugin answers on every bot, such as `/persona`. */
|
|
23
|
+
appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined;
|
|
24
|
+
/** Where the costs of handling a message go; see `usage` in core. */
|
|
25
|
+
usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined;
|
|
26
|
+
/** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */
|
|
27
|
+
sent?(bot: Bot, record: MessageRecord, transfer: {
|
|
28
|
+
bytes: number;
|
|
29
|
+
ms?: number;
|
|
30
|
+
cause?: string;
|
|
31
|
+
}): void;
|
|
32
|
+
}
|
|
33
|
+
export type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown;
|
|
34
|
+
/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */
|
|
35
|
+
export declare const BUILTIN_PRIORITY = 5;
|
|
36
|
+
/** One incoming message, as seen by a bot plugin's middleware. */
|
|
37
|
+
export declare class Session {
|
|
38
|
+
bot: Bot;
|
|
39
|
+
record: MessageRecord;
|
|
40
|
+
/** Name of the plugin whose middleware is handling this session; replies are attributed to it. */
|
|
41
|
+
plugin?: string;
|
|
42
|
+
private parsed?;
|
|
43
|
+
constructor(bot: Bot, record: MessageRecord);
|
|
44
|
+
get channel(): ChannelInfo;
|
|
45
|
+
get user(): UserInfo;
|
|
46
|
+
get segments(): Segment[];
|
|
47
|
+
get isDirect(): boolean;
|
|
48
|
+
/** True when the message @-mentions this bot. */
|
|
49
|
+
get mentioned(): boolean;
|
|
50
|
+
/** The command this message runs, such as `/score 85`, split by the bot's prefixes. */
|
|
51
|
+
get command(): ParsedCommand | undefined;
|
|
52
|
+
/** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */
|
|
53
|
+
role(): BotRole | undefined;
|
|
54
|
+
/** The sender's role in this group, when the adapter can tell; nothing in private chats. */
|
|
55
|
+
groupRole(): Promise<GroupRole | undefined>;
|
|
56
|
+
/** True when the sender is an admin or master of the bot, who may run admin-only commands. */
|
|
57
|
+
get isAdmin(): boolean;
|
|
58
|
+
/** Plain text with mentions of this bot removed. */
|
|
59
|
+
get text(): string;
|
|
60
|
+
send(content: Sendable): Promise<MessageRecord | undefined>;
|
|
61
|
+
/** Sends with a reply reference to the incoming message, when the platform supports it. */
|
|
62
|
+
reply(content: Sendable): Promise<MessageRecord | undefined>;
|
|
63
|
+
/** A view of this session attributed to another plugin. */
|
|
64
|
+
as(plugin: string): Session;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin
|
|
68
|
+
* always means that plugin's bot.
|
|
69
|
+
*/
|
|
70
|
+
export declare class Bot extends Service {
|
|
71
|
+
status: BotStatus;
|
|
72
|
+
error?: string;
|
|
73
|
+
selfId?: string;
|
|
74
|
+
selfName?: string;
|
|
75
|
+
/** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */
|
|
76
|
+
selfAvatar?: string;
|
|
77
|
+
record: BotRecord;
|
|
78
|
+
private hooks;
|
|
79
|
+
private transport?;
|
|
80
|
+
private middlewares;
|
|
81
|
+
private eventHandlers;
|
|
82
|
+
private ownCommands;
|
|
83
|
+
private commandProviders;
|
|
84
|
+
private roleResolver?;
|
|
85
|
+
private mediaResolver?;
|
|
86
|
+
private contactResolver?;
|
|
87
|
+
constructor(ctx: Context, config: {
|
|
88
|
+
record: BotRecord;
|
|
89
|
+
hooks: BotHooks;
|
|
90
|
+
});
|
|
91
|
+
get id(): string;
|
|
92
|
+
get platform(): string;
|
|
93
|
+
setStatus(status: BotStatus, error?: string): void;
|
|
94
|
+
setSelf(id: string, name?: string, avatar?: string): void;
|
|
95
|
+
/** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */
|
|
96
|
+
useTransport(transport: Transport): import("cordis").Disposable<Promise<void>>;
|
|
97
|
+
/** Called by adapters that can tell a sender's group role (owner, admin, member). */
|
|
98
|
+
useRoleResolver(resolver: GroupRoleResolver): import("cordis").Disposable<Promise<void>>;
|
|
99
|
+
/** Called by adapters that can fetch a message's media and forwarded chat histories. */
|
|
100
|
+
useMediaResolver(resolver: MediaResolver): import("cordis").Disposable<Promise<void>>;
|
|
101
|
+
/** Called by adapters that can list the account's friends and groups. */
|
|
102
|
+
useContacts(resolver: ContactResolver): import("cordis").Disposable<Promise<void>>;
|
|
103
|
+
/** The account's friends and groups; empty when the adapter cannot list them. */
|
|
104
|
+
contacts(): Promise<never[] | Contact[]>;
|
|
105
|
+
/**
|
|
106
|
+
* A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A
|
|
107
|
+
* leading "@" mentions the bot. Replies stay in the sandbox and never reach the platform.
|
|
108
|
+
*/
|
|
109
|
+
sandbox(text: string): void;
|
|
110
|
+
/** An address for an image, video, voice or file segment; see `MediaResolver.media`. */
|
|
111
|
+
media(segment: Segment, options?: {
|
|
112
|
+
channel?: ChannelInfo;
|
|
113
|
+
inline?: boolean;
|
|
114
|
+
}): Promise<ResolvedMedia | undefined>;
|
|
115
|
+
/** The messages of a forwarded chat history. */
|
|
116
|
+
forward(id: string): Promise<ForwardedMessage[]>;
|
|
117
|
+
/** The user's role on this bot, from the permissions plugin; nothing when it is not running. */
|
|
118
|
+
roleOf(userId: string): BotRole | undefined;
|
|
119
|
+
/** A sender's group role: from the message when the platform sent it, else from the adapter. */
|
|
120
|
+
groupRoleOf(target: {
|
|
121
|
+
channel: ChannelInfo;
|
|
122
|
+
user: {
|
|
123
|
+
id: string;
|
|
124
|
+
role?: GroupRole;
|
|
125
|
+
};
|
|
126
|
+
}): Promise<GroupRole | undefined>;
|
|
127
|
+
/** Whether a command's role requirement lets this session run it; logs why not. */
|
|
128
|
+
allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session): boolean;
|
|
129
|
+
/** Registers middleware for incoming messages; runs in registration order. */
|
|
130
|
+
middleware(callback: Middleware, options?: MiddlewareOptions): import("cordis").Disposable<Promise<void>>;
|
|
131
|
+
get prefixes(): string[];
|
|
132
|
+
/**
|
|
133
|
+
* Splits text into a command, with the registered command it names. Commands with prefixes of
|
|
134
|
+
* their own (such as `#`) are matched by those only; the rest by the bot's prefixes.
|
|
135
|
+
*/
|
|
136
|
+
parseCommand(text: string): ParsedCommand | undefined;
|
|
137
|
+
/** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */
|
|
138
|
+
localCommands(): CommandEntry[];
|
|
139
|
+
/**
|
|
140
|
+
* Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,
|
|
141
|
+
* so they show in `/help` and the command list. Removed when the calling plugin unloads.
|
|
142
|
+
*/
|
|
143
|
+
defineCommands(provider: () => CommandEntry[]): import("cordis").Disposable<Promise<void>>;
|
|
144
|
+
/**
|
|
145
|
+
* Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.
|
|
146
|
+
* It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot
|
|
147
|
+
* replies with how to write the command.
|
|
148
|
+
*/
|
|
149
|
+
command(def: CommandDef, handler: CommandHandler): import("cordis").Disposable<Promise<void>>;
|
|
150
|
+
/** The plugins whose middleware sees incoming messages, in the order they see them. */
|
|
151
|
+
middlewareOrder(): {
|
|
152
|
+
plugin: string;
|
|
153
|
+
priority: number;
|
|
154
|
+
}[];
|
|
155
|
+
/** Listens for adapter events that are not messages (notices, requests). */
|
|
156
|
+
onEvent(handler: (event: BotEvent) => void): import("cordis").Disposable<Promise<void>>;
|
|
157
|
+
/** Called by adapters for non-message events. */
|
|
158
|
+
dispatchEvent(event: BotEvent): void;
|
|
159
|
+
/** Called by adapters for each incoming message: records it, then runs the middleware chain. */
|
|
160
|
+
receive(message: IncomingMessage, options?: {
|
|
161
|
+
source?: Provenance;
|
|
162
|
+
}): Promise<Session>;
|
|
163
|
+
/**
|
|
164
|
+
* A notice or request from the platform (a poke, a member joining, a recall…) as a line in the
|
|
165
|
+
* bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.
|
|
166
|
+
*/
|
|
167
|
+
private logEvent;
|
|
168
|
+
/** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */
|
|
169
|
+
private logUsage;
|
|
170
|
+
/** Sends a message from a plugin; the reply is attributed to the calling plugin. */
|
|
171
|
+
send(channel: ChannelInfo, content: Sendable, options?: {
|
|
172
|
+
source?: Provenance;
|
|
173
|
+
}): Promise<MessageRecord | undefined>;
|
|
174
|
+
/** Raw adapter API, e.g. a NapCat extension action. */
|
|
175
|
+
call(action: string, params?: Record<string, any>): Promise<any>;
|
|
176
|
+
deliver(channel: ChannelInfo, content: Sendable, options: {
|
|
177
|
+
plugin?: string;
|
|
178
|
+
source?: Provenance;
|
|
179
|
+
replyTo?: string;
|
|
180
|
+
}): Promise<MessageRecord | undefined>;
|
|
181
|
+
}
|
|
182
|
+
/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */
|
|
183
|
+
export declare function byteSize(segments: Segment[]): number;
|