@owlmeans/bot-whatsapp 0.0.0-stage → 0.2.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/README.md +74 -2
- package/agent-meta/manifest.json +16 -0
- package/agent-meta/skills/bot-whatsapp/SKILL.md +104 -0
- package/build/api.d.ts +7 -0
- package/build/api.d.ts.map +1 -0
- package/build/api.js +50 -0
- package/build/api.js.map +1 -0
- package/build/append.d.ts +10 -0
- package/build/append.d.ts.map +1 -0
- package/build/append.js +13 -0
- package/build/append.js.map +1 -0
- package/build/consts.d.ts +57 -0
- package/build/consts.d.ts.map +1 -0
- package/build/consts.js +183 -0
- package/build/consts.js.map +1 -0
- package/build/errors.d.ts +22 -0
- package/build/errors.d.ts.map +1 -0
- package/build/errors.js +34 -0
- package/build/errors.js.map +1 -0
- package/build/index.d.ts +7 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +6 -0
- package/build/index.js.map +1 -0
- package/build/mock.d.ts +9 -0
- package/build/mock.d.ts.map +1 -0
- package/build/mock.js +198 -0
- package/build/mock.js.map +1 -0
- package/build/normalize.d.ts +4 -0
- package/build/normalize.d.ts.map +1 -0
- package/build/normalize.js +109 -0
- package/build/normalize.js.map +1 -0
- package/build/plugin.d.ts +13 -0
- package/build/plugin.d.ts.map +1 -0
- package/build/plugin.js +147 -0
- package/build/plugin.js.map +1 -0
- package/build/signature.d.ts +4 -0
- package/build/signature.d.ts.map +1 -0
- package/build/signature.js +20 -0
- package/build/signature.js.map +1 -0
- package/build/types.d.ts +179 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/package.json +56 -4
- package/src/api.ts +62 -0
- package/src/append.ts +18 -0
- package/src/consts.ts +206 -0
- package/src/errors.ts +37 -0
- package/src/index.ts +6 -0
- package/src/mock.ts +243 -0
- package/src/normalize.ts +131 -0
- package/src/plugin.ts +183 -0
- package/src/signature.ts +27 -0
- package/src/types.ts +174 -0
- package/tests/context.ts +85 -0
- package/tests/descriptor.spec.ts +64 -0
- package/tests/mock-ids.spec.ts +38 -0
- package/tests/tsconfig.json +12 -0
- package/tests/whatsapp.spec.ts +485 -0
- package/tsconfig.json +16 -0
package/build/types.d.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import type { BotConnection } from '@owlmeans/bot';
|
|
2
|
+
import type { BotHookRequest } from '@owlmeans/server-bot';
|
|
3
|
+
import type { BotNormalizedUpdate, BotPlatformConnection, BotPlatformMock, BotPlatformSession } from '@owlmeans/server-bot';
|
|
4
|
+
export interface WhatsAppMetadata {
|
|
5
|
+
display_phone_number: string;
|
|
6
|
+
phone_number_id: string;
|
|
7
|
+
}
|
|
8
|
+
export interface WhatsAppContact {
|
|
9
|
+
profile?: {
|
|
10
|
+
name?: string;
|
|
11
|
+
};
|
|
12
|
+
wa_id: string;
|
|
13
|
+
}
|
|
14
|
+
/** The quoted message (a reply), or a forwarded flag. */
|
|
15
|
+
export interface WhatsAppContext {
|
|
16
|
+
/** Who wrote the quoted message — the business number when it is the bot's. */
|
|
17
|
+
from?: string;
|
|
18
|
+
id?: string;
|
|
19
|
+
forwarded?: boolean;
|
|
20
|
+
frequently_forwarded?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface WhatsAppInteractive {
|
|
23
|
+
type: 'button_reply' | 'list_reply' | string;
|
|
24
|
+
button_reply?: {
|
|
25
|
+
id: string;
|
|
26
|
+
title: string;
|
|
27
|
+
};
|
|
28
|
+
list_reply?: {
|
|
29
|
+
id: string;
|
|
30
|
+
title: string;
|
|
31
|
+
description?: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export interface WhatsAppMedia {
|
|
35
|
+
id?: string;
|
|
36
|
+
caption?: string;
|
|
37
|
+
mime_type?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface WhatsAppMessage {
|
|
40
|
+
/** The customer's WhatsApp id (`wa_id`). */
|
|
41
|
+
from: string;
|
|
42
|
+
/** `wamid.…` */
|
|
43
|
+
id: string;
|
|
44
|
+
/** Unix seconds, as text. */
|
|
45
|
+
timestamp: string;
|
|
46
|
+
type: string;
|
|
47
|
+
text?: {
|
|
48
|
+
body: string;
|
|
49
|
+
};
|
|
50
|
+
interactive?: WhatsAppInteractive;
|
|
51
|
+
/** A template's quick-reply button. */
|
|
52
|
+
button?: {
|
|
53
|
+
text?: string;
|
|
54
|
+
payload?: string;
|
|
55
|
+
};
|
|
56
|
+
image?: WhatsAppMedia;
|
|
57
|
+
video?: WhatsAppMedia;
|
|
58
|
+
document?: WhatsAppMedia;
|
|
59
|
+
context?: WhatsAppContext;
|
|
60
|
+
}
|
|
61
|
+
/** A delivery receipt of a message the business sent. */
|
|
62
|
+
export interface WhatsAppStatus {
|
|
63
|
+
id: string;
|
|
64
|
+
status: string;
|
|
65
|
+
timestamp: string;
|
|
66
|
+
recipient_id: string;
|
|
67
|
+
}
|
|
68
|
+
export interface WhatsAppValue {
|
|
69
|
+
messaging_product: string;
|
|
70
|
+
metadata: WhatsAppMetadata;
|
|
71
|
+
contacts?: WhatsAppContact[];
|
|
72
|
+
messages?: WhatsAppMessage[];
|
|
73
|
+
statuses?: WhatsAppStatus[];
|
|
74
|
+
}
|
|
75
|
+
export interface WhatsAppChange {
|
|
76
|
+
field: string;
|
|
77
|
+
value: WhatsAppValue;
|
|
78
|
+
}
|
|
79
|
+
export interface WhatsAppEntry {
|
|
80
|
+
/** The WhatsApp Business Account id. */
|
|
81
|
+
id: string;
|
|
82
|
+
changes: WhatsAppChange[];
|
|
83
|
+
}
|
|
84
|
+
/** One webhook POST — Meta may batch several entries, changes and messages. */
|
|
85
|
+
export interface WhatsAppWebhook {
|
|
86
|
+
object: string;
|
|
87
|
+
entry: WhatsAppEntry[];
|
|
88
|
+
}
|
|
89
|
+
/** `GET /<phone-number-id>?fields=display_phone_number,verified_name` */
|
|
90
|
+
export interface WhatsAppPhoneNumber {
|
|
91
|
+
id: string;
|
|
92
|
+
display_phone_number?: string;
|
|
93
|
+
verified_name?: string;
|
|
94
|
+
}
|
|
95
|
+
/** `POST /<phone-number-id>/messages` — what it answers. */
|
|
96
|
+
export interface WhatsAppSendAnswer {
|
|
97
|
+
messaging_product: string;
|
|
98
|
+
contacts?: {
|
|
99
|
+
input: string;
|
|
100
|
+
wa_id: string;
|
|
101
|
+
}[];
|
|
102
|
+
messages: {
|
|
103
|
+
id: string;
|
|
104
|
+
message_status?: string;
|
|
105
|
+
}[];
|
|
106
|
+
}
|
|
107
|
+
/** Every Graph API refusal. */
|
|
108
|
+
export interface WhatsAppErrorEnvelope {
|
|
109
|
+
error: {
|
|
110
|
+
message: string;
|
|
111
|
+
type?: string;
|
|
112
|
+
code: number;
|
|
113
|
+
error_subcode?: number;
|
|
114
|
+
error_data?: {
|
|
115
|
+
messaging_product?: string;
|
|
116
|
+
details?: string;
|
|
117
|
+
};
|
|
118
|
+
fbtrace_id?: string;
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export interface WhatsAppBotPlatformOptions {
|
|
122
|
+
/** The Graph API host, default `https://graph.facebook.com`. */
|
|
123
|
+
base?: string;
|
|
124
|
+
/** The Graph API version, default `v26.0`; calls go to `<base>/<version>/…`. */
|
|
125
|
+
version?: string;
|
|
126
|
+
}
|
|
127
|
+
export interface WhatsAppCallOptions {
|
|
128
|
+
signal?: AbortSignal;
|
|
129
|
+
timeoutMs?: number;
|
|
130
|
+
}
|
|
131
|
+
/** The Graph API over a session's transport, the access token as a Bearer header. */
|
|
132
|
+
export interface WhatsAppApi {
|
|
133
|
+
/** GET `<root>/<path>?<query>`. @throws {WhatsAppApiError} an `error` answer */
|
|
134
|
+
get: <T>(path: string, query?: Record<string, string>, opts?: WhatsAppCallOptions) => Promise<T>;
|
|
135
|
+
/** POST `<root>/<path>` with a JSON body. @throws {WhatsAppApiError} an `error` answer */
|
|
136
|
+
post: <T>(path: string, body: Record<string, unknown>, opts?: WhatsAppCallOptions) => Promise<T>;
|
|
137
|
+
}
|
|
138
|
+
export interface WhatsAppApiFactory {
|
|
139
|
+
/** `root` = `<base>/<version>`. */
|
|
140
|
+
(session: Pick<BotPlatformSession, 'connection' | 'fetch'>, root: string): WhatsAppApi;
|
|
141
|
+
}
|
|
142
|
+
/** Meta's `X-Hub-Signature-256` — HMAC-SHA256 of the raw body, keyed by the app secret. */
|
|
143
|
+
export interface WhatsAppSignatureHelper {
|
|
144
|
+
/** The header value for `rawBody`: `sha256=<lower-case hex>`. */
|
|
145
|
+
sign: (rawBody: string, secret: string) => string;
|
|
146
|
+
/** Whether `header` signs `rawBody` with `secret` — timing-safe; an empty secret never matches. */
|
|
147
|
+
verify: (header: string | undefined, rawBody: string, secret: string) => boolean;
|
|
148
|
+
}
|
|
149
|
+
export interface WhatsAppNormalizer {
|
|
150
|
+
/**
|
|
151
|
+
* Every `messages[]` of every change of a `whatsapp_business_account` payload → one update each
|
|
152
|
+
* (text, interactive and button replies, media captions); statuses and other kinds → none.
|
|
153
|
+
*/
|
|
154
|
+
normalize: (payload: unknown, connection: BotConnection) => BotNormalizedUpdate[];
|
|
155
|
+
}
|
|
156
|
+
export interface WhatsAppMock extends BotPlatformMock {
|
|
157
|
+
/** The phone number id the fake API answers for a connection (its `phoneNumberId`, else one derived from its id). */
|
|
158
|
+
phoneNumberIdOf: (connection: BotPlatformConnection) => string;
|
|
159
|
+
/** The business number the fake API shows for a connection (`1555…`). */
|
|
160
|
+
displayNumberOf: (connection: BotPlatformConnection) => string;
|
|
161
|
+
/** The subscription handshake Meta sends (GET `hub.*`) — with the connection's verify token unless one is given. */
|
|
162
|
+
challenge: (connection: BotPlatformConnection, opts?: {
|
|
163
|
+
challenge?: string;
|
|
164
|
+
verifyToken?: string;
|
|
165
|
+
}) => BotHookRequest;
|
|
166
|
+
}
|
|
167
|
+
/** One mock connection's state. */
|
|
168
|
+
export interface WhatsAppMockState {
|
|
169
|
+
calls: {
|
|
170
|
+
method: string;
|
|
171
|
+
params: Record<string, unknown>;
|
|
172
|
+
at: string;
|
|
173
|
+
}[];
|
|
174
|
+
/** Message ids the fake business sent — a simulated reply to one quotes the bot. */
|
|
175
|
+
sent: Set<string>;
|
|
176
|
+
/** Payloads `feed` was handed — WhatsApp has no receiver, so nothing drains them. */
|
|
177
|
+
fed: unknown[];
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAA;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,KAAK,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AAI3H,MAAM,WAAW,gBAAgB;IAC/B,oBAAoB,EAAE,MAAM,CAAA;IAC5B,eAAe,EAAE,MAAM,CAAA;CACxB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IAC3B,KAAK,EAAE,MAAM,CAAA;CACd;AAED,yDAAyD;AACzD,MAAM,WAAW,eAAe;IAC9B,+EAA+E;IAC/E,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,EAAE,CAAC,EAAE,MAAM,CAAA;IACX,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,cAAc,GAAG,YAAY,GAAG,MAAM,CAAA;IAC5C,YAAY,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAA;IAC5C,UAAU,CAAC,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC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D,oHAAoH;IACpH,SAAS,EAAE,CAAC,UAAU,EAAE,qBAAqB,EAAE,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,cAAc,CAAA;CACtH;AAED,mCAAmC;AACnC,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IACxE,oFAAoF;IACpF,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IACjB,qFAAqF;IACrF,GAAG,EAAE,OAAO,EAAE,CAAA;CACf"}
|
package/build/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owlmeans/bot-whatsapp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "OwlMeans chat-bot platform plugin for WhatsApp (Cloud API): the @owlmeans/server-bot plugin, its descriptor and its native API client.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://owlmeans.com/docs/",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/owlmeans/connect.git",
|
|
10
|
+
"directory": "packages/bot-whatsapp"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/owlmeans/connect/issues"
|
|
14
|
+
},
|
|
15
|
+
"author": "Igor Tkachenko <igor.tkachenko@owlmeans.com> (https://owlmeans.com)",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -b",
|
|
19
|
+
"dev": "sleep 4 && nodemon -e ts,tsx,json --watch src --exec \"tsc -p ./tsconfig.json\"",
|
|
20
|
+
"watch": "tsc -b -w --preserveWatchOutput --pretty",
|
|
21
|
+
"test": "bun test ./tests"
|
|
22
|
+
},
|
|
23
|
+
"main": "build/index.js",
|
|
24
|
+
"module": "build/index.js",
|
|
25
|
+
"types": "build/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"import": "./build/index.js",
|
|
29
|
+
"require": "./build/index.js",
|
|
30
|
+
"default": "./build/index.js",
|
|
31
|
+
"module": "./build/index.js",
|
|
32
|
+
"types": "./build/index.d.ts"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@owlmeans/bot": "^0.2.0",
|
|
37
|
+
"@owlmeans/context": "^0.2.0",
|
|
38
|
+
"@owlmeans/server-bot": "^0.2.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"ajv": "*"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@owlmeans/dep-config": "^0.2.0",
|
|
45
|
+
"@owlmeans/log": "^0.2.0",
|
|
46
|
+
"@owlmeans/resource": "^0.2.0",
|
|
47
|
+
"@owlmeans/static-resource": "^0.2.0",
|
|
48
|
+
"@owlmeans/test": "^0.2.0",
|
|
49
|
+
"@types/bun": "^1.4.4",
|
|
50
|
+
"@types/node": "^26.6.5",
|
|
51
|
+
"ajv": "^8.20.0",
|
|
52
|
+
"nodemon": "^3.1.14",
|
|
53
|
+
"typescript": "^7.0.2"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { WHATSAPP_CALL_TIMEOUT_MS } from './consts.js'
|
|
2
|
+
import { WhatsAppApiError } from './errors.js'
|
|
3
|
+
import type { WhatsAppApi, WhatsAppApiFactory, WhatsAppCallOptions, WhatsAppErrorEnvelope } from './types.js'
|
|
4
|
+
import { botSignalHelper } from '@owlmeans/server-bot'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The Graph API over a session: `<root>/<path>`, the access token as `Authorization: Bearer`, JSON in
|
|
8
|
+
* and out; a refusal is `{ error: { message, code, … } }`. The token never reaches an error message.
|
|
9
|
+
*/
|
|
10
|
+
export const makeWhatsAppApi: WhatsAppApiFactory = (session, root): WhatsAppApi => {
|
|
11
|
+
const call = async <T>(
|
|
12
|
+
method: 'GET' | 'POST', path: string, query: Record<string, string> | undefined,
|
|
13
|
+
body: Record<string, unknown> | undefined, opts: WhatsAppCallOptions
|
|
14
|
+
): Promise<T> => {
|
|
15
|
+
const token = session.connection.credentials.accessToken ?? ''
|
|
16
|
+
const search = query != null && Object.keys(query).length > 0 ? `?${new URLSearchParams(query).toString()}` : ''
|
|
17
|
+
const name = `${method} ${path.split('/').pop() ?? ''}`
|
|
18
|
+
let response: Response
|
|
19
|
+
try {
|
|
20
|
+
response = await session.fetch(`${root}/${path}${search}`, {
|
|
21
|
+
method,
|
|
22
|
+
headers: {
|
|
23
|
+
...(token !== '' ? { authorization: `Bearer ${token}` } : {}),
|
|
24
|
+
...(body != null ? { 'content-type': 'application/json' } : {}),
|
|
25
|
+
},
|
|
26
|
+
...(body != null ? { body: JSON.stringify(body) } : {}),
|
|
27
|
+
signal: botSignalHelper.deadline(opts.timeoutMs ?? WHATSAPP_CALL_TIMEOUT_MS, opts.signal),
|
|
28
|
+
})
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (opts.signal?.aborted === true) {
|
|
31
|
+
throw error
|
|
32
|
+
}
|
|
33
|
+
// A transport error may carry the request — and its header the token: never pass it on.
|
|
34
|
+
const timedOut = error instanceof Error && error.name === 'TimeoutError'
|
|
35
|
+
throw WhatsAppApiError.of(timedOut ? 504 : 503, `${name}: ${timedOut ? 'timeout' : 'unreachable'}`)
|
|
36
|
+
}
|
|
37
|
+
let answer: unknown
|
|
38
|
+
try {
|
|
39
|
+
answer = await response.json()
|
|
40
|
+
} catch {
|
|
41
|
+
throw WhatsAppApiError.of(response.status, `${name}: unreadable answer`)
|
|
42
|
+
}
|
|
43
|
+
const refusal = (answer as Partial<WhatsAppErrorEnvelope> | null)?.error
|
|
44
|
+
if (refusal != null || !response.ok) {
|
|
45
|
+
throw WhatsAppApiError.of(
|
|
46
|
+
typeof refusal?.code === 'number' ? refusal.code : response.status,
|
|
47
|
+
refusal?.message ?? `${name}: refused`,
|
|
48
|
+
response.status
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return answer as T
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const get = async <T>(path: string, query?: Record<string, string>, opts: WhatsAppCallOptions = {}): Promise<T> =>
|
|
56
|
+
await call<T>('GET', path, query, undefined, opts)
|
|
57
|
+
|
|
58
|
+
const post = async <T>(path: string, body: Record<string, unknown>, opts: WhatsAppCallOptions = {}): Promise<T> =>
|
|
59
|
+
await call<T>('POST', path, undefined, body, opts)
|
|
60
|
+
|
|
61
|
+
return { get, post }
|
|
62
|
+
}
|
package/src/append.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { BasicContext } from '@owlmeans/context'
|
|
2
|
+
import { appendBot, BOT_SERVICE, type BotPlatformPlugin } from '@owlmeans/server-bot'
|
|
3
|
+
import { makeWhatsAppBotPlatform } from './plugin.js'
|
|
4
|
+
import type { WhatsAppBotPlatformOptions } from './types.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Register the WhatsApp plugin on the context's bot service — appending the service (`appendBot`, its
|
|
8
|
+
* default options) when it is not there yet — and answer the plugin. Registration is explicit:
|
|
9
|
+
* importing this package registers nothing.
|
|
10
|
+
*/
|
|
11
|
+
export const appendWhatsAppBotPlatform = <C extends BasicContext<any>>(
|
|
12
|
+
context: C, opts?: WhatsAppBotPlatformOptions, alias: string = BOT_SERVICE
|
|
13
|
+
): BotPlatformPlugin => {
|
|
14
|
+
const plugin = makeWhatsAppBotPlatform(opts)
|
|
15
|
+
appendBot(context, undefined, alias).register(plugin)
|
|
16
|
+
|
|
17
|
+
return plugin
|
|
18
|
+
}
|
package/src/consts.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BotActionKind, BotReceiveMode, type BotCredentialField, type BotPlatformDescriptor, type BotTexts,
|
|
3
|
+
} from '@owlmeans/bot'
|
|
4
|
+
|
|
5
|
+
/** The Graph API host — override `base` (and `version`) through `makeWhatsAppBotPlatform`. */
|
|
6
|
+
export const WHATSAPP_API_BASE = 'https://graph.facebook.com'
|
|
7
|
+
|
|
8
|
+
/** The Graph API version calls go to: `<base>/<version>/…`. */
|
|
9
|
+
export const WHATSAPP_API_VERSION = 'v26.0'
|
|
10
|
+
|
|
11
|
+
/** The header Meta signs every webhook POST in (lower-cased, as servers hand it over). */
|
|
12
|
+
export const WHATSAPP_SIGNATURE_HEADER = 'x-hub-signature-256'
|
|
13
|
+
|
|
14
|
+
/** What precedes the hex HMAC-SHA256 digest in the signature header. */
|
|
15
|
+
export const WHATSAPP_SIGNATURE_PREFIX = 'sha256='
|
|
16
|
+
|
|
17
|
+
/** `object` of every WhatsApp Business Account webhook payload. */
|
|
18
|
+
export const WHATSAPP_WEBHOOK_OBJECT = 'whatsapp_business_account'
|
|
19
|
+
|
|
20
|
+
/** The webhook field a connection subscribes to — incoming messages and the statuses of sent ones. */
|
|
21
|
+
export const WHATSAPP_MESSAGES_FIELD = 'messages'
|
|
22
|
+
|
|
23
|
+
/** The subscription handshake's `hub.mode`. */
|
|
24
|
+
export const WHATSAPP_HUB_MODE = 'subscribe'
|
|
25
|
+
|
|
26
|
+
/** What `verify` reads of the business phone number. */
|
|
27
|
+
export const WHATSAPP_PHONE_FIELDS = 'display_phone_number,verified_name'
|
|
28
|
+
|
|
29
|
+
/** `messaging_product` of every Cloud API message. */
|
|
30
|
+
export const WHATSAPP_MESSAGING_PRODUCT = 'whatsapp'
|
|
31
|
+
|
|
32
|
+
/** How long one Graph API call may take. */
|
|
33
|
+
export const WHATSAPP_CALL_TIMEOUT_MS = 15_000
|
|
34
|
+
|
|
35
|
+
/** `text.body` limit — longer text is clipped. */
|
|
36
|
+
export const WHATSAPP_TEXT_MAX = 4096
|
|
37
|
+
|
|
38
|
+
/** The credentials a live `verify` calls with (the app secret only signs inbound requests). */
|
|
39
|
+
export const WHATSAPP_VERIFY_CREDENTIALS = Object.freeze(['accessToken', 'phoneNumberId'])
|
|
40
|
+
|
|
41
|
+
/** Graph error codes that refuse the access token or the phone number id (verification fails on them). */
|
|
42
|
+
export const WHATSAPP_CREDENTIAL_ERROR_CODES = Object.freeze([0, 3, 10, 100, 190])
|
|
43
|
+
|
|
44
|
+
/** HTTP statuses that refuse the credentials whatever the error code. */
|
|
45
|
+
export const WHATSAPP_CREDENTIAL_STATUSES = Object.freeze([401, 403, 404])
|
|
46
|
+
|
|
47
|
+
/** The incoming message types whose text the bot reads (media by their caption). */
|
|
48
|
+
export const WHATSAPP_CAPTIONED_TYPES = Object.freeze(['image', 'video', 'document'])
|
|
49
|
+
|
|
50
|
+
/** Where the callback URL and the verify token are pasted (the plugin's first two steps name them). */
|
|
51
|
+
export const WHATSAPP_SETUP_CONSOLE = 'In the Meta App Dashboard, open WhatsApp → Configuration → Webhook and press Edit.'
|
|
52
|
+
|
|
53
|
+
/** The steps after the callback URL and the verify token. */
|
|
54
|
+
export const WHATSAPP_SETUP_STEPS = Object.freeze([
|
|
55
|
+
'Under Webhook fields, subscribe to "messages".',
|
|
56
|
+
'Use a permanent System User access token with the whatsapp_business_messaging permission — the temporary token of the API Setup page expires within a day.',
|
|
57
|
+
'A Meta app posts the messages of all its numbers to one callback URL: give every connected number its own app.',
|
|
58
|
+
'Customers write first: WhatsApp lets the bot answer a customer within 24 hours of their last message.',
|
|
59
|
+
])
|
|
60
|
+
|
|
61
|
+
/** The mock's simulated defaults: one customer writing to a test business number. */
|
|
62
|
+
export const WHATSAPP_MOCK_SENDER_ID = '15551230001'
|
|
63
|
+
export const WHATSAPP_MOCK_SENDER_NAME = 'Test customer'
|
|
64
|
+
export const WHATSAPP_MOCK_BUSINESS_NAME = 'Mock business'
|
|
65
|
+
/** A mock business number is `1555` and seven digits derived from the connection id. */
|
|
66
|
+
export const WHATSAPP_MOCK_NUMBER_PREFIX = '1555'
|
|
67
|
+
/** A mock phone number id is fifteen digits derived from the connection id, starting here. */
|
|
68
|
+
export const WHATSAPP_MOCK_PHONE_ID_BASE = 100_000_000_000_000
|
|
69
|
+
/** Random bytes in a mock `wamid.` (as hex, the way Meta's ids carry a 20-character hex message key). */
|
|
70
|
+
export const WHATSAPP_MOCK_ID_BYTES = 10
|
|
71
|
+
|
|
72
|
+
/** The platform id — a stored column and a hook URL segment: it never changes. */
|
|
73
|
+
export const WHATSAPP_PLATFORM = 'whatsapp'
|
|
74
|
+
|
|
75
|
+
/** What a WhatsApp connection needs typed (or generated), with its labels and hints in every panel language. */
|
|
76
|
+
export const WHATSAPP_CREDENTIALS: readonly BotCredentialField[] = Object.freeze([
|
|
77
|
+
Object.freeze({
|
|
78
|
+
key: 'accessToken',
|
|
79
|
+
secret: true,
|
|
80
|
+
required: true,
|
|
81
|
+
label: Object.freeze({
|
|
82
|
+
en: 'Access token',
|
|
83
|
+
pl: 'Token dostępu',
|
|
84
|
+
ru: 'Токен доступа',
|
|
85
|
+
be: 'Токен доступу',
|
|
86
|
+
uk: 'Токен доступу',
|
|
87
|
+
es: 'Token de acceso',
|
|
88
|
+
de: 'Zugriffstoken',
|
|
89
|
+
fr: 'Jeton d’accès',
|
|
90
|
+
}),
|
|
91
|
+
hint: Object.freeze({
|
|
92
|
+
en: 'A permanent system-user token of your Meta app with the WhatsApp messaging permission.',
|
|
93
|
+
pl: 'Stały token użytkownika systemowego Twojej aplikacji Meta z uprawnieniem do wiadomości WhatsApp.',
|
|
94
|
+
ru: 'Постоянный токен системного пользователя вашего приложения Meta с правом отправки сообщений WhatsApp.',
|
|
95
|
+
be: 'Пастаянны токен сістэмнага карыстальніка вашай праграмы Meta з правам адпраўкі паведамленняў WhatsApp.',
|
|
96
|
+
uk: 'Постійний токен системного користувача вашого застосунку Meta з правом надсилати повідомлення WhatsApp.',
|
|
97
|
+
es: 'Un token permanente de usuario del sistema de tu app de Meta con permiso de mensajería de WhatsApp.',
|
|
98
|
+
de: 'Ein dauerhaftes System-User-Token Ihrer Meta-App mit der Berechtigung für WhatsApp-Nachrichten.',
|
|
99
|
+
fr: 'Un jeton permanent d’utilisateur système de votre app Meta, avec l’autorisation de messagerie WhatsApp.',
|
|
100
|
+
}),
|
|
101
|
+
}),
|
|
102
|
+
Object.freeze({
|
|
103
|
+
key: 'phoneNumberId',
|
|
104
|
+
secret: false,
|
|
105
|
+
required: true,
|
|
106
|
+
label: Object.freeze({
|
|
107
|
+
en: 'Phone number ID',
|
|
108
|
+
pl: 'ID numeru telefonu',
|
|
109
|
+
ru: 'ID номера телефона',
|
|
110
|
+
be: 'ID нумара тэлефона',
|
|
111
|
+
uk: 'ID номера телефону',
|
|
112
|
+
es: 'ID del número de teléfono',
|
|
113
|
+
de: 'Telefonnummern-ID',
|
|
114
|
+
fr: 'ID du numéro de téléphone',
|
|
115
|
+
}),
|
|
116
|
+
hint: Object.freeze({
|
|
117
|
+
en: 'WhatsApp → API Setup in your Meta app dashboard.',
|
|
118
|
+
pl: 'WhatsApp → API Setup w panelu Twojej aplikacji Meta.',
|
|
119
|
+
ru: 'WhatsApp → API Setup в панели вашего приложения Meta.',
|
|
120
|
+
be: 'WhatsApp → API Setup у панэлі вашай праграмы Meta.',
|
|
121
|
+
uk: 'WhatsApp → API Setup у панелі вашого застосунку Meta.',
|
|
122
|
+
es: 'WhatsApp → API Setup en el panel de tu app de Meta.',
|
|
123
|
+
de: 'WhatsApp → API Setup im Dashboard Ihrer Meta-App.',
|
|
124
|
+
fr: 'WhatsApp → API Setup dans le tableau de bord de votre app Meta.',
|
|
125
|
+
}),
|
|
126
|
+
}),
|
|
127
|
+
Object.freeze({
|
|
128
|
+
key: 'appSecret',
|
|
129
|
+
secret: true,
|
|
130
|
+
required: true,
|
|
131
|
+
label: Object.freeze({
|
|
132
|
+
en: 'App secret',
|
|
133
|
+
pl: 'Sekret aplikacji',
|
|
134
|
+
ru: 'Секрет приложения',
|
|
135
|
+
be: 'Сакрэт праграмы',
|
|
136
|
+
uk: 'Секрет застосунку',
|
|
137
|
+
es: 'Secreto de la app',
|
|
138
|
+
de: 'App-Geheimnis',
|
|
139
|
+
fr: 'Clé secrète de l’app',
|
|
140
|
+
}),
|
|
141
|
+
hint: Object.freeze({
|
|
142
|
+
en: 'App settings → Basic in your Meta app; it proves every incoming message came from Meta.',
|
|
143
|
+
pl: 'App settings → Basic w Twojej aplikacji Meta; potwierdza, że każda przychodząca wiadomość pochodzi od Meta.',
|
|
144
|
+
ru: 'App settings → Basic в вашем приложении Meta; он подтверждает, что каждое входящее сообщение пришло от Meta.',
|
|
145
|
+
be: 'App settings → Basic у вашай праграме Meta; ён пацвярджае, што кожнае ўваходнае паведамленне прыйшло ад Meta.',
|
|
146
|
+
uk: 'App settings → Basic у вашому застосунку Meta; він підтверджує, що кожне вхідне повідомлення надійшло від Meta.',
|
|
147
|
+
es: 'App settings → Basic en tu app de Meta; demuestra que cada mensaje entrante viene de Meta.',
|
|
148
|
+
de: 'App settings → Basic in Ihrer Meta-App; es belegt, dass jede eingehende Nachricht von Meta stammt.',
|
|
149
|
+
fr: 'App settings → Basic dans votre app Meta ; elle prouve que chaque message entrant vient de Meta.',
|
|
150
|
+
}),
|
|
151
|
+
}),
|
|
152
|
+
Object.freeze({
|
|
153
|
+
key: 'verifyToken',
|
|
154
|
+
secret: true,
|
|
155
|
+
required: true,
|
|
156
|
+
generated: true,
|
|
157
|
+
label: Object.freeze({
|
|
158
|
+
en: 'Verify token',
|
|
159
|
+
pl: 'Token weryfikacyjny',
|
|
160
|
+
ru: 'Токен подтверждения',
|
|
161
|
+
be: 'Токен пацверджання',
|
|
162
|
+
uk: 'Токен підтвердження',
|
|
163
|
+
es: 'Token de verificación',
|
|
164
|
+
de: 'Verifizierungstoken',
|
|
165
|
+
fr: 'Jeton de vérification',
|
|
166
|
+
}),
|
|
167
|
+
hint: Object.freeze({
|
|
168
|
+
en: 'Created for you; paste it into the webhook settings of your Meta app.',
|
|
169
|
+
pl: 'Tworzony dla Ciebie; wklej go w ustawieniach webhooka Twojej aplikacji Meta.',
|
|
170
|
+
ru: 'Создаётся автоматически; вставьте его в настройки вебхука вашего приложения Meta.',
|
|
171
|
+
be: 'Ствараецца аўтаматычна; устаўце яго ў налады вэбхука вашай праграмы Meta.',
|
|
172
|
+
uk: 'Створюється автоматично; вставте його в налаштування вебхука вашого застосунку Meta.',
|
|
173
|
+
es: 'Se crea por ti; pégalo en la configuración del webhook de tu app de Meta.',
|
|
174
|
+
de: 'Wird für Sie erzeugt; fügen Sie es in die Webhook-Einstellungen Ihrer Meta-App ein.',
|
|
175
|
+
fr: 'Créé pour vous ; collez-le dans les paramètres du webhook de votre app Meta.',
|
|
176
|
+
}),
|
|
177
|
+
}),
|
|
178
|
+
]) as readonly BotCredentialField[]
|
|
179
|
+
|
|
180
|
+
/** What a person does in WhatsApp itself so the bot can act — in every panel language. */
|
|
181
|
+
export const WHATSAPP_HINT: BotTexts = Object.freeze({
|
|
182
|
+
en: 'Paste the webhook URL and the verify token below into the webhook settings of your Meta app, then subscribe to the messages field.',
|
|
183
|
+
pl: 'Wklej poniższy adres webhooka i token weryfikacyjny w ustawieniach webhooka Twojej aplikacji Meta, a następnie zasubskrybuj pole messages.',
|
|
184
|
+
ru: 'Вставьте URL вебхука и токен подтверждения ниже в настройки вебхука вашего приложения Meta, затем подпишитесь на поле messages.',
|
|
185
|
+
be: 'Устаўце URL вэбхука і токен пацверджання ніжэй у налады вэбхука вашай праграмы Meta, потым падпішыцеся на поле messages.',
|
|
186
|
+
uk: 'Вставте URL вебхука й токен підтвердження нижче в налаштування вебхука вашого застосунку Meta, потім підпишіться на поле messages.',
|
|
187
|
+
es: 'Pega la URL del webhook y el token de verificación de abajo en la configuración del webhook de tu app de Meta y suscríbete al campo messages.',
|
|
188
|
+
de: 'Fügen Sie die Webhook-URL und das Verifizierungstoken unten in die Webhook-Einstellungen Ihrer Meta-App ein und abonnieren Sie dann das Feld messages.',
|
|
189
|
+
fr: 'Collez l’URL du webhook et le jeton de vérification ci-dessous dans les paramètres du webhook de votre app Meta, puis abonnez-vous au champ messages.',
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The WhatsApp descriptor — what the server verifies and acts by and what the panels draw (`platform.list`).
|
|
194
|
+
* `actions` are the calls the required credentials allow; `note` is never listed.
|
|
195
|
+
*/
|
|
196
|
+
export const WHATSAPP_DESCRIPTOR: BotPlatformDescriptor = Object.freeze({
|
|
197
|
+
platform: WHATSAPP_PLATFORM,
|
|
198
|
+
title: 'WhatsApp',
|
|
199
|
+
glyph: 'phone',
|
|
200
|
+
credentials: WHATSAPP_CREDENTIALS,
|
|
201
|
+
receive: Object.freeze([BotReceiveMode.Webhook]),
|
|
202
|
+
actions: Object.freeze([BotActionKind.Reply, BotActionKind.Send, BotActionKind.React]),
|
|
203
|
+
setup: 'manual',
|
|
204
|
+
docs: 'https://developers.facebook.com/docs/whatsapp/cloud-api/get-started',
|
|
205
|
+
hint: WHATSAPP_HINT,
|
|
206
|
+
}) as BotPlatformDescriptor
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { BotErrorPlatform } from '@owlmeans/bot'
|
|
2
|
+
import { WHATSAPP_PLATFORM } from './consts.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The Graph API refused a call — `bot:platform:whatsapp:<code>:<message>`, `code` being the Graph
|
|
6
|
+
* error code (`error.code`: 190 an expired token, 100 a bad parameter, 131047 outside the 24-hour
|
|
7
|
+
* window …), or the HTTP status when the answer carried none (503 unreachable, 504 timeout).
|
|
8
|
+
*
|
|
9
|
+
* Declares no type name of its own: it travels as `BotErrorPlatform`, so a refusal is rebuilt (and
|
|
10
|
+
* explained) wherever this package is not loaded.
|
|
11
|
+
*/
|
|
12
|
+
export class WhatsAppApiError extends BotErrorPlatform {
|
|
13
|
+
/** The refusal as the Graph API stated it. */
|
|
14
|
+
public static override of(code: number | string, description: string, status?: number): WhatsAppApiError {
|
|
15
|
+
const error = new WhatsAppApiError(`${code}:${description}`)
|
|
16
|
+
error.status = status ?? (Number(code) || 500)
|
|
17
|
+
return error
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The Graph error code (or the HTTP status when there was none). */
|
|
21
|
+
public code: number = 500
|
|
22
|
+
/** The HTTP status of the answer — not carried across a hop (500 there; the code is carried). */
|
|
23
|
+
public status: number = 500
|
|
24
|
+
|
|
25
|
+
/** `message` is `<code>:<description>` — prefer {@link WhatsAppApiError.of}. */
|
|
26
|
+
constructor(message: string = '500:error') {
|
|
27
|
+
super(`${WHATSAPP_PLATFORM}:${message}`)
|
|
28
|
+
this.finalizeUnmarshal()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The code is read back from the detail. */
|
|
32
|
+
public override finalizeUnmarshal(): void {
|
|
33
|
+
super.finalizeUnmarshal()
|
|
34
|
+
const code = Number(/^(\d+):/.exec(this.detail)?.[1])
|
|
35
|
+
this.code = Number.isFinite(code) ? code : 500
|
|
36
|
+
}
|
|
37
|
+
}
|