@gakr-gakr/zalo 0.1.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 +50 -0
- package/api.ts +8 -0
- package/autobot.plugin.json +15 -0
- package/channel-plugin-api.ts +1 -0
- package/contract-api.ts +5 -0
- package/index.ts +20 -0
- package/package.json +60 -0
- package/runtime-api.ts +71 -0
- package/secret-contract-api.ts +5 -0
- package/setup-api.ts +34 -0
- package/setup-entry.ts +13 -0
- package/src/accounts.ts +65 -0
- package/src/actions.runtime.ts +5 -0
- package/src/actions.ts +62 -0
- package/src/api.ts +265 -0
- package/src/approval-auth.ts +25 -0
- package/src/channel.runtime.ts +93 -0
- package/src/channel.ts +309 -0
- package/src/config-schema.ts +29 -0
- package/src/group-access.ts +23 -0
- package/src/monitor-durable.ts +38 -0
- package/src/monitor.ts +1012 -0
- package/src/monitor.types.ts +4 -0
- package/src/monitor.webhook.ts +278 -0
- package/src/outbound-media.ts +239 -0
- package/src/probe.ts +45 -0
- package/src/proxy.ts +18 -0
- package/src/runtime-api.ts +71 -0
- package/src/runtime-support.ts +85 -0
- package/src/runtime.ts +9 -0
- package/src/secret-contract.ts +109 -0
- package/src/secret-input.ts +5 -0
- package/src/send.ts +207 -0
- package/src/session-route.ts +32 -0
- package/src/setup-allow-from.ts +97 -0
- package/src/setup-core.ts +152 -0
- package/src/setup-surface.ts +294 -0
- package/src/status-issues.ts +37 -0
- package/src/token.ts +79 -0
- package/src/types.ts +50 -0
- package/test-api.ts +1 -0
- package/tsconfig.json +16 -0
package/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# @gakr-gakr/zalo
|
|
2
|
+
|
|
3
|
+
Zalo channel plugin for AutoBot (Bot API).
|
|
4
|
+
|
|
5
|
+
## Install (local checkout)
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
autobot plugins install ./path/to/local/zalo-plugin
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Install (npm)
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
autobot plugins install @gakr-gakr/zalo
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Onboarding: select Zalo and confirm the install prompt to fetch the plugin automatically.
|
|
18
|
+
|
|
19
|
+
## Config
|
|
20
|
+
|
|
21
|
+
```json5
|
|
22
|
+
{
|
|
23
|
+
channels: {
|
|
24
|
+
zalo: {
|
|
25
|
+
enabled: true,
|
|
26
|
+
botToken: "12345689:abc-xyz",
|
|
27
|
+
dmPolicy: "pairing",
|
|
28
|
+
proxy: "http://proxy.local:8080",
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Webhook mode
|
|
35
|
+
|
|
36
|
+
```json5
|
|
37
|
+
{
|
|
38
|
+
channels: {
|
|
39
|
+
zalo: {
|
|
40
|
+
webhookUrl: "https://example.com/zalo-webhook",
|
|
41
|
+
webhookSecret: "your-secret-8-plus-chars",
|
|
42
|
+
webhookPath: "/zalo-webhook",
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
If `webhookPath` is omitted, the plugin uses the webhook URL path.
|
|
49
|
+
|
|
50
|
+
Restart the gateway after config changes.
|
package/api.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "zalo",
|
|
3
|
+
"activation": {
|
|
4
|
+
"onStartup": false
|
|
5
|
+
},
|
|
6
|
+
"channels": ["zalo"],
|
|
7
|
+
"channelEnvVars": {
|
|
8
|
+
"zalo": ["ZALO_BOT_TOKEN", "ZALO_WEBHOOK_SECRET"]
|
|
9
|
+
},
|
|
10
|
+
"configSchema": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"additionalProperties": false,
|
|
13
|
+
"properties": {}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { zaloPlugin } from "./src/channel.js";
|
package/contract-api.ts
ADDED
package/index.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { defineBundledChannelEntry } from "autobot/plugin-sdk/channel-entry-contract";
|
|
2
|
+
|
|
3
|
+
export default defineBundledChannelEntry({
|
|
4
|
+
id: "zalo",
|
|
5
|
+
name: "Zalo",
|
|
6
|
+
description: "Zalo channel plugin",
|
|
7
|
+
importMetaUrl: import.meta.url,
|
|
8
|
+
plugin: {
|
|
9
|
+
specifier: "./channel-plugin-api.js",
|
|
10
|
+
exportName: "zaloPlugin",
|
|
11
|
+
},
|
|
12
|
+
secrets: {
|
|
13
|
+
specifier: "./secret-contract-api.js",
|
|
14
|
+
exportName: "channelSecrets",
|
|
15
|
+
},
|
|
16
|
+
runtime: {
|
|
17
|
+
specifier: "./runtime-api.js",
|
|
18
|
+
exportName: "setZaloRuntime",
|
|
19
|
+
},
|
|
20
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@gakr-gakr/zalo",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AutoBot Zalo channel plugin",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/autobot/autobot"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"devDependencies": {
|
|
11
|
+
"@gakr-gakr/plugin-sdk": "workspace:*",
|
|
12
|
+
"@gakr-gakr/autobot": "workspace:*",
|
|
13
|
+
"autobot": "workspace:@gakr-gakr/autobot@*"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"@gakr-gakr/autobot": ">=0.1.0"
|
|
17
|
+
},
|
|
18
|
+
"peerDependenciesMeta": {
|
|
19
|
+
"@gakr-gakr/autobot": {
|
|
20
|
+
"optional": true
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"autobot": {
|
|
24
|
+
"extensions": [
|
|
25
|
+
"./index.ts"
|
|
26
|
+
],
|
|
27
|
+
"setupEntry": "./setup-entry.ts",
|
|
28
|
+
"channel": {
|
|
29
|
+
"id": "zalo",
|
|
30
|
+
"label": "Zalo",
|
|
31
|
+
"selectionLabel": "Zalo (Bot API)",
|
|
32
|
+
"docsPath": "/channels/zalo",
|
|
33
|
+
"docsLabel": "zalo",
|
|
34
|
+
"blurb": "Vietnam-focused messaging platform with Bot API.",
|
|
35
|
+
"aliases": [
|
|
36
|
+
"zl"
|
|
37
|
+
],
|
|
38
|
+
"order": 80,
|
|
39
|
+
"quickstartAllowFrom": true
|
|
40
|
+
},
|
|
41
|
+
"install": {
|
|
42
|
+
"npmSpec": "@gakr-gakr/zalo",
|
|
43
|
+
"defaultChoice": "npm",
|
|
44
|
+
"minHostVersion": ">=0.1.0"
|
|
45
|
+
},
|
|
46
|
+
"compat": {
|
|
47
|
+
"pluginApi": ">=0.1.0"
|
|
48
|
+
},
|
|
49
|
+
"build": {
|
|
50
|
+
"autobotVersion": "0.1.0"
|
|
51
|
+
},
|
|
52
|
+
"release": {
|
|
53
|
+
"publishToClawHub": true,
|
|
54
|
+
"publishToNpm": true
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"zod": "4.4.3"
|
|
59
|
+
}
|
|
60
|
+
}
|
package/runtime-api.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export {
|
|
2
|
+
addWildcardAllowFrom,
|
|
3
|
+
applyAccountNameToChannelSection,
|
|
4
|
+
applyBasicWebhookRequestGuards,
|
|
5
|
+
applySetupAccountConfigPatch,
|
|
6
|
+
type BaseProbeResult,
|
|
7
|
+
type BaseTokenResolution,
|
|
8
|
+
buildBaseAccountStatusSnapshot,
|
|
9
|
+
buildChannelConfigSchema,
|
|
10
|
+
buildSecretInputSchema,
|
|
11
|
+
buildSingleChannelSecretPromptState,
|
|
12
|
+
buildTokenChannelStatusSummary,
|
|
13
|
+
type ChannelAccountSnapshot,
|
|
14
|
+
type ChannelMessageActionAdapter,
|
|
15
|
+
type ChannelMessageActionName,
|
|
16
|
+
type ChannelPlugin,
|
|
17
|
+
type ChannelStatusIssue,
|
|
18
|
+
chunkTextForOutbound,
|
|
19
|
+
createChannelPairingController,
|
|
20
|
+
createChannelMessageReplyPipeline,
|
|
21
|
+
createDedupeCache,
|
|
22
|
+
createFixedWindowRateLimiter,
|
|
23
|
+
createWebhookAnomalyTracker,
|
|
24
|
+
DEFAULT_ACCOUNT_ID,
|
|
25
|
+
deliverTextOrMediaReply,
|
|
26
|
+
formatAllowFromLowercase,
|
|
27
|
+
formatPairingApproveHint,
|
|
28
|
+
type GroupPolicy,
|
|
29
|
+
hasConfiguredSecretInput,
|
|
30
|
+
isNormalizedSenderAllowed,
|
|
31
|
+
isNumericTargetId,
|
|
32
|
+
jsonResult,
|
|
33
|
+
logTypingFailure,
|
|
34
|
+
type MarkdownTableMode,
|
|
35
|
+
mergeAllowFromEntries,
|
|
36
|
+
migrateBaseNameToDefaultAccount,
|
|
37
|
+
normalizeAccountId,
|
|
38
|
+
normalizeResolvedSecretInputString,
|
|
39
|
+
normalizeSecretInputString,
|
|
40
|
+
type AutoBotConfig,
|
|
41
|
+
type OutboundReplyPayload,
|
|
42
|
+
PAIRING_APPROVED_MESSAGE,
|
|
43
|
+
type PluginRuntime,
|
|
44
|
+
promptSingleChannelSecretInput,
|
|
45
|
+
readJsonWebhookBodyOrReject,
|
|
46
|
+
readStringParam,
|
|
47
|
+
registerPluginHttpRoute,
|
|
48
|
+
type RegisterWebhookPluginRouteOptions,
|
|
49
|
+
registerWebhookTarget,
|
|
50
|
+
type RegisterWebhookTargetOptions,
|
|
51
|
+
registerWebhookTargetWithPluginRoute,
|
|
52
|
+
type ReplyPayload,
|
|
53
|
+
resolveClientIp,
|
|
54
|
+
resolveDefaultGroupPolicy,
|
|
55
|
+
resolveInboundRouteEnvelopeBuilderWithRuntime,
|
|
56
|
+
resolveOpenProviderRuntimeGroupPolicy,
|
|
57
|
+
resolveWebhookPath,
|
|
58
|
+
resolveWebhookTargetWithAuthOrRejectSync,
|
|
59
|
+
runSingleChannelSecretStep,
|
|
60
|
+
type RuntimeEnv,
|
|
61
|
+
type SecretInput,
|
|
62
|
+
sendPayloadWithChunkedTextAndMedia,
|
|
63
|
+
setTopLevelChannelDmPolicyWithAllowFrom,
|
|
64
|
+
setZaloRuntime,
|
|
65
|
+
waitForAbortSignal,
|
|
66
|
+
warnMissingProviderGroupPolicyFallbackOnce,
|
|
67
|
+
WEBHOOK_ANOMALY_COUNTER_DEFAULTS,
|
|
68
|
+
WEBHOOK_RATE_LIMIT_DEFAULTS,
|
|
69
|
+
withResolvedWebhookRequestPipeline,
|
|
70
|
+
type WizardPrompter,
|
|
71
|
+
} from "./src/runtime-api.js";
|
package/setup-api.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { loadBundledEntryExportSync } from "autobot/plugin-sdk/channel-entry-contract";
|
|
2
|
+
|
|
3
|
+
type SetupSurfaceModule = typeof import("./src/setup-surface.js");
|
|
4
|
+
|
|
5
|
+
function createLazyObjectValue<T extends object>(load: () => T): T {
|
|
6
|
+
return new Proxy({} as T, {
|
|
7
|
+
get(_target, property, receiver) {
|
|
8
|
+
return Reflect.get(load(), property, receiver);
|
|
9
|
+
},
|
|
10
|
+
has(_target, property) {
|
|
11
|
+
return property in load();
|
|
12
|
+
},
|
|
13
|
+
ownKeys() {
|
|
14
|
+
return Reflect.ownKeys(load());
|
|
15
|
+
},
|
|
16
|
+
getOwnPropertyDescriptor(_target, property) {
|
|
17
|
+
const descriptor = Object.getOwnPropertyDescriptor(load(), property);
|
|
18
|
+
return descriptor ? { ...descriptor, configurable: true } : undefined;
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function loadSetupSurfaceModule(): SetupSurfaceModule {
|
|
24
|
+
return loadBundledEntryExportSync<SetupSurfaceModule>(import.meta.url, {
|
|
25
|
+
specifier: "./src/setup-surface.js",
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export { zaloDmPolicy, zaloSetupAdapter, createZaloSetupWizardProxy } from "./src/setup-core.js";
|
|
30
|
+
export { resolveZaloRuntimeGroupPolicy } from "./src/group-access.js";
|
|
31
|
+
|
|
32
|
+
export const zaloSetupWizard: SetupSurfaceModule["zaloSetupWizard"] = createLazyObjectValue(
|
|
33
|
+
() => loadSetupSurfaceModule().zaloSetupWizard as object,
|
|
34
|
+
) as SetupSurfaceModule["zaloSetupWizard"];
|
package/setup-entry.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { defineBundledChannelSetupEntry } from "autobot/plugin-sdk/channel-entry-contract";
|
|
2
|
+
|
|
3
|
+
export default defineBundledChannelSetupEntry({
|
|
4
|
+
importMetaUrl: import.meta.url,
|
|
5
|
+
plugin: {
|
|
6
|
+
specifier: "./api.js",
|
|
7
|
+
exportName: "zaloPlugin",
|
|
8
|
+
},
|
|
9
|
+
secrets: {
|
|
10
|
+
specifier: "./secret-contract-api.js",
|
|
11
|
+
exportName: "channelSecrets",
|
|
12
|
+
},
|
|
13
|
+
});
|
package/src/accounts.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createAccountListHelpers,
|
|
3
|
+
resolveMergedAccountConfig,
|
|
4
|
+
} from "autobot/plugin-sdk/account-helpers";
|
|
5
|
+
import { normalizeAccountId } from "autobot/plugin-sdk/account-id";
|
|
6
|
+
import type { AutoBotConfig } from "autobot/plugin-sdk/config-contracts";
|
|
7
|
+
import { normalizeOptionalString } from "autobot/plugin-sdk/string-coerce-runtime";
|
|
8
|
+
import { resolveZaloToken } from "./token.js";
|
|
9
|
+
import type { ResolvedZaloAccount, ZaloAccountConfig, ZaloConfig } from "./types.js";
|
|
10
|
+
|
|
11
|
+
export type { ResolvedZaloAccount };
|
|
12
|
+
|
|
13
|
+
const { listAccountIds: listZaloAccountIds, resolveDefaultAccountId: resolveDefaultZaloAccountId } =
|
|
14
|
+
createAccountListHelpers("zalo", {
|
|
15
|
+
implicitDefaultAccount: {
|
|
16
|
+
channelKeys: ["botToken", "tokenFile"],
|
|
17
|
+
envVars: ["ZALO_BOT_TOKEN"],
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
export { listZaloAccountIds, resolveDefaultZaloAccountId };
|
|
21
|
+
|
|
22
|
+
function mergeZaloAccountConfig(cfg: AutoBotConfig, accountId: string): ZaloAccountConfig {
|
|
23
|
+
return resolveMergedAccountConfig<ZaloAccountConfig>({
|
|
24
|
+
channelConfig: cfg.channels?.zalo as ZaloAccountConfig | undefined,
|
|
25
|
+
accounts: (cfg.channels?.zalo as ZaloConfig | undefined)?.accounts as
|
|
26
|
+
| Record<string, Partial<ZaloAccountConfig>>
|
|
27
|
+
| undefined,
|
|
28
|
+
accountId,
|
|
29
|
+
omitKeys: ["defaultAccount"],
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function resolveZaloAccount(params: {
|
|
34
|
+
cfg: AutoBotConfig;
|
|
35
|
+
accountId?: string | null;
|
|
36
|
+
allowUnresolvedSecretRef?: boolean;
|
|
37
|
+
}): ResolvedZaloAccount {
|
|
38
|
+
const accountId = normalizeAccountId(
|
|
39
|
+
params.accountId ?? (params.cfg.channels?.zalo as ZaloConfig | undefined)?.defaultAccount,
|
|
40
|
+
);
|
|
41
|
+
const baseEnabled = (params.cfg.channels?.zalo as ZaloConfig | undefined)?.enabled !== false;
|
|
42
|
+
const merged = mergeZaloAccountConfig(params.cfg, accountId);
|
|
43
|
+
const accountEnabled = merged.enabled !== false;
|
|
44
|
+
const enabled = baseEnabled && accountEnabled;
|
|
45
|
+
const tokenResolution = resolveZaloToken(
|
|
46
|
+
params.cfg.channels?.zalo as ZaloConfig | undefined,
|
|
47
|
+
accountId,
|
|
48
|
+
{ allowUnresolvedSecretRef: params.allowUnresolvedSecretRef },
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
accountId,
|
|
53
|
+
name: normalizeOptionalString(merged.name),
|
|
54
|
+
enabled,
|
|
55
|
+
token: tokenResolution.token,
|
|
56
|
+
tokenSource: tokenResolution.source,
|
|
57
|
+
config: merged,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function listEnabledZaloAccounts(cfg: AutoBotConfig): ResolvedZaloAccount[] {
|
|
62
|
+
return listZaloAccountIds(cfg)
|
|
63
|
+
.map((accountId) => resolveZaloAccount({ cfg, accountId }))
|
|
64
|
+
.filter((account) => account.enabled);
|
|
65
|
+
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { jsonResult, readStringParam } from "autobot/plugin-sdk/channel-actions";
|
|
2
|
+
import type {
|
|
3
|
+
ChannelMessageActionAdapter,
|
|
4
|
+
ChannelMessageActionName,
|
|
5
|
+
} from "autobot/plugin-sdk/channel-contract";
|
|
6
|
+
import type { AutoBotConfig } from "autobot/plugin-sdk/config-contracts";
|
|
7
|
+
import { createLazyRuntimeNamedExport } from "autobot/plugin-sdk/lazy-runtime";
|
|
8
|
+
import { extractToolSend } from "autobot/plugin-sdk/tool-send";
|
|
9
|
+
import { listEnabledZaloAccounts, resolveZaloAccount } from "./accounts.js";
|
|
10
|
+
|
|
11
|
+
const loadZaloActionsRuntime = createLazyRuntimeNamedExport(
|
|
12
|
+
() => import("./actions.runtime.js"),
|
|
13
|
+
"zaloActionsRuntime",
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
const providerId = "zalo";
|
|
17
|
+
|
|
18
|
+
function listEnabledAccounts(cfg: AutoBotConfig, accountId?: string | null) {
|
|
19
|
+
return (
|
|
20
|
+
accountId ? [resolveZaloAccount({ cfg, accountId })] : listEnabledZaloAccounts(cfg)
|
|
21
|
+
).filter((account) => account.enabled && account.tokenSource !== "none");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const zaloMessageActions: ChannelMessageActionAdapter = {
|
|
25
|
+
describeMessageTool: ({ cfg, accountId }) => {
|
|
26
|
+
const accounts = listEnabledAccounts(cfg, accountId);
|
|
27
|
+
if (accounts.length === 0) {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
const actions = new Set<ChannelMessageActionName>(["send"]);
|
|
31
|
+
return { actions: Array.from(actions), capabilities: [] };
|
|
32
|
+
},
|
|
33
|
+
extractToolSend: ({ args }) => extractToolSend(args, "sendMessage"),
|
|
34
|
+
handleAction: async ({ action, params, cfg, accountId }) => {
|
|
35
|
+
if (action === "send") {
|
|
36
|
+
const to = readStringParam(params, "to", { required: true });
|
|
37
|
+
const content = readStringParam(params, "message", {
|
|
38
|
+
required: true,
|
|
39
|
+
allowEmpty: true,
|
|
40
|
+
});
|
|
41
|
+
const mediaUrl = readStringParam(params, "media", { trim: false });
|
|
42
|
+
|
|
43
|
+
const { sendMessageZalo } = await loadZaloActionsRuntime();
|
|
44
|
+
const result = await sendMessageZalo(to ?? "", content ?? "", {
|
|
45
|
+
accountId: accountId ?? undefined,
|
|
46
|
+
mediaUrl: mediaUrl ?? undefined,
|
|
47
|
+
cfg: cfg,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
if (!result.ok) {
|
|
51
|
+
return jsonResult({
|
|
52
|
+
ok: false,
|
|
53
|
+
error: result.error ?? "Failed to send Zalo message",
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return jsonResult({ ok: true, to, messageId: result.messageId });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
throw new Error(`Action ${action} is not supported for provider ${providerId}.`);
|
|
61
|
+
},
|
|
62
|
+
};
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zalo Bot API client
|
|
3
|
+
* @see https://bot.zaloplatforms.com/docs
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { resolvePinnedHostnameWithPolicy, type SsrFPolicy } from "autobot/plugin-sdk/ssrf-runtime";
|
|
7
|
+
|
|
8
|
+
const ZALO_API_BASE = "https://bot-api.zaloplatforms.com";
|
|
9
|
+
const ZALO_MEDIA_SSRF_POLICY: SsrFPolicy = {};
|
|
10
|
+
|
|
11
|
+
export type ZaloFetch = (input: string, init?: RequestInit) => Promise<Response>;
|
|
12
|
+
|
|
13
|
+
export type ZaloApiResponse<T = unknown> = {
|
|
14
|
+
ok: boolean;
|
|
15
|
+
result?: T;
|
|
16
|
+
error_code?: number;
|
|
17
|
+
description?: string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type ZaloBotInfo = {
|
|
21
|
+
id: string;
|
|
22
|
+
name: string;
|
|
23
|
+
avatar?: string;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type ZaloMessage = {
|
|
27
|
+
message_id: string;
|
|
28
|
+
from: {
|
|
29
|
+
id: string;
|
|
30
|
+
name?: string;
|
|
31
|
+
display_name?: string;
|
|
32
|
+
avatar?: string;
|
|
33
|
+
is_bot?: boolean;
|
|
34
|
+
};
|
|
35
|
+
chat: {
|
|
36
|
+
id: string;
|
|
37
|
+
chat_type: "PRIVATE" | "GROUP";
|
|
38
|
+
};
|
|
39
|
+
date: number;
|
|
40
|
+
text?: string;
|
|
41
|
+
photo_url?: string;
|
|
42
|
+
caption?: string;
|
|
43
|
+
sticker?: string;
|
|
44
|
+
message_type?: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export type ZaloUpdate = {
|
|
48
|
+
event_name:
|
|
49
|
+
| "message.text.received"
|
|
50
|
+
| "message.image.received"
|
|
51
|
+
| "message.sticker.received"
|
|
52
|
+
| "message.unsupported.received";
|
|
53
|
+
message?: ZaloMessage;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export type ZaloSendMessageParams = {
|
|
57
|
+
chat_id: string;
|
|
58
|
+
text: string;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export type ZaloSendPhotoParams = {
|
|
62
|
+
chat_id: string;
|
|
63
|
+
photo: string;
|
|
64
|
+
caption?: string;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type ZaloSendChatActionParams = {
|
|
68
|
+
chat_id: string;
|
|
69
|
+
action: "typing" | "upload_photo";
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export type ZaloSetWebhookParams = {
|
|
73
|
+
url: string;
|
|
74
|
+
secret_token: string;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export type ZaloWebhookInfo = {
|
|
78
|
+
url?: string;
|
|
79
|
+
updated_at?: number;
|
|
80
|
+
has_custom_certificate?: boolean;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
export type ZaloGetUpdatesParams = {
|
|
84
|
+
/** Timeout in seconds (passed as string to API) */
|
|
85
|
+
timeout?: number;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export class ZaloApiError extends Error {
|
|
89
|
+
constructor(
|
|
90
|
+
message: string,
|
|
91
|
+
public readonly errorCode?: number,
|
|
92
|
+
public readonly description?: string,
|
|
93
|
+
) {
|
|
94
|
+
super(message);
|
|
95
|
+
this.name = "ZaloApiError";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** True if this is a long-polling timeout (no updates available) */
|
|
99
|
+
get isPollingTimeout(): boolean {
|
|
100
|
+
return this.errorCode === 408;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Call the Zalo Bot API
|
|
106
|
+
*/
|
|
107
|
+
export async function callZaloApi<T = unknown>(
|
|
108
|
+
method: string,
|
|
109
|
+
token: string,
|
|
110
|
+
body?: Record<string, unknown>,
|
|
111
|
+
options?: { timeoutMs?: number; fetch?: ZaloFetch },
|
|
112
|
+
): Promise<ZaloApiResponse<T>> {
|
|
113
|
+
const url = `${ZALO_API_BASE}/bot${token}/${method}`;
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
const timeoutId = options?.timeoutMs
|
|
116
|
+
? setTimeout(() => controller.abort(), options.timeoutMs)
|
|
117
|
+
: undefined;
|
|
118
|
+
const fetcher = options?.fetch ?? fetch;
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
const response = await fetcher(url, {
|
|
122
|
+
method: "POST",
|
|
123
|
+
headers: {
|
|
124
|
+
"Content-Type": "application/json",
|
|
125
|
+
},
|
|
126
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
127
|
+
signal: controller.signal,
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const data = (await response.json()) as ZaloApiResponse<T>;
|
|
131
|
+
|
|
132
|
+
if (!data.ok) {
|
|
133
|
+
throw new ZaloApiError(
|
|
134
|
+
data.description ?? `Zalo API error: ${method}`,
|
|
135
|
+
data.error_code,
|
|
136
|
+
data.description,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return data;
|
|
141
|
+
} finally {
|
|
142
|
+
if (timeoutId) {
|
|
143
|
+
clearTimeout(timeoutId);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Validate bot token and get bot info
|
|
150
|
+
*/
|
|
151
|
+
export async function getMe(
|
|
152
|
+
token: string,
|
|
153
|
+
timeoutMs?: number,
|
|
154
|
+
fetcher?: ZaloFetch,
|
|
155
|
+
): Promise<ZaloApiResponse<ZaloBotInfo>> {
|
|
156
|
+
return callZaloApi<ZaloBotInfo>("getMe", token, undefined, { timeoutMs, fetch: fetcher });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Send a text message
|
|
161
|
+
*/
|
|
162
|
+
export async function sendMessage(
|
|
163
|
+
token: string,
|
|
164
|
+
params: ZaloSendMessageParams,
|
|
165
|
+
fetcher?: ZaloFetch,
|
|
166
|
+
): Promise<ZaloApiResponse<ZaloMessage>> {
|
|
167
|
+
return callZaloApi<ZaloMessage>("sendMessage", token, params, { fetch: fetcher });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Send a photo message
|
|
172
|
+
*/
|
|
173
|
+
export async function sendPhoto(
|
|
174
|
+
token: string,
|
|
175
|
+
params: ZaloSendPhotoParams,
|
|
176
|
+
fetcher?: ZaloFetch,
|
|
177
|
+
): Promise<ZaloApiResponse<ZaloMessage>> {
|
|
178
|
+
const photoUrl = params.photo.trim();
|
|
179
|
+
let parsedPhotoUrl: URL;
|
|
180
|
+
try {
|
|
181
|
+
parsedPhotoUrl = new URL(photoUrl);
|
|
182
|
+
} catch {
|
|
183
|
+
throw new Error("Zalo photo URL must be an absolute HTTP or HTTPS URL");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (parsedPhotoUrl.protocol !== "http:" && parsedPhotoUrl.protocol !== "https:") {
|
|
187
|
+
throw new Error("Zalo photo URL must use HTTP or HTTPS");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
await resolvePinnedHostnameWithPolicy(parsedPhotoUrl.hostname, {
|
|
191
|
+
policy: ZALO_MEDIA_SSRF_POLICY,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
return callZaloApi<ZaloMessage>(
|
|
195
|
+
"sendPhoto",
|
|
196
|
+
token,
|
|
197
|
+
{ ...params, photo: parsedPhotoUrl.href },
|
|
198
|
+
{ fetch: fetcher },
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Send a temporary chat action such as typing.
|
|
204
|
+
*/
|
|
205
|
+
export async function sendChatAction(
|
|
206
|
+
token: string,
|
|
207
|
+
params: ZaloSendChatActionParams,
|
|
208
|
+
fetcher?: ZaloFetch,
|
|
209
|
+
timeoutMs?: number,
|
|
210
|
+
): Promise<ZaloApiResponse<boolean>> {
|
|
211
|
+
return callZaloApi<boolean>("sendChatAction", token, params, {
|
|
212
|
+
timeoutMs,
|
|
213
|
+
fetch: fetcher,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Get updates using long polling (dev/testing only)
|
|
219
|
+
* Note: Zalo returns a single update per call, not an array like Telegram
|
|
220
|
+
*/
|
|
221
|
+
export async function getUpdates(
|
|
222
|
+
token: string,
|
|
223
|
+
params?: ZaloGetUpdatesParams,
|
|
224
|
+
fetcher?: ZaloFetch,
|
|
225
|
+
): Promise<ZaloApiResponse<ZaloUpdate>> {
|
|
226
|
+
const pollTimeoutSec = params?.timeout ?? 30;
|
|
227
|
+
const timeoutMs = (pollTimeoutSec + 5) * 1000;
|
|
228
|
+
const body = { timeout: String(pollTimeoutSec) };
|
|
229
|
+
return callZaloApi<ZaloUpdate>("getUpdates", token, body, { timeoutMs, fetch: fetcher });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Set webhook URL for receiving updates
|
|
234
|
+
*/
|
|
235
|
+
export async function setWebhook(
|
|
236
|
+
token: string,
|
|
237
|
+
params: ZaloSetWebhookParams,
|
|
238
|
+
fetcher?: ZaloFetch,
|
|
239
|
+
): Promise<ZaloApiResponse<ZaloWebhookInfo>> {
|
|
240
|
+
return callZaloApi<ZaloWebhookInfo>("setWebhook", token, params, { fetch: fetcher });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Delete webhook configuration
|
|
245
|
+
*/
|
|
246
|
+
export async function deleteWebhook(
|
|
247
|
+
token: string,
|
|
248
|
+
fetcher?: ZaloFetch,
|
|
249
|
+
timeoutMs?: number,
|
|
250
|
+
): Promise<ZaloApiResponse<ZaloWebhookInfo>> {
|
|
251
|
+
return callZaloApi<ZaloWebhookInfo>("deleteWebhook", token, undefined, {
|
|
252
|
+
timeoutMs,
|
|
253
|
+
fetch: fetcher,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Get current webhook info
|
|
259
|
+
*/
|
|
260
|
+
export async function getWebhookInfo(
|
|
261
|
+
token: string,
|
|
262
|
+
fetcher?: ZaloFetch,
|
|
263
|
+
): Promise<ZaloApiResponse<ZaloWebhookInfo>> {
|
|
264
|
+
return callZaloApi<ZaloWebhookInfo>("getWebhookInfo", token, undefined, { fetch: fetcher });
|
|
265
|
+
}
|