whatsauto.js 1.3.0 → 2.0.1

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 (37) hide show
  1. package/README.md +0 -6
  2. package/dist/Defaults/index.d.ts +1 -1
  3. package/dist/Defaults/index.d.ts.map +1 -1
  4. package/dist/Defaults/index.js +8 -13
  5. package/dist/Error/index.js +2 -7
  6. package/dist/Logger/index.d.ts +1 -1
  7. package/dist/Logger/index.d.ts.map +1 -1
  8. package/dist/Logger/index.js +10 -11
  9. package/dist/Types/index.d.ts +15 -11
  10. package/dist/Types/index.d.ts.map +1 -1
  11. package/dist/Types/index.js +1 -2
  12. package/dist/Utils/helper.d.ts +3 -2
  13. package/dist/Utils/helper.d.ts.map +1 -1
  14. package/dist/Utils/helper.js +56 -96
  15. package/dist/Utils/index.d.ts +1 -1
  16. package/dist/Utils/index.d.ts.map +1 -1
  17. package/dist/Utils/index.js +1 -17
  18. package/dist/Utils/make-stiker.d.ts +1 -1
  19. package/dist/Utils/make-stiker.d.ts.map +1 -1
  20. package/dist/Utils/make-stiker.js +35 -50
  21. package/dist/WhatsApp/AutoWA.d.ts +17 -17
  22. package/dist/WhatsApp/AutoWA.d.ts.map +1 -1
  23. package/dist/WhatsApp/AutoWA.js +736 -798
  24. package/dist/WhatsApp/AutoWAEvent.js +3 -8
  25. package/dist/WhatsApp/index.d.ts +2 -2
  26. package/dist/WhatsApp/index.d.ts.map +1 -1
  27. package/dist/WhatsApp/index.js +4 -21
  28. package/dist/index.d.ts +5 -5
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +6 -22
  31. package/package.json +15 -5
  32. package/dist/Utils/set-credentials-dir.d.ts +0 -2
  33. package/dist/Utils/set-credentials-dir.d.ts.map +0 -1
  34. package/dist/Utils/set-credentials-dir.js +0 -15
  35. package/dist/WhatsApp/AutoWAManager.d.ts +0 -12
  36. package/dist/WhatsApp/AutoWAManager.d.ts.map +0 -1
  37. package/dist/WhatsApp/AutoWAManager.js +0 -68
@@ -1,885 +1,824 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
1
+ import path from "path";
2
+ import fs from "fs";
3
+ import makeWASocket, { DisconnectReason, downloadMediaMessage, Browsers, fetchLatestBaileysVersion, useMultiFileAuthState, proto, } from "@whiskeysockets/baileys";
4
+ import { CREDENTIALS, Messages } from "../Defaults/index.js";
5
+ import { ValidationError, AutoWAError } from "../Error/index.js";
6
+ import { parseMessageStatusCodeToReadable, getMediaMimeType, phoneToJid, createDelay, isSessionExist, getRandomFromArrays, getContextInfo, } from "../Utils/helper.js";
7
+ import AutoWAEvent from "./AutoWAEvent.js";
8
+ import mime from "mime";
9
+ import Logger from "../Logger/index.js";
10
+ import { makeWebpBuffer } from "../Utils/make-stiker.js";
11
+ import { sessions } from "./index.js";
12
+ import pino from "pino";
13
+ import qrcode from "qrcode-terminal";
14
+ const P = pino({
15
+ level: "silent",
17
16
  });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
17
+ export class AutoWA {
18
+ logger;
19
+ retryCount;
20
+ sock;
21
+ sessionId;
22
+ options;
23
+ events = new AutoWAEvent();
24
+ pairingCode;
25
+ defaultStickerProps = {
26
+ pack: "whatsauto.js",
27
+ author: "freack21",
28
+ media: null,
33
29
  };
34
- })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
- var __rest = (this && this.__rest) || function (s, e) {
45
- var t = {};
46
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
47
- t[p] = s[p];
48
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
49
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
50
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
51
- t[p[i]] = s[p[i]];
52
- }
53
- return t;
54
- };
55
- var __importDefault = (this && this.__importDefault) || function (mod) {
56
- return (mod && mod.__esModule) ? mod : { "default": mod };
57
- };
58
- Object.defineProperty(exports, "__esModule", { value: true });
59
- exports.AutoWA = void 0;
60
- const path_1 = __importDefault(require("path"));
61
- const fs_1 = __importDefault(require("fs"));
62
- const baileys_1 = __importStar(require("@whiskeysockets/baileys"));
63
- const Defaults_1 = require("../Defaults");
64
- const Error_1 = require("../Error");
65
- const helper_1 = require("../Utils/helper");
66
- const AutoWAEvent_1 = __importDefault(require("./AutoWAEvent"));
67
- const mime_1 = __importDefault(require("mime"));
68
- const Logger_1 = __importDefault(require("../Logger"));
69
- const make_stiker_1 = require("../Utils/make-stiker");
70
- const _1 = require(".");
71
- const P = require("pino")({
72
- level: "fatal",
73
- });
74
- const qrcode = require("qrcode-terminal");
75
- class AutoWA {
76
30
  constructor(sessionId, options) {
77
- this.events = new AutoWAEvent_1.default();
78
- this.defaultStickerProps = {
79
- pack: "whatsauto.js",
80
- author: "freack21",
81
- media: null,
82
- };
83
- if ((0, helper_1.isSessionExist)(sessionId) && _1.sessions.get(sessionId))
84
- throw new Error_1.ValidationError(Defaults_1.Messages.sessionAlreadyExist(sessionId));
31
+ if (isSessionExist(sessionId) && sessions.get(sessionId))
32
+ throw new ValidationError(Messages.sessionAlreadyExist(sessionId));
85
33
  const defaultOptions = {
86
34
  printQR: true,
87
35
  logging: true,
88
36
  };
89
37
  this.sessionId = sessionId;
90
- this.options = Object.assign(Object.assign({}, defaultOptions), options);
38
+ this.options = { ...defaultOptions, ...options };
91
39
  this.retryCount = 0;
92
- this.logger = new Logger_1.default(sessionId, this);
93
- _1.sessions.set(sessionId, this);
40
+ this.logger = new Logger(sessionId, this);
41
+ sessions.set(sessionId, this);
94
42
  this.logger.info("Created!");
95
43
  }
96
- setLogging(logging) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- this.options.logging = logging;
99
- });
44
+ async setLogging(logging) {
45
+ this.options.logging = logging;
100
46
  }
101
- initialize() {
102
- return __awaiter(this, void 0, void 0, function* () {
103
- this.logger.info("Initializing...");
104
- yield this.startWhatsApp(this.sessionId, this.options);
105
- });
47
+ async initialize() {
48
+ this.logger.info("Initializing...");
49
+ await this.startWhatsApp(this.sessionId, this.options);
106
50
  }
107
- startWhatsApp() {
108
- return __awaiter(this, arguments, void 0, function* (sessionId = "mySession", options = { printQR: true }) {
109
- if (typeof options.phoneNumber == "string") {
110
- if (options.phoneNumber === "")
111
- throw new Error_1.ValidationError(Defaults_1.Messages.paremetersNotValid("phoneNumber"));
112
- options.printQR = false;
113
- options.phoneNumber = (0, helper_1.phoneToJid)({
114
- from: options.phoneNumber,
115
- });
116
- }
117
- return this.startSocket(sessionId, options);
118
- });
51
+ async startWhatsApp(sessionId = "mySession", options = { printQR: true }) {
52
+ if (typeof options.phoneNumber == "string") {
53
+ if (options.phoneNumber === "")
54
+ throw new ValidationError(Messages.paremetersNotValid("phoneNumber"));
55
+ options.printQR = false;
56
+ options.phoneNumber = phoneToJid({
57
+ from: options.phoneNumber,
58
+ });
59
+ }
60
+ return this.startSocket(sessionId, options);
61
+ }
62
+ async startSocket(sessionId, options) {
63
+ try {
64
+ const { version } = await fetchLatestBaileysVersion();
65
+ const { state, saveCreds } = await useMultiFileAuthState(path.resolve(CREDENTIALS.DIR_NAME, sessionId + CREDENTIALS.PREFIX));
66
+ const [platform, browser] = getRandomFromArrays([Browsers.macOS, Browsers.ubuntu, Browsers.windows], ["Chrome", "Firefox", "Safari"]);
67
+ this.sock = makeWASocket({
68
+ version,
69
+ auth: state,
70
+ logger: P,
71
+ markOnlineOnConnect: false,
72
+ browser: platform(browser),
73
+ });
74
+ return this.setupWASocket(saveCreds);
75
+ }
76
+ catch (error) {
77
+ const msg = `Failed initiliaze WASocket: ${error.message}`;
78
+ this.logger.error(msg);
79
+ throw new AutoWAError(msg);
80
+ }
119
81
  }
120
- startSocket(sessionId, options) {
121
- return __awaiter(this, void 0, void 0, function* () {
122
- try {
123
- const { version } = yield (0, baileys_1.fetchLatestBaileysVersion)();
124
- const { state, saveCreds } = yield (0, baileys_1.useMultiFileAuthState)(path_1.default.resolve(Defaults_1.CREDENTIALS.DIR_NAME, sessionId + Defaults_1.CREDENTIALS.PREFIX));
125
- const [platform, browser] = (0, helper_1.getRandomFromArrays)([baileys_1.Browsers.macOS, baileys_1.Browsers.ubuntu, baileys_1.Browsers.windows], ["Chrome", "Firefox", "Safari"]);
126
- this.sock = (0, baileys_1.default)({
127
- version,
128
- auth: state,
129
- logger: P,
130
- markOnlineOnConnect: false,
131
- browser: platform(browser),
132
- });
133
- return this.setupWASocket(saveCreds);
134
- }
135
- catch (error) {
136
- const msg = `Failed initiliaze WASocket: ${error.message}`;
137
- this.logger.error(msg);
138
- throw new Error_1.AutoWAError(msg);
82
+ async setupWASocket(saveCreds) {
83
+ try {
84
+ if (typeof this.options.phoneNumber == "string" &&
85
+ !this.options.printQR &&
86
+ !this.pairingCode &&
87
+ !this.sock.authState.creds.registered) {
88
+ const phoneNumber = phoneToJid({ from: this.options.phoneNumber, reverse: true });
89
+ try {
90
+ this.pairingCode = await this.sock.requestPairingCode(phoneNumber);
91
+ this.logger.info(`Pairing Code: ${this.pairingCode}`);
92
+ this.events.emit("pairing-code", this.pairingCode);
93
+ this.retryCount = 0;
94
+ }
95
+ catch (error) {
96
+ this.retryCount++;
97
+ this.logger.warn(`Retry get pairing code for ${phoneNumber} (${this.retryCount}x)`);
98
+ await createDelay(1000);
99
+ return await this.startSocket(this.sessionId, this.options);
100
+ }
139
101
  }
140
- });
141
- }
142
- setupWASocket(saveCreds) {
143
- return __awaiter(this, void 0, void 0, function* () {
144
- try {
145
- if (typeof this.options.phoneNumber == "string" &&
146
- !this.options.printQR &&
147
- !this.pairingCode &&
148
- !this.sock.authState.creds.registered) {
149
- const phoneNumber = (0, helper_1.phoneToJid)({ from: this.options.phoneNumber, reverse: true });
150
- try {
151
- this.pairingCode = yield this.sock.requestPairingCode(phoneNumber);
152
- this.logger.info(`Pairing Code: ${this.pairingCode}`);
153
- this.events.emit("pairing-code", this.pairingCode);
154
- this.retryCount = 0;
155
- }
156
- catch (error) {
157
- this.retryCount++;
158
- this.logger.warn(`Retry get pairing code for ${phoneNumber} (${this.retryCount}x)`);
159
- yield (0, helper_1.createDelay)(1000);
160
- return yield this.startSocket(this.sessionId, this.options);
102
+ this.sock.ev.on("connection.update", async (update) => {
103
+ const { connection, lastDisconnect, qr } = update;
104
+ if (this.options.printQR && qr) {
105
+ this.logger.info("QR Updated!");
106
+ if (this.options.printQR) {
107
+ qrcode.generate(qr, { small: true });
161
108
  }
109
+ this.events.emit("qr", qr);
162
110
  }
163
- this.sock.ev.on("connection.update", (update) => __awaiter(this, void 0, void 0, function* () {
164
- var _a, _b;
165
- const { connection, lastDisconnect, qr } = update;
166
- if (this.options.printQR && qr) {
167
- this.logger.info("QR Updated!");
168
- if (this.options.printQR) {
169
- qrcode.generate(qr, { small: true });
170
- }
171
- this.events.emit("qr", qr);
111
+ if (connection == "connecting") {
112
+ this.logger.info("Connecting...");
113
+ this.events.emit("connecting");
114
+ }
115
+ if (connection === "close" && !this.pairingCode) {
116
+ const code = lastDisconnect?.error?.output?.statusCode;
117
+ let shouldRetry = false;
118
+ if (code == DisconnectReason.restartRequired) {
119
+ this.logger.info("Restarting...");
120
+ return await this.startSocket(this.sessionId, this.options);
172
121
  }
173
- if (connection == "connecting") {
174
- this.logger.info("Connecting...");
175
- this.events.emit("connecting");
122
+ else if (code == DisconnectReason.connectionLost) {
123
+ this.logger.warn("No Internet!");
124
+ shouldRetry = true;
176
125
  }
177
- if (connection === "close" && !this.pairingCode) {
178
- const code = (_b = (_a = lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.statusCode;
179
- let shouldRetry = false;
180
- if (code == baileys_1.DisconnectReason.restartRequired) {
181
- this.logger.info("Restarting...");
182
- return yield this.startSocket(this.sessionId, this.options);
183
- }
184
- else if (code == baileys_1.DisconnectReason.connectionLost) {
185
- this.logger.warn("No Internet!");
186
- shouldRetry = true;
187
- }
188
- else if (code == baileys_1.DisconnectReason.connectionClosed) {
189
- this.logger.warn("Connection Closed!");
190
- shouldRetry = true;
191
- }
192
- else if (code == baileys_1.DisconnectReason.loggedOut) {
193
- this.logger.warn("Logged Out!");
194
- }
195
- else if (code != baileys_1.DisconnectReason.loggedOut && this.retryCount < 10) {
196
- this.logger.warn("Connection Status : " + code);
197
- shouldRetry = true;
198
- }
199
- if (shouldRetry) {
200
- this.logger.warn("Retry connecting...");
201
- this.retryCount++;
202
- yield (0, helper_1.createDelay)(5000);
203
- return yield this.startSocket(this.sessionId, this.options);
204
- }
205
- else {
206
- this.retryCount = 0;
207
- this.logger.warn("Disconnected!");
208
- this.events.emit("disconnected");
209
- try {
210
- yield this.destroy(true);
211
- }
212
- catch (error) { }
213
- return;
214
- }
126
+ else if (code == DisconnectReason.connectionClosed) {
127
+ this.logger.warn("Connection Closed!");
128
+ shouldRetry = true;
215
129
  }
216
- if (connection == "open") {
217
- this.logger.info("Connected!");
218
- this.retryCount = 0;
219
- this.events.emit("connected");
130
+ else if (code == DisconnectReason.loggedOut) {
131
+ this.logger.warn("Logged Out!");
220
132
  }
221
- }));
222
- this.sock.ev.on("creds.update", () => __awaiter(this, void 0, void 0, function* () {
223
- yield saveCreds();
224
- }));
225
- this.sock.ev.on("messages.update", (message) => __awaiter(this, void 0, void 0, function* () {
226
- const msg = message[0];
227
- const data = Object.assign({ sessionId: this.sessionId, messageStatus: (0, helper_1.parseMessageStatusCodeToReadable)(msg.update.status) }, msg);
228
- this.events.emit("message-updated", data);
229
- }));
230
- this.sock.ev.on("messages.upsert", (new_message) => __awaiter(this, void 0, void 0, function* () {
231
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
232
- if (new_message.type == "append")
233
- return;
234
- const myJid = (0, helper_1.phoneToJid)({ from: this.sock.user.id });
235
- let msg = (_a = new_message.messages) === null || _a === void 0 ? void 0 : _a[0];
236
- const isDeletedMsg = ((_d = (_c = (_b = new_message.messages) === null || _b === void 0 ? void 0 : _b[0].message) === null || _c === void 0 ? void 0 : _c.protocolMessage) === null || _d === void 0 ? void 0 : _d.type) ==
237
- baileys_1.proto.Message.ProtocolMessage.Type.REVOKE;
238
- if (isDeletedMsg) {
239
- msg = Object.assign(Object.assign({}, (_e = new_message.messages) === null || _e === void 0 ? void 0 : _e[0]), { deletedMessage: {
240
- key: {
241
- id: (_j = (_h = (_g = (_f = new_message.messages) === null || _f === void 0 ? void 0 : _f[0].message) === null || _g === void 0 ? void 0 : _g.protocolMessage) === null || _h === void 0 ? void 0 : _h.key) === null || _j === void 0 ? void 0 : _j.id,
242
- },
243
- } });
133
+ else if (code != DisconnectReason.loggedOut && this.retryCount < 10) {
134
+ this.logger.warn("Connection Status : " + code);
135
+ shouldRetry = true;
136
+ }
137
+ if (shouldRetry) {
138
+ this.logger.warn("Retry connecting...");
139
+ this.retryCount++;
140
+ await createDelay(5000);
141
+ return await this.startSocket(this.sessionId, this.options);
244
142
  }
245
143
  else {
246
- if ((_k = msg.message) === null || _k === void 0 ? void 0 : _k.documentWithCaptionMessage)
247
- msg = Object.assign(Object.assign({}, msg), { message: msg.message.documentWithCaptionMessage.message });
248
- else if ((_l = msg.message) === null || _l === void 0 ? void 0 : _l.ephemeralMessage)
249
- msg = Object.assign(Object.assign({}, msg), { message: (_m = msg.message.ephemeralMessage) === null || _m === void 0 ? void 0 : _m.message });
250
- msg.sessionId = this.sessionId;
251
- let quotedMessage = null;
252
- const msgContextInfo = ((_p = (_o = msg.message) === null || _o === void 0 ? void 0 : _o.extendedTextMessage) === null || _p === void 0 ? void 0 : _p.contextInfo) ||
253
- ((_r = (_q = msg.message) === null || _q === void 0 ? void 0 : _q.imageMessage) === null || _r === void 0 ? void 0 : _r.contextInfo) ||
254
- ((_t = (_s = msg.message) === null || _s === void 0 ? void 0 : _s.videoMessage) === null || _t === void 0 ? void 0 : _t.contextInfo) ||
255
- ((_v = (_u = msg.message) === null || _u === void 0 ? void 0 : _u.stickerMessage) === null || _v === void 0 ? void 0 : _v.contextInfo) ||
256
- ((_x = (_w = msg.message) === null || _w === void 0 ? void 0 : _w.documentMessage) === null || _x === void 0 ? void 0 : _x.contextInfo);
257
- if (msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.quotedMessage) {
258
- quotedMessage = {
259
- key: {
260
- remoteJid: (_y = msg.key) === null || _y === void 0 ? void 0 : _y.remoteJid,
261
- id: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.stanzaId,
262
- participant: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.participant,
263
- fromMe: (msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.participant) == myJid,
264
- },
265
- message: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.quotedMessage,
266
- };
267
- }
268
- if ((_z = quotedMessage === null || quotedMessage === void 0 ? void 0 : quotedMessage.message) === null || _z === void 0 ? void 0 : _z.documentWithCaptionMessage) {
269
- quotedMessage = Object.assign(Object.assign({}, quotedMessage), { message: quotedMessage.message.documentWithCaptionMessage.message });
144
+ this.retryCount = 0;
145
+ this.logger.warn("Disconnected!");
146
+ this.events.emit("disconnected");
147
+ try {
148
+ await this.destroy(true);
270
149
  }
271
- msg.quotedMessage = quotedMessage;
150
+ catch (error) { }
151
+ return;
272
152
  }
273
- const mediaTypes = ["image", "audio", "video", "document"];
274
- const setupMsg = (msg) => {
275
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
276
- const text = ((_a = msg.message) === null || _a === void 0 ? void 0 : _a.conversation) ||
277
- ((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.extendedTextMessage) === null || _c === void 0 ? void 0 : _c.text) ||
278
- ((_e = (_d = msg.message) === null || _d === void 0 ? void 0 : _d.imageMessage) === null || _e === void 0 ? void 0 : _e.caption) ||
279
- ((_g = (_f = msg.message) === null || _f === void 0 ? void 0 : _f.videoMessage) === null || _g === void 0 ? void 0 : _g.caption) ||
280
- ((_j = (_h = msg.message) === null || _h === void 0 ? void 0 : _h.documentMessage) === null || _j === void 0 ? void 0 : _j.caption) ||
281
- "";
282
- msg.text = text;
283
- const mimeType = (0, helper_1.getMediaMimeType)(msg);
284
- const ext = mime_1.default.getExtension(mimeType);
285
- msg.hasMedia = mimeType !== "";
286
- msg.mediaType = "";
287
- if (mimeType)
288
- msg.mediaType =
289
- mediaTypes[mediaTypes.indexOf(mimeType.split("/")[0]) !== -1
290
- ? mediaTypes.indexOf(mimeType.split("/")[0])
291
- : 3];
292
- msg.downloadMedia = () => __awaiter(this, void 0, void 0, function* () { return Promise.resolve(null); });
293
- msg.toSticker = () => __awaiter(this, void 0, void 0, function* () { return Promise.resolve([null, false]); });
294
- if (msg.hasMedia) {
295
- msg.downloadMedia = (...args_1) => __awaiter(this, [...args_1], void 0, function* (opts = {}) { return this.downloadMedia(msg, opts, ext); });
296
- }
297
- if (msg.hasMedia || ((_k = msg.quotedMessage) === null || _k === void 0 ? void 0 : _k.hasMedia)) {
298
- msg.toSticker = (props) => __awaiter(this, void 0, void 0, function* () {
299
- let mediaBuf;
300
- if (msg.hasMedia && ["image", "video"].includes(msg.mediaType)) {
301
- mediaBuf = yield msg.downloadMedia({ asBuffer: true });
302
- }
303
- else if (msg.quotedMessage &&
304
- msg.quotedMessage.hasMedia &&
305
- ["image", "video"].includes(msg.quotedMessage.mediaType)) {
306
- mediaBuf = yield msg.quotedMessage.downloadMedia({ asBuffer: true });
307
- }
308
- if (!mediaBuf)
309
- return [null, false];
310
- const stickerProps = Object.assign(Object.assign(Object.assign({}, this.defaultStickerProps), props), { media: mediaBuf });
311
- const buffer = yield (0, make_stiker_1.makeWebpBuffer)(stickerProps);
312
- return [buffer, true];
313
- });
314
- }
315
- const from = ((_l = msg.key) === null || _l === void 0 ? void 0 : _l.remoteJid) || "";
316
- const participant = ((_m = msg.key) === null || _m === void 0 ? void 0 : _m.participant) || "";
317
- const isGroup = from.includes("@g.us");
318
- const isStory = from.includes("status@broadcast");
319
- const isReaction = ((_o = msg.message) === null || _o === void 0 ? void 0 : _o.reactionMessage) ? true : false;
320
- if ((_p = msg.key) === null || _p === void 0 ? void 0 : _p.fromMe) {
153
+ }
154
+ if (connection == "open") {
155
+ this.logger.info("Connected!");
156
+ this.retryCount = 0;
157
+ this.events.emit("connected");
158
+ }
159
+ });
160
+ this.sock.ev.on("creds.update", async () => {
161
+ await saveCreds();
162
+ });
163
+ this.sock.ev.on("messages.update", async (message) => {
164
+ const msg = message[0];
165
+ const data = {
166
+ sessionId: this.sessionId,
167
+ messageStatus: parseMessageStatusCodeToReadable(msg.update.status),
168
+ ...msg,
169
+ };
170
+ this.events.emit("message-updated", data);
171
+ });
172
+ this.sock.ev.on("messages.upsert", async (new_message) => {
173
+ if (new_message.type == "append")
174
+ return;
175
+ const myJid = phoneToJid({ from: this.sock.user.id });
176
+ let msg = new_message.messages?.[0];
177
+ const isDeletedMsg = new_message.messages?.[0].message?.protocolMessage?.type ==
178
+ proto.Message.ProtocolMessage.Type.REVOKE;
179
+ if (isDeletedMsg) {
180
+ msg = {
181
+ ...new_message.messages?.[0],
182
+ deletedMessage: {
183
+ key: {
184
+ id: new_message.messages?.[0].message?.protocolMessage?.key?.id,
185
+ },
186
+ },
187
+ };
188
+ }
189
+ else {
190
+ if (msg.message?.documentWithCaptionMessage)
191
+ msg = {
192
+ ...msg,
193
+ message: msg.message.documentWithCaptionMessage.message,
194
+ };
195
+ else if (msg.message?.ephemeralMessage)
196
+ msg = {
197
+ ...msg,
198
+ message: msg.message.ephemeralMessage?.message,
199
+ };
200
+ msg.sessionId = this.sessionId;
201
+ let quotedMessage = null;
202
+ const msgContextInfo = getContextInfo(msg);
203
+ if (msgContextInfo?.quotedMessage) {
204
+ quotedMessage = {
205
+ key: {
206
+ remoteJid: msg.key?.remoteJid,
207
+ remoteJidAlt: msg.key?.remoteJidAlt,
208
+ id: msgContextInfo?.stanzaId,
209
+ participant: msgContextInfo?.participant,
210
+ fromMe: msgContextInfo?.participant == myJid,
211
+ },
212
+ message: msgContextInfo?.quotedMessage,
213
+ };
214
+ }
215
+ if (quotedMessage?.message?.documentWithCaptionMessage) {
216
+ quotedMessage = {
217
+ ...quotedMessage,
218
+ message: quotedMessage.message.documentWithCaptionMessage.message,
219
+ };
220
+ }
221
+ msg.quotedMessage = quotedMessage;
222
+ }
223
+ const mediaTypes = ["image", "audio", "video", "document"];
224
+ const setupMsg = (msg) => {
225
+ const text = msg.message?.conversation ||
226
+ msg.message?.extendedTextMessage?.text ||
227
+ msg.message?.imageMessage?.caption ||
228
+ msg.message?.videoMessage?.caption ||
229
+ msg.message?.documentMessage?.caption ||
230
+ "";
231
+ msg.text = text;
232
+ const mimeType = getMediaMimeType(msg);
233
+ const ext = mime.getExtension(mimeType);
234
+ msg.hasMedia = mimeType !== "";
235
+ msg.mediaType = "";
236
+ if (mimeType)
237
+ msg.mediaType =
238
+ mediaTypes[mediaTypes.indexOf(mimeType.split("/")[0]) !== -1
239
+ ? mediaTypes.indexOf(mimeType.split("/")[0])
240
+ : 3];
241
+ msg.downloadMedia = async () => Promise.resolve(null);
242
+ msg.toSticker = async () => Promise.resolve([null, false]);
243
+ if (msg.hasMedia) {
244
+ msg.downloadMedia = async (opts = {}) => this.downloadMedia(msg, opts, ext);
245
+ }
246
+ if (msg.hasMedia || msg.quotedMessage?.hasMedia) {
247
+ msg.toSticker = async (props) => {
248
+ let mediaBuf;
249
+ if (msg.hasMedia && ["image", "video"].includes(msg.mediaType)) {
250
+ mediaBuf = await msg.downloadMedia({ asBuffer: true });
251
+ }
252
+ else if (msg.quotedMessage &&
253
+ msg.quotedMessage.hasMedia &&
254
+ ["image", "video"].includes(msg.quotedMessage.mediaType)) {
255
+ mediaBuf = await msg.quotedMessage.downloadMedia({ asBuffer: true });
256
+ }
257
+ if (!mediaBuf)
258
+ return [null, false];
259
+ const stickerProps = {
260
+ ...this.defaultStickerProps,
261
+ ...props,
262
+ media: mediaBuf,
263
+ };
264
+ const buffer = await makeWebpBuffer(stickerProps);
265
+ return [buffer, true];
266
+ };
267
+ }
268
+ const from = msg.key?.remoteJidAlt || msg.key?.remoteJid || "";
269
+ const participant = msg.key?.participant || "";
270
+ const isGroup = from.includes("@g.us");
271
+ const isStory = from.includes("status@broadcast");
272
+ const isReaction = msg.message?.reactionMessage ? true : false;
273
+ if (msg.key?.fromMe) {
274
+ msg.receiver = from;
275
+ msg.author = myJid;
276
+ }
277
+ else {
278
+ msg.receiver = myJid;
279
+ msg.author = from;
280
+ if (isGroup || isStory)
281
+ msg.author = participant;
282
+ if (isGroup)
321
283
  msg.receiver = from;
322
- msg.author = myJid;
323
- }
324
- else {
325
- msg.receiver = myJid;
326
- msg.author = from;
327
- if (isGroup || isStory)
328
- msg.author = participant;
329
- if (isGroup)
330
- msg.receiver = from;
331
- }
332
- msg.from = from;
333
- msg.isGroup = isGroup;
334
- msg.isStory = isStory;
335
- msg.isReaction = isReaction;
336
- if (isReaction)
337
- msg.text = (_r = (_q = msg.message) === null || _q === void 0 ? void 0 : _q.reactionMessage) === null || _r === void 0 ? void 0 : _r.text;
338
- msg.replyWithText = (text, opts) => __awaiter(this, void 0, void 0, function* () {
339
- return yield this.sendText(Object.assign(Object.assign({}, opts), { text, to: from, answering: msg }));
340
- });
341
- msg.replyWithAudio = (media, opts) => __awaiter(this, void 0, void 0, function* () {
342
- return yield this.sendAudio(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg }));
343
- });
344
- msg.replyWithImage = (media, opts) => __awaiter(this, void 0, void 0, function* () {
345
- return yield this.sendImage(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg }));
346
- });
347
- msg.replyWithVideo = (media, opts) => __awaiter(this, void 0, void 0, function* () {
348
- return yield this.sendVideo(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg }));
349
- });
350
- msg.replyWithSticker = (sticker, opts) => __awaiter(this, void 0, void 0, function* () {
351
- return yield this.sendSticker(Object.assign(Object.assign({ sticker }, opts), { to: from, answering: msg }));
352
- });
353
- msg.replyWithTyping = (callback) => __awaiter(this, void 0, void 0, function* () {
354
- return yield this.sendTyping({ to: from, callback });
355
- });
356
- msg.replyWithRecording = (callback) => __awaiter(this, void 0, void 0, function* () {
357
- return yield this.sendRecording({ to: from, callback });
358
- });
359
- msg.read = () => __awaiter(this, void 0, void 0, function* () {
360
- return yield this.readMessage([msg]);
361
- });
362
- msg.react = (reaction) => __awaiter(this, void 0, void 0, function* () {
363
- return yield this.sendReaction({ to: from, answering: msg, text: reaction });
364
- });
365
- msg.forward = (to, opts) => __awaiter(this, void 0, void 0, function* () {
366
- return yield this.forwardMessage(Object.assign({ to, msg }, opts));
284
+ }
285
+ msg.from = from;
286
+ msg.isGroup = isGroup;
287
+ msg.isStory = isStory;
288
+ msg.isReaction = isReaction;
289
+ if (isReaction)
290
+ msg.text = msg.message?.reactionMessage?.text;
291
+ msg.replyWithText = async (text, opts) => {
292
+ return await this.sendText({ ...opts, text, to: from, answering: msg });
293
+ };
294
+ msg.replyWithAudio = async (media, opts) => {
295
+ return await this.sendAudio({ media, ...opts, to: from, answering: msg });
296
+ };
297
+ msg.replyWithImage = async (media, opts) => {
298
+ return await this.sendImage({ media, ...opts, to: from, answering: msg });
299
+ };
300
+ msg.replyWithVideo = async (media, opts) => {
301
+ return await this.sendVideo({ media, ...opts, to: from, answering: msg });
302
+ };
303
+ msg.replyWithSticker = async (sticker, opts) => {
304
+ return await this.sendSticker({
305
+ sticker,
306
+ ...opts,
307
+ to: from,
308
+ answering: msg,
367
309
  });
368
310
  };
369
- msg.quotedMessage && setupMsg(msg.quotedMessage);
370
- setupMsg(msg);
371
- const { isStory, isReaction, isGroup } = msg;
372
- if (msg.key.fromMe) {
373
- this.events.emit("message-sent", msg);
374
- if (isStory) {
375
- this.events.emit("story-sent", msg);
376
- }
377
- else if (isReaction) {
378
- this.events.emit("reaction-sent", msg);
379
- if (isGroup)
380
- this.events.emit("group-reaction-sent", msg);
381
- else
382
- this.events.emit("private-reaction-sent", msg);
383
- }
384
- else if (isGroup) {
385
- this.events.emit("group-message-sent", msg);
386
- }
387
- else {
388
- this.events.emit("private-message-sent", msg);
389
- }
311
+ msg.replyWithTyping = async (callback) => {
312
+ return await this.sendTyping({ to: from, callback });
313
+ };
314
+ msg.replyWithRecording = async (callback) => {
315
+ return await this.sendRecording({ to: from, callback });
316
+ };
317
+ msg.read = async () => {
318
+ return await this.readMessage([msg]);
319
+ };
320
+ msg.react = async (reaction) => {
321
+ return await this.sendReaction({ to: from, answering: msg, text: reaction });
322
+ };
323
+ msg.forward = async (to, opts) => {
324
+ return await this.forwardMessage({ to, msg, ...opts });
325
+ };
326
+ };
327
+ msg.quotedMessage && setupMsg(msg.quotedMessage);
328
+ setupMsg(msg);
329
+ const { isStory, isReaction, isGroup } = msg;
330
+ if (msg.key.fromMe) {
331
+ this.events.emit("message-sent", msg);
332
+ if (isStory) {
333
+ this.events.emit("story-sent", msg);
390
334
  }
391
- else {
392
- this.events.emit("message-received", msg);
393
- if (isStory) {
394
- this.events.emit("story-received", msg);
395
- }
396
- else if (isReaction) {
397
- this.events.emit("reaction-received", msg);
398
- if (isGroup)
399
- this.events.emit("group-reaction-received", msg);
400
- else
401
- this.events.emit("private-reaction-received", msg);
402
- }
403
- else if (isGroup) {
404
- this.events.emit("group-message-received", msg);
405
- }
406
- else {
407
- this.events.emit("private-message-received", msg);
408
- }
335
+ else if (isReaction) {
336
+ this.events.emit("reaction-sent", msg);
337
+ if (isGroup)
338
+ this.events.emit("group-reaction-sent", msg);
339
+ else
340
+ this.events.emit("private-reaction-sent", msg);
409
341
  }
410
- if (isDeletedMsg) {
411
- this.events.emit("message-deleted", msg);
342
+ else if (isGroup) {
343
+ this.events.emit("group-message-sent", msg);
344
+ }
345
+ else {
346
+ this.events.emit("private-message-sent", msg);
412
347
  }
413
- else if (isStory) {
414
- this.events.emit("story", msg);
348
+ }
349
+ else {
350
+ this.events.emit("message-received", msg);
351
+ if (isStory) {
352
+ this.events.emit("story-received", msg);
415
353
  }
416
354
  else if (isReaction) {
417
- this.events.emit("reaction", msg);
355
+ this.events.emit("reaction-received", msg);
418
356
  if (isGroup)
419
- this.events.emit("group-reaction", msg);
357
+ this.events.emit("group-reaction-received", msg);
420
358
  else
421
- this.events.emit("private-reaction", msg);
359
+ this.events.emit("private-reaction-received", msg);
422
360
  }
423
361
  else if (isGroup) {
424
- this.events.emit("group-message", msg);
362
+ this.events.emit("group-message-received", msg);
425
363
  }
426
364
  else {
427
- this.events.emit("private-message", msg);
428
- }
429
- this.events.emit("message", msg);
430
- }));
431
- this.sock.ev.on("group-participants.update", (data) => __awaiter(this, void 0, void 0, function* () {
432
- const msg = Object.assign(Object.assign({}, data), { sessionId: this.sessionId });
433
- msg.replyWithText = (text, opts) => __awaiter(this, void 0, void 0, function* () {
434
- return yield this.sendText(Object.assign(Object.assign({}, opts), { text, to: data.id }));
435
- });
436
- msg.replyWithAudio = (media, opts) => __awaiter(this, void 0, void 0, function* () {
437
- return yield this.sendAudio(Object.assign(Object.assign({ media }, opts), { to: data.id }));
438
- });
439
- msg.replyWithImage = (media, opts) => __awaiter(this, void 0, void 0, function* () {
440
- return yield this.sendImage(Object.assign(Object.assign({ media }, opts), { to: data.id }));
441
- });
442
- msg.replyWithVideo = (media, opts) => __awaiter(this, void 0, void 0, function* () {
443
- return yield this.sendVideo(Object.assign(Object.assign({ media }, opts), { to: data.id }));
444
- });
445
- msg.replyWithSticker = (sticker, opts) => __awaiter(this, void 0, void 0, function* () {
446
- return yield this.sendSticker(Object.assign(Object.assign({ sticker }, opts), { to: data.id }));
447
- });
448
- msg.replyWithTyping = (callback) => __awaiter(this, void 0, void 0, function* () {
449
- return yield this.sendTyping({ to: data.id, callback });
450
- });
451
- msg.replyWithRecording = (callback) => __awaiter(this, void 0, void 0, function* () {
452
- return yield this.sendRecording({ to: data.id, callback });
453
- });
454
- this.events.emit("group-member-update", msg);
455
- }));
456
- this.sock.ev.on("messages.delete", (msgs) => __awaiter(this, void 0, void 0, function* () {
457
- this.logger.info("Msg Deleted : " + JSON.stringify(msgs, null, 2));
458
- }));
459
- return this.sock;
460
- }
461
- catch (error) {
462
- const msg = `Failed setup WASocket: ${error.message}`;
463
- this.logger.error(msg);
464
- throw new Error_1.AutoWAError(msg);
465
- }
466
- });
467
- }
468
- destroy(full) {
469
- return __awaiter(this, void 0, void 0, function* () {
470
- this.logger.info("Destroying...");
471
- let error = false;
472
- let msg = "";
473
- try {
474
- yield this.sock.logout();
475
- }
476
- catch (err) {
477
- msg = `Logout failed: ${err.message}`;
478
- error = true;
479
- }
480
- finally {
481
- this.sock.end(undefined);
482
- if (full) {
483
- const dir = path_1.default.resolve(Defaults_1.CREDENTIALS.DIR_NAME, this.sessionId + Defaults_1.CREDENTIALS.PREFIX);
484
- if (fs_1.default.existsSync(dir)) {
485
- fs_1.default.rmSync(dir, { force: true, recursive: true });
365
+ this.events.emit("private-message-received", msg);
486
366
  }
487
367
  }
488
- this.logger.info("Destroyed!");
489
- }
490
- if (error) {
491
- this.logger.error(msg);
492
- throw new Error_1.AutoWAError(msg);
493
- }
494
- });
495
- }
496
- isExist(_a) {
497
- return __awaiter(this, arguments, void 0, function* ({ from, isGroup = false }) {
498
- var _b, _c;
499
- try {
500
- const receiver = (0, helper_1.phoneToJid)({
501
- from: from,
502
- isGroup,
503
- });
504
- if (receiver.includes("@broadcast")) {
505
- return true;
368
+ if (isDeletedMsg) {
369
+ this.events.emit("message-deleted", msg);
506
370
  }
507
- else if (!receiver.includes("@g.us")) {
508
- return Boolean((_c = (_b = (yield this.sock.onWhatsApp(receiver))) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.exists);
371
+ else if (isStory) {
372
+ this.events.emit("story", msg);
373
+ }
374
+ else if (isReaction) {
375
+ this.events.emit("reaction", msg);
376
+ if (isGroup)
377
+ this.events.emit("group-reaction", msg);
378
+ else
379
+ this.events.emit("private-reaction", msg);
380
+ }
381
+ else if (isGroup) {
382
+ this.events.emit("group-message", msg);
509
383
  }
510
384
  else {
511
- return Boolean((yield this.sock.groupMetadata(receiver)).id);
385
+ this.events.emit("private-message", msg);
512
386
  }
513
- }
514
- catch (error) {
515
- const msg = `Failed get exist status: ${error.message}`;
516
- this.logger.error(msg);
517
- throw new Error_1.AutoWAError(msg);
518
- }
519
- });
387
+ this.events.emit("message", msg);
388
+ });
389
+ this.sock.ev.on("group-participants.update", async (data) => {
390
+ const msg = {
391
+ ...data,
392
+ sessionId: this.sessionId,
393
+ };
394
+ msg.replyWithText = async (text, opts) => {
395
+ return await this.sendText({ ...opts, text, to: data.id });
396
+ };
397
+ msg.replyWithAudio = async (media, opts) => {
398
+ return await this.sendAudio({ media, ...opts, to: data.id });
399
+ };
400
+ msg.replyWithImage = async (media, opts) => {
401
+ return await this.sendImage({ media, ...opts, to: data.id });
402
+ };
403
+ msg.replyWithVideo = async (media, opts) => {
404
+ return await this.sendVideo({ media, ...opts, to: data.id });
405
+ };
406
+ msg.replyWithSticker = async (sticker, opts) => {
407
+ return await this.sendSticker({ sticker, ...opts, to: data.id });
408
+ };
409
+ msg.replyWithTyping = async (callback) => {
410
+ return await this.sendTyping({ to: data.id, callback });
411
+ };
412
+ msg.replyWithRecording = async (callback) => {
413
+ return await this.sendRecording({ to: data.id, callback });
414
+ };
415
+ this.events.emit("group-member-update", msg);
416
+ });
417
+ this.sock.ev.on("messages.delete", async (msgs) => {
418
+ this.logger.info("Msg Deleted : " + JSON.stringify(msgs, null, 2));
419
+ });
420
+ return this.sock;
421
+ }
422
+ catch (error) {
423
+ const msg = `Failed setup WASocket: ${error.message}`;
424
+ this.logger.error(msg);
425
+ throw new AutoWAError(msg);
426
+ }
520
427
  }
521
- downloadMedia(msg, opts, ext) {
522
- return __awaiter(this, void 0, void 0, function* () {
523
- const filePath = path_1.default.join(process.cwd(), (opts.path || "my_media") + "." + ext);
524
- const buf = yield (0, baileys_1.downloadMediaMessage)(msg, "buffer", {});
525
- if (opts.asBuffer)
526
- return Promise.resolve(buf);
527
- fs_1.default.writeFileSync(filePath, buf);
528
- return Promise.resolve(filePath);
529
- });
428
+ async destroy(full) {
429
+ this.logger.info("Destroying...");
430
+ let error = false;
431
+ let msg = "";
432
+ try {
433
+ await this.sock.logout();
434
+ }
435
+ catch (err) {
436
+ msg = `Logout failed: ${err.message}`;
437
+ error = true;
438
+ }
439
+ finally {
440
+ this.sock.end(undefined);
441
+ if (full) {
442
+ const dir = path.resolve(CREDENTIALS.DIR_NAME, this.sessionId + CREDENTIALS.PREFIX);
443
+ if (fs.existsSync(dir)) {
444
+ fs.rmSync(dir, { force: true, recursive: true });
445
+ }
446
+ }
447
+ this.logger.info("Destroyed!");
448
+ }
449
+ if (error) {
450
+ this.logger.error(msg);
451
+ throw new AutoWAError(msg);
452
+ }
530
453
  }
531
- validateReceiver(_a) {
532
- return __awaiter(this, arguments, void 0, function* ({ from, isGroup = false }) {
533
- const oldPhone = from;
534
- from = (0, helper_1.phoneToJid)({ from, isGroup });
535
- const isRegistered = yield this.isExist({
536
- from,
454
+ async isExist({ from, isGroup = false }) {
455
+ try {
456
+ const receiver = phoneToJid({
457
+ from: from,
537
458
  isGroup,
538
459
  });
539
- if (!isRegistered) {
540
- return {
541
- msg: `${oldPhone} is not registered on Whatsapp`,
542
- };
460
+ if (receiver.includes("@broadcast")) {
461
+ return true;
462
+ }
463
+ else if (!receiver.includes("@g.us")) {
464
+ return Boolean((await this.sock.onWhatsApp(receiver))?.[0]?.exists);
543
465
  }
466
+ else {
467
+ return Boolean((await this.sock.groupMetadata(receiver)).id);
468
+ }
469
+ }
470
+ catch (error) {
471
+ const msg = `Failed get exist status: ${error.message}`;
472
+ this.logger.error(msg);
473
+ throw new AutoWAError(msg);
474
+ }
475
+ }
476
+ async downloadMedia(msg, opts, ext) {
477
+ const filePath = path.join(process.cwd(), (opts.path || "my_media") + "." + ext);
478
+ const buf = await downloadMediaMessage(msg, "buffer", {});
479
+ if (opts.asBuffer)
480
+ return Promise.resolve(buf);
481
+ fs.writeFileSync(filePath, buf);
482
+ return Promise.resolve(filePath);
483
+ }
484
+ async validateReceiver({ from, isGroup = false }) {
485
+ const oldPhone = from;
486
+ from = phoneToJid({ from, isGroup });
487
+ const isRegistered = await this.isExist({
488
+ from,
489
+ isGroup,
490
+ });
491
+ if (!isRegistered) {
544
492
  return {
545
- receiver: from,
493
+ msg: `${oldPhone} is not registered on Whatsapp`,
546
494
  };
495
+ }
496
+ return {
497
+ receiver: from,
498
+ };
499
+ }
500
+ async sendText({ to, text = "", isGroup = false, ...props }) {
501
+ const { receiver, msg } = await this.validateReceiver({
502
+ from: to,
503
+ isGroup,
504
+ });
505
+ if (msg)
506
+ throw new AutoWAError(msg);
507
+ return await this.sock.sendMessage(receiver, {
508
+ text: text,
509
+ mentions: props.mentions,
510
+ }, {
511
+ quoted: props.answering,
547
512
  });
548
513
  }
549
- sendText(_a) {
550
- return __awaiter(this, void 0, void 0, function* () {
551
- var { to, text = "", isGroup = false } = _a, props = __rest(_a, ["to", "text", "isGroup"]);
552
- const { receiver, msg } = yield this.validateReceiver({
553
- from: to,
554
- isGroup,
555
- });
556
- if (msg)
557
- throw new Error_1.AutoWAError(msg);
558
- return yield this.sock.sendMessage(receiver, {
559
- text: text,
514
+ async sendImage({ to, text = "", isGroup = false, media, failMsg, ...props }) {
515
+ if (!media)
516
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
517
+ const { receiver, msg } = await this.validateReceiver({
518
+ from: to,
519
+ isGroup,
520
+ });
521
+ if (msg)
522
+ throw new AutoWAError(msg);
523
+ try {
524
+ return await this.sock.sendMessage(receiver, {
525
+ image: typeof media == "string"
526
+ ? {
527
+ url: media,
528
+ }
529
+ : media,
530
+ caption: text,
560
531
  mentions: props.mentions,
561
532
  }, {
562
533
  quoted: props.answering,
563
534
  });
564
- });
565
- }
566
- sendImage(_a) {
567
- return __awaiter(this, void 0, void 0, function* () {
568
- var { to, text = "", isGroup = false, media, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "failMsg"]);
569
- if (!media)
570
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
571
- const { receiver, msg } = yield this.validateReceiver({
572
- from: to,
573
- isGroup,
535
+ }
536
+ catch (error) {
537
+ this.logger.error("Failed send media:" + error.message);
538
+ return await this.sendText({
539
+ to: receiver,
540
+ text: failMsg || "There is error while trying to send the image🥹",
541
+ ...props,
574
542
  });
575
- if (msg)
576
- throw new Error_1.AutoWAError(msg);
577
- try {
578
- return yield this.sock.sendMessage(receiver, {
579
- image: typeof media == "string"
580
- ? {
581
- url: media,
582
- }
583
- : media,
584
- caption: text,
585
- mentions: props.mentions,
586
- }, {
587
- quoted: props.answering,
588
- });
589
- }
590
- catch (error) {
591
- this.logger.error("Failed send media:" + error.message);
592
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the image🥹" }, props));
593
- }
594
- });
543
+ }
595
544
  }
596
- sendVideo(_a) {
597
- return __awaiter(this, void 0, void 0, function* () {
598
- var { to, text = "", isGroup = false, media, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "failMsg"]);
599
- if (!media)
600
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
601
- const { receiver, msg } = yield this.validateReceiver({
602
- from: to,
603
- isGroup,
604
- });
605
- if (msg)
606
- throw new Error_1.AutoWAError(msg);
607
- try {
608
- return yield this.sock.sendMessage(receiver, {
609
- video: typeof media == "string"
610
- ? {
611
- url: media,
612
- }
613
- : media,
614
- caption: text,
615
- mentions: props.mentions,
616
- }, {
617
- quoted: props.answering,
618
- });
619
- }
620
- catch (error) {
621
- this.logger.error("Failed send media:" + error.message);
622
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the video🥹" }, props));
623
- }
545
+ async sendVideo({ to, text = "", isGroup = false, media, failMsg, ...props }) {
546
+ if (!media)
547
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
548
+ const { receiver, msg } = await this.validateReceiver({
549
+ from: to,
550
+ isGroup,
624
551
  });
625
- }
626
- sendDocument(_a) {
627
- return __awaiter(this, void 0, void 0, function* () {
628
- var { to, text = "", isGroup = false, media, filename, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "filename", "failMsg"]);
629
- if (!media)
630
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
631
- const mimetype = mime_1.default.getType(filename);
632
- if (!mimetype)
633
- throw new Error_1.AutoWAError(`Filename must include valid extension`);
634
- const { receiver, msg } = yield this.validateReceiver({
635
- from: to,
636
- isGroup,
552
+ if (msg)
553
+ throw new AutoWAError(msg);
554
+ try {
555
+ return await this.sock.sendMessage(receiver, {
556
+ video: typeof media == "string"
557
+ ? {
558
+ url: media,
559
+ }
560
+ : media,
561
+ caption: text,
562
+ mentions: props.mentions,
563
+ }, {
564
+ quoted: props.answering,
637
565
  });
638
- if (msg)
639
- throw new Error_1.AutoWAError(msg);
640
- try {
641
- return yield this.sock.sendMessage(receiver, {
642
- fileName: filename,
643
- document: typeof media == "string"
644
- ? {
645
- url: media,
646
- }
647
- : media,
648
- mimetype: mimetype,
649
- caption: text,
650
- mentions: props.mentions,
651
- }, {
652
- quoted: props.answering,
653
- });
654
- }
655
- catch (error) {
656
- this.logger.error("Failed send media:" + error.message);
657
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the document" }, props));
658
- }
659
- });
660
- }
661
- sendAudio(_a) {
662
- return __awaiter(this, void 0, void 0, function* () {
663
- var { to, isGroup = false, media, voiceNote = false, failMsg } = _a, props = __rest(_a, ["to", "isGroup", "media", "voiceNote", "failMsg"]);
664
- if (!media)
665
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
666
- const { receiver, msg } = yield this.validateReceiver({
667
- from: to,
668
- isGroup,
566
+ }
567
+ catch (error) {
568
+ this.logger.error("Failed send media:" + error.message);
569
+ return await this.sendText({
570
+ to: receiver,
571
+ text: failMsg || "There is error while trying to send the video🥹",
572
+ ...props,
669
573
  });
670
- if (msg)
671
- throw new Error_1.AutoWAError(msg);
672
- try {
673
- return yield this.sock.sendMessage(receiver, {
674
- audio: typeof media == "string"
675
- ? {
676
- url: media,
677
- }
678
- : media,
679
- ptt: voiceNote,
680
- mentions: props.mentions,
681
- }, {
682
- quoted: props.answering,
683
- });
684
- }
685
- catch (error) {
686
- this.logger.error("Failed send media:" + error.message);
687
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the audio🥹" }, props));
688
- }
689
- });
574
+ }
690
575
  }
691
- sendReaction(_a) {
692
- return __awaiter(this, arguments, void 0, function* ({ to, text, isGroup = false, answering }) {
693
- const { receiver, msg } = yield this.validateReceiver({
694
- from: to,
695
- isGroup,
576
+ async sendDocument({ to, text = "", isGroup = false, media, filename, failMsg, ...props }) {
577
+ if (!media)
578
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
579
+ const mimetype = mime.getType(filename);
580
+ if (!mimetype)
581
+ throw new AutoWAError(`Filename must include valid extension`);
582
+ const { receiver, msg } = await this.validateReceiver({
583
+ from: to,
584
+ isGroup,
585
+ });
586
+ if (msg)
587
+ throw new AutoWAError(msg);
588
+ try {
589
+ return await this.sock.sendMessage(receiver, {
590
+ fileName: filename,
591
+ document: typeof media == "string"
592
+ ? {
593
+ url: media,
594
+ }
595
+ : media,
596
+ mimetype: mimetype,
597
+ caption: text,
598
+ mentions: props.mentions,
599
+ }, {
600
+ quoted: props.answering,
696
601
  });
697
- if (msg)
698
- throw new Error_1.AutoWAError(msg);
699
- return yield this.sock.sendMessage(receiver, {
700
- react: {
701
- text,
702
- key: answering.key,
703
- },
602
+ }
603
+ catch (error) {
604
+ this.logger.error("Failed send media:" + error.message);
605
+ return await this.sendText({
606
+ to: receiver,
607
+ text: failMsg || "There is error while trying to send the document",
608
+ ...props,
704
609
  });
705
- });
610
+ }
706
611
  }
707
- sendTyping(_a) {
708
- return __awaiter(this, arguments, void 0, function* ({ to, callback, isGroup = false }) {
709
- const { receiver, msg } = yield this.validateReceiver({
710
- from: to,
711
- isGroup,
712
- });
713
- if (msg)
714
- throw new Error_1.AutoWAError(msg);
715
- yield this.sock.sendPresenceUpdate("composing", receiver);
716
- yield callback();
717
- yield this.sock.sendPresenceUpdate("available", receiver);
612
+ async sendAudio({ to, isGroup = false, media, voiceNote = false, failMsg, ...props }) {
613
+ if (!media)
614
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
615
+ const { receiver, msg } = await this.validateReceiver({
616
+ from: to,
617
+ isGroup,
718
618
  });
719
- }
720
- sendRecording(_a) {
721
- return __awaiter(this, arguments, void 0, function* ({ to, callback, isGroup = false }) {
722
- const { receiver, msg } = yield this.validateReceiver({
723
- from: to,
724
- isGroup,
619
+ if (msg)
620
+ throw new AutoWAError(msg);
621
+ try {
622
+ return await this.sock.sendMessage(receiver, {
623
+ audio: typeof media == "string"
624
+ ? {
625
+ url: media,
626
+ }
627
+ : media,
628
+ ptt: voiceNote,
629
+ mentions: props.mentions,
630
+ }, {
631
+ quoted: props.answering,
725
632
  });
726
- if (msg)
727
- throw new Error_1.AutoWAError(msg);
728
- yield this.sock.sendPresenceUpdate("recording", receiver);
729
- yield callback();
730
- yield this.sock.sendPresenceUpdate("available", receiver);
731
- });
633
+ }
634
+ catch (error) {
635
+ this.logger.error("Failed send media:" + error.message);
636
+ return await this.sendText({
637
+ to: receiver,
638
+ text: failMsg || "There is error while trying to send the audio🥹",
639
+ ...props,
640
+ });
641
+ }
732
642
  }
733
- readMessage(msgs) {
734
- return __awaiter(this, void 0, void 0, function* () {
735
- yield this.sock.readMessages(msgs.map((msg) => msg.key));
643
+ async sendReaction({ to, text, isGroup = false, answering }) {
644
+ const { receiver, msg } = await this.validateReceiver({
645
+ from: to,
646
+ isGroup,
736
647
  });
737
- }
738
- sendSticker(_a) {
739
- return __awaiter(this, void 0, void 0, function* () {
740
- var { to, isGroup, sticker, media, failMsg, hasMedia } = _a, props = __rest(_a, ["to", "isGroup", "sticker", "media", "failMsg", "hasMedia"]);
741
- const { receiver, msg } = yield this.validateReceiver({
742
- from: to,
743
- isGroup,
744
- });
745
- if (msg)
746
- throw new Error_1.AutoWAError(msg);
747
- if (!media && !sticker && !hasMedia)
748
- throw new Error_1.AutoWAError("'media' or 'sticker' parameter must be filled");
749
- if (!sticker) {
750
- if (!(typeof media === "string" || Buffer.isBuffer(media)) && !hasMedia) {
751
- throw new Error_1.AutoWAError("'media' parameter must be string or buffer");
752
- }
753
- const stickerProps = Object.assign(Object.assign(Object.assign({}, this.defaultStickerProps), { media }), props);
754
- sticker = yield (0, make_stiker_1.makeWebpBuffer)(stickerProps);
755
- }
756
- if (!sticker || !Buffer.isBuffer(sticker)) {
757
- return yield this.sendText(Object.assign({ to, text: failMsg || "There is error while creating the sticker🥹", isGroup }, props));
758
- }
759
- try {
760
- return yield this.sock.sendMessage(receiver, {
761
- sticker,
762
- mentions: props.mentions,
763
- }, {
764
- quoted: props.answering,
765
- });
766
- }
767
- catch (error) {
768
- this.logger.error("Failed send media:" + error.message);
769
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the sticker🥹" }, props));
770
- }
648
+ if (msg)
649
+ throw new AutoWAError(msg);
650
+ return await this.sock.sendMessage(receiver, {
651
+ react: {
652
+ text,
653
+ key: answering.key,
654
+ },
771
655
  });
772
656
  }
773
- forwardMessage(_a) {
774
- return __awaiter(this, void 0, void 0, function* () {
775
- var { to, msg, isGroup = false } = _a, props = __rest(_a, ["to", "msg", "isGroup"]);
776
- const { receiver, msg: err_msg } = yield this.validateReceiver({
777
- from: to,
657
+ async sendTyping({ to, callback, isGroup = false }) {
658
+ const { receiver, msg } = await this.validateReceiver({
659
+ from: to,
660
+ isGroup,
661
+ });
662
+ if (msg)
663
+ throw new AutoWAError(msg);
664
+ await this.sock.sendPresenceUpdate("composing", receiver);
665
+ await callback();
666
+ await this.sock.sendPresenceUpdate("available", receiver);
667
+ }
668
+ async sendRecording({ to, callback, isGroup = false }) {
669
+ const { receiver, msg } = await this.validateReceiver({
670
+ from: to,
671
+ isGroup,
672
+ });
673
+ if (msg)
674
+ throw new AutoWAError(msg);
675
+ await this.sock.sendPresenceUpdate("recording", receiver);
676
+ await callback();
677
+ await this.sock.sendPresenceUpdate("available", receiver);
678
+ }
679
+ async readMessage(msgs) {
680
+ await this.sock.readMessages(msgs.map((msg) => msg.key));
681
+ }
682
+ async sendSticker({ to, isGroup, sticker, media, failMsg, hasMedia, ...props }) {
683
+ const { receiver, msg } = await this.validateReceiver({
684
+ from: to,
685
+ isGroup,
686
+ });
687
+ if (msg)
688
+ throw new AutoWAError(msg);
689
+ if (!media && !sticker && !hasMedia)
690
+ throw new AutoWAError("'media' or 'sticker' parameter must be filled");
691
+ if (!sticker) {
692
+ if (!(typeof media === "string" || Buffer.isBuffer(media)) && !hasMedia) {
693
+ throw new AutoWAError("'media' parameter must be string or buffer");
694
+ }
695
+ const stickerProps = {
696
+ ...this.defaultStickerProps,
697
+ media,
698
+ ...props,
699
+ };
700
+ sticker = await makeWebpBuffer(stickerProps);
701
+ }
702
+ if (!sticker || !Buffer.isBuffer(sticker)) {
703
+ return await this.sendText({
704
+ to,
705
+ text: failMsg || "There is error while creating the sticker🥹",
778
706
  isGroup,
707
+ ...props,
779
708
  });
780
- if (err_msg)
781
- throw new Error_1.AutoWAError(err_msg);
782
- try {
783
- return yield this.sock.sendMessage(receiver, {
784
- forward: msg,
785
- mentions: props.mentions,
786
- force: true,
787
- });
788
- }
789
- catch (error) {
790
- this.logger.error("Failed forward a message!");
791
- }
792
- });
793
- }
794
- getProfileInfo(target) {
795
- return __awaiter(this, void 0, void 0, function* () {
796
- const { receiver, msg } = yield this.validateReceiver({
797
- from: target,
709
+ }
710
+ try {
711
+ return await this.sock.sendMessage(receiver, {
712
+ sticker,
713
+ mentions: props.mentions,
714
+ }, {
715
+ quoted: props.answering,
798
716
  });
799
- if (msg)
800
- throw new Error_1.AutoWAError(msg);
801
- try {
802
- const [profilePictureUrl, status] = yield Promise.allSettled([
803
- this.sock.profilePictureUrl(receiver, "image", 5000),
804
- this.sock.fetchStatus(receiver),
805
- ]);
806
- return {
807
- profilePictureUrl: profilePictureUrl.status === "fulfilled" ? profilePictureUrl.value || null : null,
808
- status: status.status === "fulfilled" ? status.value || null : null,
809
- };
810
- }
811
- catch (error) {
812
- const msg = `Failed get profile info: ${error.message}`;
813
- this.logger.error(msg);
814
- }
815
- return null;
816
- });
817
- }
818
- getGroupInfo(target) {
819
- return __awaiter(this, void 0, void 0, function* () {
820
- const { receiver, msg } = yield this.validateReceiver({
821
- from: target,
822
- isGroup: true,
717
+ }
718
+ catch (error) {
719
+ this.logger.error("Failed send media:" + error.message);
720
+ return await this.sendText({
721
+ to: receiver,
722
+ text: failMsg || "There is error while trying to send the sticker🥹",
723
+ ...props,
823
724
  });
824
- if (msg)
825
- throw new Error_1.AutoWAError(msg);
826
- try {
827
- return yield this.sock.groupMetadata(receiver);
828
- }
829
- catch (error) {
830
- const msg = `Failed get group info: ${error.message}`;
831
- this.logger.error(msg);
832
- }
833
- return null;
834
- });
725
+ }
835
726
  }
836
- addMemberToGroup(_a) {
837
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
838
- const { receiver: group, msg } = yield this.validateReceiver({
839
- from: to,
840
- isGroup: true,
841
- });
842
- if (msg)
843
- throw new Error_1.AutoWAError(msg);
844
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
845
- return yield this.sock.groupParticipantsUpdate(group, participants, "add");
727
+ async forwardMessage({ to, msg, isGroup = false, ...props }) {
728
+ const { receiver, msg: err_msg } = await this.validateReceiver({
729
+ from: to,
730
+ isGroup,
846
731
  });
847
- }
848
- removeMemberFromGroup(_a) {
849
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
850
- const { receiver: group, msg } = yield this.validateReceiver({
851
- from: to,
852
- isGroup: true,
732
+ if (err_msg)
733
+ throw new AutoWAError(err_msg);
734
+ try {
735
+ return await this.sock.sendMessage(receiver, {
736
+ forward: msg,
737
+ mentions: props.mentions,
738
+ force: true,
853
739
  });
854
- if (msg)
855
- throw new Error_1.AutoWAError(msg);
856
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
857
- return yield this.sock.groupParticipantsUpdate(group, participants, "remove");
740
+ }
741
+ catch (error) {
742
+ this.logger.error("Failed forward a message!");
743
+ }
744
+ }
745
+ async getProfileInfo(target) {
746
+ const { receiver, msg } = await this.validateReceiver({
747
+ from: target,
858
748
  });
749
+ if (msg)
750
+ throw new AutoWAError(msg);
751
+ try {
752
+ const [profilePictureUrl, status] = await Promise.allSettled([
753
+ this.sock.profilePictureUrl(receiver, "image", 5000),
754
+ this.sock.fetchStatus(receiver),
755
+ ]);
756
+ return {
757
+ profilePictureUrl: profilePictureUrl.status === "fulfilled" ? profilePictureUrl.value || null : null,
758
+ status: status.status === "fulfilled" ? status.value || null : null,
759
+ };
760
+ }
761
+ catch (error) {
762
+ const msg = `Failed get profile info: ${error.message}`;
763
+ this.logger.error(msg);
764
+ }
765
+ return null;
859
766
  }
860
- promoteMemberGroup(_a) {
861
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
862
- const { receiver: group, msg } = yield this.validateReceiver({
863
- from: to,
864
- isGroup: true,
865
- });
866
- if (msg)
867
- throw new Error_1.AutoWAError(msg);
868
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
869
- return yield this.sock.groupParticipantsUpdate(group, participants, "promote");
767
+ async getGroupInfo(target) {
768
+ const { receiver, msg } = await this.validateReceiver({
769
+ from: target,
770
+ isGroup: true,
870
771
  });
772
+ if (msg)
773
+ throw new AutoWAError(msg);
774
+ try {
775
+ return await this.sock.groupMetadata(receiver);
776
+ }
777
+ catch (error) {
778
+ const msg = `Failed get group info: ${error.message}`;
779
+ this.logger.error(msg);
780
+ }
781
+ return null;
871
782
  }
872
- demoteMemberGroup(_a) {
873
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
874
- const { receiver: group, msg } = yield this.validateReceiver({
875
- from: to,
876
- isGroup: true,
877
- });
878
- if (msg)
879
- throw new Error_1.AutoWAError(msg);
880
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
881
- return yield this.sock.groupParticipantsUpdate(group, participants, "demote");
783
+ async addMemberToGroup({ participants, to }) {
784
+ const { receiver: group, msg } = await this.validateReceiver({
785
+ from: to,
786
+ isGroup: true,
787
+ });
788
+ if (msg)
789
+ throw new AutoWAError(msg);
790
+ participants = participants.map((d) => phoneToJid({ from: d }));
791
+ return await this.sock.groupParticipantsUpdate(group, participants, "add");
792
+ }
793
+ async removeMemberFromGroup({ participants, to }) {
794
+ const { receiver: group, msg } = await this.validateReceiver({
795
+ from: to,
796
+ isGroup: true,
797
+ });
798
+ if (msg)
799
+ throw new AutoWAError(msg);
800
+ participants = participants.map((d) => phoneToJid({ from: d }));
801
+ return await this.sock.groupParticipantsUpdate(group, participants, "remove");
802
+ }
803
+ async promoteMemberGroup({ participants, to }) {
804
+ const { receiver: group, msg } = await this.validateReceiver({
805
+ from: to,
806
+ isGroup: true,
807
+ });
808
+ if (msg)
809
+ throw new AutoWAError(msg);
810
+ participants = participants.map((d) => phoneToJid({ from: d }));
811
+ return await this.sock.groupParticipantsUpdate(group, participants, "promote");
812
+ }
813
+ async demoteMemberGroup({ participants, to }) {
814
+ const { receiver: group, msg } = await this.validateReceiver({
815
+ from: to,
816
+ isGroup: true,
882
817
  });
818
+ if (msg)
819
+ throw new AutoWAError(msg);
820
+ participants = participants.map((d) => phoneToJid({ from: d }));
821
+ return await this.sock.groupParticipantsUpdate(group, participants, "demote");
883
822
  }
884
823
  on(event, listener) {
885
824
  this.events.on(event, listener);
@@ -897,4 +836,3 @@ class AutoWA {
897
836
  this.events.removeAllListeners(event);
898
837
  }
899
838
  }
900
- exports.AutoWA = AutoWA;