@theowlops/channelhub 1.0.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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -0
  3. package/bin/cli.ts +36 -0
  4. package/dist/bridges/mcp/index.d.ts +14 -0
  5. package/dist/bridges/mcp/index.js +96 -0
  6. package/dist/bridges/webhook/index.d.ts +32 -0
  7. package/dist/bridges/webhook/index.js +123 -0
  8. package/dist/channels/discord/adapter.d.ts +24 -0
  9. package/dist/channels/discord/index.d.ts +1 -0
  10. package/dist/channels/discord/index.js +130 -0
  11. package/dist/channels/slack/adapter.d.ts +20 -0
  12. package/dist/channels/slack/index.d.ts +1 -0
  13. package/dist/channels/slack/index.js +122 -0
  14. package/dist/channels/telegram/adapter.d.ts +21 -0
  15. package/dist/channels/telegram/index.d.ts +2 -0
  16. package/dist/channels/telegram/index.js +179 -0
  17. package/dist/channels/telegram/types.d.ts +6 -0
  18. package/dist/channels/zalo/adapter.d.ts +22 -0
  19. package/dist/channels/zalo/index.d.ts +5 -0
  20. package/dist/channels/zalo/index.js +38337 -0
  21. package/dist/commands/modules/general.d.ts +4 -0
  22. package/dist/commands/modules/group.d.ts +4 -0
  23. package/dist/commands/modules/reaction.d.ts +4 -0
  24. package/dist/commands/router.d.ts +7 -0
  25. package/dist/commands/types.d.ts +15 -0
  26. package/dist/config/env.d.ts +13 -0
  27. package/dist/core/adapter.d.ts +12 -0
  28. package/dist/core/bus.d.ts +12 -0
  29. package/dist/core/context.d.ts +9 -0
  30. package/dist/core/hub.d.ts +14 -0
  31. package/dist/core/index.d.ts +5 -0
  32. package/dist/core/index.js +99 -0
  33. package/dist/core/types.d.ts +63 -0
  34. package/dist/index.cjs +39235 -0
  35. package/dist/index.d.ts +16 -0
  36. package/dist/index.js +39191 -0
  37. package/dist/login_personal.js +60 -0
  38. package/dist/oa/client.d.ts +25 -0
  39. package/dist/oa/index.d.ts +3 -0
  40. package/dist/oa/index.js +556 -0
  41. package/dist/personal/client.d.ts +162 -0
  42. package/dist/personal/index.d.ts +5 -0
  43. package/dist/personal/index.js +37098 -0
  44. package/package.json +107 -0
@@ -0,0 +1,25 @@
1
+ export interface OAResponse<T = any> {
2
+ error: number;
3
+ message: string;
4
+ data?: T;
5
+ }
6
+ export declare class ZaloOABot {
7
+ private accessToken;
8
+ private baseUrl;
9
+ constructor(accessToken?: string);
10
+ setAccessToken(token: string): void;
11
+ private request;
12
+ sendConsultantText(userId: string, text: string): Promise<OAResponse<unknown>>;
13
+ sendConsultantImage(userId: string, attachmentId: string, text?: string): Promise<OAResponse<unknown>>;
14
+ sendTransactionMessage(userId: string, templateId: string, templateData: Record<string, any>): Promise<OAResponse<unknown>>;
15
+ sendPromotionMessage(userId: string, templateId: string, templateData: Record<string, any>): Promise<OAResponse<unknown>>;
16
+ getProfile(userId: string): Promise<OAResponse<unknown>>;
17
+ getFollowers(offset?: number, count?: number): Promise<OAResponse<unknown>>;
18
+ getTags(): Promise<OAResponse<unknown>>;
19
+ tagUser(userId: string, tagName: string): Promise<OAResponse<unknown>>;
20
+ removeTag(userId: string, tagName: string): Promise<OAResponse<unknown>>;
21
+ uploadImage(imageBlob: Blob): Promise<OAResponse<{
22
+ attachment_id: string;
23
+ }>>;
24
+ refreshAccessToken(refreshToken?: string): Promise<any>;
25
+ }
@@ -0,0 +1,3 @@
1
+ import { ZaloOABot } from "./client.js";
2
+ export * from "./client.js";
3
+ export declare function initOABot(): ZaloOABot;
@@ -0,0 +1,556 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ if (mod && typeof mod === "object" || typeof mod === "function") {
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ }
30
+ if (canCache)
31
+ cache.set(mod, to);
32
+ return to;
33
+ };
34
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
36
+
37
+ // node_modules/dotenv/package.json
38
+ var require_package = __commonJS(function(exports, module) {
39
+ module.exports = {
40
+ name: "dotenv",
41
+ version: "16.6.1",
42
+ description: "Loads environment variables from .env file",
43
+ main: "lib/main.js",
44
+ types: "lib/main.d.ts",
45
+ exports: {
46
+ ".": {
47
+ types: "./lib/main.d.ts",
48
+ require: "./lib/main.js",
49
+ default: "./lib/main.js"
50
+ },
51
+ "./config": "./config.js",
52
+ "./config.js": "./config.js",
53
+ "./lib/env-options": "./lib/env-options.js",
54
+ "./lib/env-options.js": "./lib/env-options.js",
55
+ "./lib/cli-options": "./lib/cli-options.js",
56
+ "./lib/cli-options.js": "./lib/cli-options.js",
57
+ "./package.json": "./package.json"
58
+ },
59
+ scripts: {
60
+ "dts-check": "tsc --project tests/types/tsconfig.json",
61
+ lint: "standard",
62
+ pretest: "npm run lint && npm run dts-check",
63
+ test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
64
+ "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
65
+ prerelease: "npm test",
66
+ release: "standard-version"
67
+ },
68
+ repository: {
69
+ type: "git",
70
+ url: "git://github.com/motdotla/dotenv.git"
71
+ },
72
+ homepage: "https://github.com/motdotla/dotenv#readme",
73
+ funding: "https://dotenvx.com",
74
+ keywords: [
75
+ "dotenv",
76
+ "env",
77
+ ".env",
78
+ "environment",
79
+ "variables",
80
+ "config",
81
+ "settings"
82
+ ],
83
+ readmeFilename: "README.md",
84
+ license: "BSD-2-Clause",
85
+ devDependencies: {
86
+ "@types/node": "^18.11.3",
87
+ decache: "^4.6.2",
88
+ sinon: "^14.0.1",
89
+ standard: "^17.0.0",
90
+ "standard-version": "^9.5.0",
91
+ tap: "^19.2.0",
92
+ typescript: "^4.8.4"
93
+ },
94
+ engines: {
95
+ node: ">=12"
96
+ },
97
+ browser: {
98
+ fs: false
99
+ }
100
+ };
101
+ });
102
+
103
+ // node_modules/dotenv/lib/main.js
104
+ var require_main = __commonJS(function(exports, module) {
105
+ var fs = __require("fs");
106
+ var path = __require("path");
107
+ var os = __require("os");
108
+ var crypto = __require("crypto");
109
+ var packageJson = require_package();
110
+ var version = packageJson.version;
111
+ var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
112
+ function parse(src) {
113
+ const obj = {};
114
+ let lines = src.toString();
115
+ lines = lines.replace(/\r\n?/mg, `
116
+ `);
117
+ let match;
118
+ while ((match = LINE.exec(lines)) != null) {
119
+ const key = match[1];
120
+ let value = match[2] || "";
121
+ value = value.trim();
122
+ const maybeQuote = value[0];
123
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
124
+ if (maybeQuote === '"') {
125
+ value = value.replace(/\\n/g, `
126
+ `);
127
+ value = value.replace(/\\r/g, "\r");
128
+ }
129
+ obj[key] = value;
130
+ }
131
+ return obj;
132
+ }
133
+ function _parseVault(options) {
134
+ options = options || {};
135
+ const vaultPath = _vaultPath(options);
136
+ options.path = vaultPath;
137
+ const result = DotenvModule.configDotenv(options);
138
+ if (!result.parsed) {
139
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
140
+ err.code = "MISSING_DATA";
141
+ throw err;
142
+ }
143
+ const keys = _dotenvKey(options).split(",");
144
+ const length = keys.length;
145
+ let decrypted;
146
+ for (let i = 0;i < length; i++) {
147
+ try {
148
+ const key = keys[i].trim();
149
+ const attrs = _instructions(result, key);
150
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
151
+ break;
152
+ } catch (error) {
153
+ if (i + 1 >= length) {
154
+ throw error;
155
+ }
156
+ }
157
+ }
158
+ return DotenvModule.parse(decrypted);
159
+ }
160
+ function _warn(message) {
161
+ console.log(`[dotenv@${version}][WARN] ${message}`);
162
+ }
163
+ function _debug(message) {
164
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
165
+ }
166
+ function _log(message) {
167
+ console.log(`[dotenv@${version}] ${message}`);
168
+ }
169
+ function _dotenvKey(options) {
170
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
171
+ return options.DOTENV_KEY;
172
+ }
173
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
174
+ return process.env.DOTENV_KEY;
175
+ }
176
+ return "";
177
+ }
178
+ function _instructions(result, dotenvKey) {
179
+ let uri;
180
+ try {
181
+ uri = new URL(dotenvKey);
182
+ } catch (error) {
183
+ if (error.code === "ERR_INVALID_URL") {
184
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
185
+ err.code = "INVALID_DOTENV_KEY";
186
+ throw err;
187
+ }
188
+ throw error;
189
+ }
190
+ const key = uri.password;
191
+ if (!key) {
192
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
193
+ err.code = "INVALID_DOTENV_KEY";
194
+ throw err;
195
+ }
196
+ const environment = uri.searchParams.get("environment");
197
+ if (!environment) {
198
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
199
+ err.code = "INVALID_DOTENV_KEY";
200
+ throw err;
201
+ }
202
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
203
+ const ciphertext = result.parsed[environmentKey];
204
+ if (!ciphertext) {
205
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
206
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
207
+ throw err;
208
+ }
209
+ return { ciphertext, key };
210
+ }
211
+ function _vaultPath(options) {
212
+ let possibleVaultPath = null;
213
+ if (options && options.path && options.path.length > 0) {
214
+ if (Array.isArray(options.path)) {
215
+ for (const filepath of options.path) {
216
+ if (fs.existsSync(filepath)) {
217
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
218
+ }
219
+ }
220
+ } else {
221
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
222
+ }
223
+ } else {
224
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
225
+ }
226
+ if (fs.existsSync(possibleVaultPath)) {
227
+ return possibleVaultPath;
228
+ }
229
+ return null;
230
+ }
231
+ function _resolveHome(envPath) {
232
+ return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
233
+ }
234
+ function _configVault(options) {
235
+ const debug = Boolean(options && options.debug);
236
+ const quiet = options && "quiet" in options ? options.quiet : true;
237
+ if (debug || !quiet) {
238
+ _log("Loading env from encrypted .env.vault");
239
+ }
240
+ const parsed = DotenvModule._parseVault(options);
241
+ let processEnv = process.env;
242
+ if (options && options.processEnv != null) {
243
+ processEnv = options.processEnv;
244
+ }
245
+ DotenvModule.populate(processEnv, parsed, options);
246
+ return { parsed };
247
+ }
248
+ function configDotenv(options) {
249
+ const dotenvPath = path.resolve(process.cwd(), ".env");
250
+ let encoding = "utf8";
251
+ const debug = Boolean(options && options.debug);
252
+ const quiet = options && "quiet" in options ? options.quiet : true;
253
+ if (options && options.encoding) {
254
+ encoding = options.encoding;
255
+ } else {
256
+ if (debug) {
257
+ _debug("No encoding is specified. UTF-8 is used by default");
258
+ }
259
+ }
260
+ let optionPaths = [dotenvPath];
261
+ if (options && options.path) {
262
+ if (!Array.isArray(options.path)) {
263
+ optionPaths = [_resolveHome(options.path)];
264
+ } else {
265
+ optionPaths = [];
266
+ for (const filepath of options.path) {
267
+ optionPaths.push(_resolveHome(filepath));
268
+ }
269
+ }
270
+ }
271
+ let lastError;
272
+ const parsedAll = {};
273
+ for (const path of optionPaths) {
274
+ try {
275
+ const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
276
+ DotenvModule.populate(parsedAll, parsed, options);
277
+ } catch (e) {
278
+ if (debug) {
279
+ _debug(`Failed to load ${path} ${e.message}`);
280
+ }
281
+ lastError = e;
282
+ }
283
+ }
284
+ let processEnv = process.env;
285
+ if (options && options.processEnv != null) {
286
+ processEnv = options.processEnv;
287
+ }
288
+ DotenvModule.populate(processEnv, parsedAll, options);
289
+ if (debug || !quiet) {
290
+ const keysCount = Object.keys(parsedAll).length;
291
+ const shortPaths = [];
292
+ for (const filePath of optionPaths) {
293
+ try {
294
+ const relative2 = path.relative(process.cwd(), filePath);
295
+ shortPaths.push(relative2);
296
+ } catch (e) {
297
+ if (debug) {
298
+ _debug(`Failed to load ${filePath} ${e.message}`);
299
+ }
300
+ lastError = e;
301
+ }
302
+ }
303
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`);
304
+ }
305
+ if (lastError) {
306
+ return { parsed: parsedAll, error: lastError };
307
+ } else {
308
+ return { parsed: parsedAll };
309
+ }
310
+ }
311
+ function config(options) {
312
+ if (_dotenvKey(options).length === 0) {
313
+ return DotenvModule.configDotenv(options);
314
+ }
315
+ const vaultPath = _vaultPath(options);
316
+ if (!vaultPath) {
317
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
318
+ return DotenvModule.configDotenv(options);
319
+ }
320
+ return DotenvModule._configVault(options);
321
+ }
322
+ function decrypt(encrypted, keyStr) {
323
+ const key = Buffer.from(keyStr.slice(-64), "hex");
324
+ let ciphertext = Buffer.from(encrypted, "base64");
325
+ const nonce = ciphertext.subarray(0, 12);
326
+ const authTag = ciphertext.subarray(-16);
327
+ ciphertext = ciphertext.subarray(12, -16);
328
+ try {
329
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
330
+ aesgcm.setAuthTag(authTag);
331
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
332
+ } catch (error) {
333
+ const isRange = error instanceof RangeError;
334
+ const invalidKeyLength = error.message === "Invalid key length";
335
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
336
+ if (isRange || invalidKeyLength) {
337
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
338
+ err.code = "INVALID_DOTENV_KEY";
339
+ throw err;
340
+ } else if (decryptionFailed) {
341
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
342
+ err.code = "DECRYPTION_FAILED";
343
+ throw err;
344
+ } else {
345
+ throw error;
346
+ }
347
+ }
348
+ }
349
+ function populate(processEnv, parsed, options = {}) {
350
+ const debug = Boolean(options && options.debug);
351
+ const override = Boolean(options && options.override);
352
+ if (typeof parsed !== "object") {
353
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
354
+ err.code = "OBJECT_REQUIRED";
355
+ throw err;
356
+ }
357
+ for (const key of Object.keys(parsed)) {
358
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
359
+ if (override === true) {
360
+ processEnv[key] = parsed[key];
361
+ }
362
+ if (debug) {
363
+ if (override === true) {
364
+ _debug(`"${key}" is already defined and WAS overwritten`);
365
+ } else {
366
+ _debug(`"${key}" is already defined and was NOT overwritten`);
367
+ }
368
+ }
369
+ } else {
370
+ processEnv[key] = parsed[key];
371
+ }
372
+ }
373
+ }
374
+ var DotenvModule = {
375
+ configDotenv,
376
+ _configVault,
377
+ _parseVault,
378
+ config,
379
+ decrypt,
380
+ parse,
381
+ populate
382
+ };
383
+ module.exports.configDotenv = DotenvModule.configDotenv;
384
+ module.exports._configVault = DotenvModule._configVault;
385
+ module.exports._parseVault = DotenvModule._parseVault;
386
+ module.exports.config = DotenvModule.config;
387
+ module.exports.decrypt = DotenvModule.decrypt;
388
+ module.exports.parse = DotenvModule.parse;
389
+ module.exports.populate = DotenvModule.populate;
390
+ module.exports = DotenvModule;
391
+ });
392
+
393
+ // src/config/env.ts
394
+ var import_dotenv = __toESM(require_main(), 1);
395
+ import path from "node:path";
396
+ import_dotenv.default.config();
397
+ var CONFIG = {
398
+ PERSONAL: {
399
+ CRED_PATH: process.env.ZALO_CRED_PATH || path.resolve("./credentials.json"),
400
+ DEFAULT_PREFIX: "!"
401
+ },
402
+ OA: {
403
+ APP_ID: process.env.ZALO_OA_APP_ID || "",
404
+ APP_SECRET: process.env.ZALO_OA_APP_SECRET || "",
405
+ ACCESS_TOKEN: process.env.ZALO_OA_ACCESS_TOKEN || "",
406
+ REFRESH_TOKEN: process.env.ZALO_OA_REFRESH_TOKEN || "",
407
+ BASE_URL: "https://openapi.zalo.me/v3.0/oa"
408
+ }
409
+ };
410
+
411
+ // src/oa/client.ts
412
+ class ZaloOABot {
413
+ accessToken;
414
+ baseUrl;
415
+ constructor(accessToken = CONFIG.OA.ACCESS_TOKEN) {
416
+ this.accessToken = accessToken;
417
+ this.baseUrl = CONFIG.OA.BASE_URL;
418
+ }
419
+ setAccessToken(token) {
420
+ this.accessToken = token;
421
+ }
422
+ async request(endpoint, options = {}) {
423
+ const url = `${this.baseUrl}${endpoint}`;
424
+ const headers = {
425
+ "Content-Type": "application/json",
426
+ access_token: this.accessToken,
427
+ ...options.headers || {}
428
+ };
429
+ const res = await fetch(url, { ...options, headers });
430
+ return await res.json();
431
+ }
432
+ async sendConsultantText(userId, text) {
433
+ return await this.request("/message/cs", {
434
+ method: "POST",
435
+ body: JSON.stringify({ recipient: { user_id: userId }, message: { text } })
436
+ });
437
+ }
438
+ async sendConsultantImage(userId, attachmentId, text = "") {
439
+ return await this.request("/message/cs", {
440
+ method: "POST",
441
+ body: JSON.stringify({
442
+ recipient: { user_id: userId },
443
+ message: {
444
+ text,
445
+ attachment: {
446
+ type: "template",
447
+ payload: {
448
+ template_type: "media",
449
+ elements: [{ media_type: "image", attachment_id: attachmentId }]
450
+ }
451
+ }
452
+ }
453
+ })
454
+ });
455
+ }
456
+ async sendTransactionMessage(userId, templateId, templateData) {
457
+ return await this.request("/message/transaction", {
458
+ method: "POST",
459
+ body: JSON.stringify({
460
+ recipient: { user_id: userId },
461
+ message: {
462
+ attachment: {
463
+ type: "template",
464
+ payload: {
465
+ template_type: "transaction",
466
+ template_id: templateId,
467
+ template_data: templateData
468
+ }
469
+ }
470
+ }
471
+ })
472
+ });
473
+ }
474
+ async sendPromotionMessage(userId, templateId, templateData) {
475
+ return await this.request("/message/promotion", {
476
+ method: "POST",
477
+ body: JSON.stringify({
478
+ recipient: { user_id: userId },
479
+ message: {
480
+ attachment: {
481
+ type: "template",
482
+ payload: {
483
+ template_type: "promotion",
484
+ template_id: templateId,
485
+ template_data: templateData
486
+ }
487
+ }
488
+ }
489
+ })
490
+ });
491
+ }
492
+ async getProfile(userId) {
493
+ return await this.request(`/user/detail?data=${encodeURIComponent(JSON.stringify({ user_id: userId }))}`, {
494
+ method: "GET"
495
+ });
496
+ }
497
+ async getFollowers(offset = 0, count = 50) {
498
+ return await this.request(`/user/getlist?data=${encodeURIComponent(JSON.stringify({ offset, count }))}`, {
499
+ method: "GET"
500
+ });
501
+ }
502
+ async getTags() {
503
+ return await this.request("/tag/gettagsofoa", { method: "GET" });
504
+ }
505
+ async tagUser(userId, tagName) {
506
+ return await this.request("/tag/taguser", {
507
+ method: "POST",
508
+ body: JSON.stringify({ user_id: userId, tag_name: tagName })
509
+ });
510
+ }
511
+ async removeTag(userId, tagName) {
512
+ return await this.request("/tag/rmuserfromtag", {
513
+ method: "POST",
514
+ body: JSON.stringify({ user_id: userId, tag_name: tagName })
515
+ });
516
+ }
517
+ async uploadImage(imageBlob) {
518
+ const formData = new FormData;
519
+ formData.append("file", imageBlob);
520
+ const res = await fetch("https://openapi.zalo.me/v2.0/oa/upload/image", {
521
+ method: "POST",
522
+ headers: { access_token: this.accessToken },
523
+ body: formData
524
+ });
525
+ return await res.json();
526
+ }
527
+ async refreshAccessToken(refreshToken = CONFIG.OA.REFRESH_TOKEN) {
528
+ const params = new URLSearchParams({
529
+ app_id: CONFIG.OA.APP_ID,
530
+ grant_type: "refresh_token",
531
+ refresh_token: refreshToken
532
+ });
533
+ const res = await fetch("https://oauth.zaloapp.com/v4/oa/access_token", {
534
+ method: "POST",
535
+ headers: {
536
+ "Content-Type": "application/x-www-form-urlencoded",
537
+ secret_key: CONFIG.OA.APP_SECRET
538
+ },
539
+ body: params.toString()
540
+ });
541
+ const data = await res.json();
542
+ if (data.access_token) {
543
+ this.accessToken = data.access_token;
544
+ }
545
+ return data;
546
+ }
547
+ }
548
+
549
+ // src/oa/index.ts
550
+ function initOABot() {
551
+ return new ZaloOABot;
552
+ }
553
+ export {
554
+ ZaloOABot,
555
+ initOABot
556
+ };