whatsauto.js 1.2.3 → 2.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 (37) hide show
  1. package/README.md +40 -1
  2. package/dist/Defaults/index.d.ts +3 -2
  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 +5 -5
  7. package/dist/Logger/index.d.ts.map +1 -1
  8. package/dist/Logger/index.js +19 -39
  9. package/dist/Types/index.d.ts +21 -14
  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 +22 -21
  22. package/dist/WhatsApp/AutoWA.d.ts.map +1 -1
  23. package/dist/WhatsApp/AutoWA.js +730 -775
  24. package/dist/WhatsApp/AutoWAEvent.js +3 -8
  25. package/dist/WhatsApp/index.d.ts +3 -2
  26. package/dist/WhatsApp/index.d.ts.map +1 -1
  27. package/dist/WhatsApp/index.js +4 -19
  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,869 +1,825 @@
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;
232
- if (new_message.type == "append")
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);
142
+ }
143
+ else {
144
+ this.retryCount = 0;
145
+ this.logger.warn("Disconnected!");
146
+ this.events.emit("disconnected");
147
+ try {
148
+ await this.destroy(true);
149
+ }
150
+ catch (error) { }
233
151
  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
- if ((_b = msg.message) === null || _b === void 0 ? void 0 : _b.documentWithCaptionMessage)
237
- msg = Object.assign(Object.assign({}, msg), { message: msg.message.documentWithCaptionMessage.message });
238
- else if ((_c = msg.message) === null || _c === void 0 ? void 0 : _c.ephemeralMessage)
239
- msg = Object.assign(Object.assign({}, msg), { message: (_d = msg.message.ephemeralMessage) === null || _d === void 0 ? void 0 : _d.message });
152
+ }
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
+ };
240
200
  msg.sessionId = this.sessionId;
241
201
  let quotedMessage = null;
242
- const msgContextInfo = ((_f = (_e = msg.message) === null || _e === void 0 ? void 0 : _e.extendedTextMessage) === null || _f === void 0 ? void 0 : _f.contextInfo) ||
243
- ((_h = (_g = msg.message) === null || _g === void 0 ? void 0 : _g.imageMessage) === null || _h === void 0 ? void 0 : _h.contextInfo) ||
244
- ((_k = (_j = msg.message) === null || _j === void 0 ? void 0 : _j.videoMessage) === null || _k === void 0 ? void 0 : _k.contextInfo) ||
245
- ((_m = (_l = msg.message) === null || _l === void 0 ? void 0 : _l.stickerMessage) === null || _m === void 0 ? void 0 : _m.contextInfo) ||
246
- ((_p = (_o = msg.message) === null || _o === void 0 ? void 0 : _o.documentMessage) === null || _p === void 0 ? void 0 : _p.contextInfo);
247
- if (msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.quotedMessage) {
202
+ const msgContextInfo = getContextInfo(msg);
203
+ if (msgContextInfo?.quotedMessage) {
248
204
  quotedMessage = {
249
205
  key: {
250
- remoteJid: (_q = msg.key) === null || _q === void 0 ? void 0 : _q.remoteJid,
251
- id: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.stanzaId,
252
- participant: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.participant,
253
- fromMe: (msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.participant) == myJid,
206
+ remoteJid: msg.key?.remoteJid,
207
+ remoteJidAlt: msg.key?.remoteJidAlt,
208
+ id: msgContextInfo?.stanzaId,
209
+ participant: msgContextInfo?.participant,
210
+ fromMe: msgContextInfo?.participant == myJid,
254
211
  },
255
- message: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.quotedMessage,
212
+ message: msgContextInfo?.quotedMessage,
256
213
  };
257
214
  }
258
- if ((_r = quotedMessage === null || quotedMessage === void 0 ? void 0 : quotedMessage.message) === null || _r === void 0 ? void 0 : _r.documentWithCaptionMessage) {
259
- quotedMessage = Object.assign(Object.assign({}, quotedMessage), { message: quotedMessage.message.documentWithCaptionMessage.message });
215
+ if (quotedMessage?.message?.documentWithCaptionMessage) {
216
+ quotedMessage = {
217
+ ...quotedMessage,
218
+ message: quotedMessage.message.documentWithCaptionMessage.message,
219
+ };
260
220
  }
261
221
  msg.quotedMessage = quotedMessage;
262
- const mediaTypes = ["image", "audio", "video", "document"];
263
- const setupMsg = (msg) => {
264
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
265
- const text = ((_a = msg.message) === null || _a === void 0 ? void 0 : _a.conversation) ||
266
- ((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.extendedTextMessage) === null || _c === void 0 ? void 0 : _c.text) ||
267
- ((_e = (_d = msg.message) === null || _d === void 0 ? void 0 : _d.imageMessage) === null || _e === void 0 ? void 0 : _e.caption) ||
268
- ((_g = (_f = msg.message) === null || _f === void 0 ? void 0 : _f.videoMessage) === null || _g === void 0 ? void 0 : _g.caption) ||
269
- ((_j = (_h = msg.message) === null || _h === void 0 ? void 0 : _h.documentMessage) === null || _j === void 0 ? void 0 : _j.caption) ||
270
- "";
271
- msg.text = text;
272
- const mimeType = (0, helper_1.getMediaMimeType)(msg);
273
- const ext = mime_1.default.getExtension(mimeType);
274
- msg.hasMedia = mimeType !== "";
275
- msg.mediaType = "";
276
- if (mimeType)
277
- msg.mediaType =
278
- mediaTypes[mediaTypes.indexOf(mimeType.split("/")[0]) !== -1
279
- ? mediaTypes.indexOf(mimeType.split("/")[0])
280
- : 3];
281
- msg.downloadMedia = () => __awaiter(this, void 0, void 0, function* () { return Promise.resolve(null); });
282
- msg.toSticker = () => __awaiter(this, void 0, void 0, function* () { return Promise.resolve([null, false]); });
283
- if (msg.hasMedia) {
284
- msg.downloadMedia = (...args_1) => __awaiter(this, [...args_1], void 0, function* (opts = {}) { return this.downloadMedia(msg, opts, ext); });
285
- }
286
- if (msg.hasMedia || ((_k = msg.quotedMessage) === null || _k === void 0 ? void 0 : _k.hasMedia)) {
287
- msg.toSticker = (props) => __awaiter(this, void 0, void 0, function* () {
288
- let mediaBuf;
289
- if (msg.hasMedia && ["image", "video"].includes(msg.mediaType)) {
290
- mediaBuf = yield msg.downloadMedia({ asBuffer: true });
291
- }
292
- else if (msg.quotedMessage &&
293
- msg.quotedMessage.hasMedia &&
294
- ["image", "video"].includes(msg.quotedMessage.mediaType)) {
295
- mediaBuf = yield msg.quotedMessage.downloadMedia({ asBuffer: true });
296
- }
297
- if (!mediaBuf)
298
- return [null, false];
299
- const stickerProps = Object.assign(Object.assign(Object.assign({}, this.defaultStickerProps), props), { media: mediaBuf });
300
- const buffer = yield (0, make_stiker_1.makeWebpBuffer)(stickerProps);
301
- return [buffer, true];
302
- });
303
- }
304
- const from = ((_l = msg.key) === null || _l === void 0 ? void 0 : _l.remoteJid) || "";
305
- const participant = ((_m = msg.key) === null || _m === void 0 ? void 0 : _m.participant) || "";
306
- const isGroup = from.includes("@g.us");
307
- const isStory = from.includes("status@broadcast");
308
- const isReaction = ((_o = msg.message) === null || _o === void 0 ? void 0 : _o.reactionMessage) ? true : false;
309
- if ((_p = msg.key) === null || _p === void 0 ? void 0 : _p.fromMe) {
310
- msg.from = from;
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)
311
283
  msg.receiver = from;
312
- msg.author = myJid;
313
- }
314
- else {
315
- msg.from = from;
316
- msg.receiver = myJid;
317
- msg.author = from;
318
- if (isGroup || isStory)
319
- msg.author = participant;
320
- if (isGroup)
321
- msg.receiver = from;
322
- }
323
- msg.isGroup = isGroup;
324
- msg.isStory = isStory;
325
- msg.isReaction = isReaction;
326
- if (isReaction)
327
- msg.text = (_r = (_q = msg.message) === null || _q === void 0 ? void 0 : _q.reactionMessage) === null || _r === void 0 ? void 0 : _r.text;
328
- msg.replyWithText = (text, opts) => __awaiter(this, void 0, void 0, function* () {
329
- return yield this.sendText(Object.assign(Object.assign({}, opts), { text, to: from, answering: msg }));
330
- });
331
- msg.replyWithAudio = (media, opts) => __awaiter(this, void 0, void 0, function* () {
332
- return yield this.sendAudio(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg }));
333
- });
334
- msg.replyWithImage = (media, opts) => __awaiter(this, void 0, void 0, function* () {
335
- return yield this.sendImage(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg }));
336
- });
337
- msg.replyWithVideo = (media, opts) => __awaiter(this, void 0, void 0, function* () {
338
- return yield this.sendVideo(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg }));
339
- });
340
- msg.replyWithSticker = (sticker, opts) => __awaiter(this, void 0, void 0, function* () {
341
- return yield this.sendSticker(Object.assign(Object.assign({ sticker }, opts), { to: from, answering: msg }));
342
- });
343
- msg.replyWithTyping = (callback) => __awaiter(this, void 0, void 0, function* () {
344
- return yield this.sendTyping({ to: from, callback });
345
- });
346
- msg.replyWithRecording = (callback) => __awaiter(this, void 0, void 0, function* () {
347
- return yield this.sendRecording({ to: from, callback });
348
- });
349
- msg.read = () => __awaiter(this, void 0, void 0, function* () {
350
- return yield this.readMessage([msg]);
351
- });
352
- msg.react = (reaction) => __awaiter(this, void 0, void 0, function* () {
353
- return yield this.sendReaction({ to: from, answering: msg, text: reaction });
354
- });
355
- msg.forward = (to, opts) => __awaiter(this, void 0, void 0, function* () {
356
- 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,
357
309
  });
358
310
  };
359
- msg.quotedMessage && setupMsg(msg.quotedMessage);
360
- setupMsg(msg);
361
- const { isStory, isReaction, isGroup } = msg;
362
- if (msg.key.fromMe) {
363
- this.events.emit("message-sent", msg);
364
- if (isStory) {
365
- this.events.emit("story-sent", msg);
366
- }
367
- else if (isReaction) {
368
- this.events.emit("reaction-sent", msg);
369
- if (isGroup)
370
- this.events.emit("group-reaction-sent", msg);
371
- else
372
- this.events.emit("private-reaction-sent", msg);
373
- }
374
- else if (isGroup) {
375
- this.events.emit("group-message-sent", msg);
376
- }
377
- else {
378
- this.events.emit("private-message-sent", msg);
379
- }
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);
334
+ }
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);
341
+ }
342
+ else if (isGroup) {
343
+ this.events.emit("group-message-sent", msg);
380
344
  }
381
345
  else {
382
- this.events.emit("message-received", msg);
383
- if (isStory) {
384
- this.events.emit("story-received", msg);
385
- }
386
- else if (isReaction) {
387
- this.events.emit("reaction-received", msg);
388
- if (isGroup)
389
- this.events.emit("group-reaction-received", msg);
390
- else
391
- this.events.emit("private-reaction-received", msg);
392
- }
393
- else if (isGroup) {
394
- this.events.emit("group-message-received", msg);
395
- }
396
- else {
397
- this.events.emit("private-message-received", msg);
398
- }
346
+ this.events.emit("private-message-sent", msg);
399
347
  }
348
+ }
349
+ else {
350
+ this.events.emit("message-received", msg);
400
351
  if (isStory) {
401
- this.events.emit("story", msg);
352
+ this.events.emit("story-received", msg);
402
353
  }
403
354
  else if (isReaction) {
404
- this.events.emit("reaction", msg);
355
+ this.events.emit("reaction-received", msg);
405
356
  if (isGroup)
406
- this.events.emit("group-reaction", msg);
357
+ this.events.emit("group-reaction-received", msg);
407
358
  else
408
- this.events.emit("private-reaction", msg);
359
+ this.events.emit("private-reaction-received", msg);
409
360
  }
410
361
  else if (isGroup) {
411
- this.events.emit("group-message", msg);
362
+ this.events.emit("group-message-received", msg);
412
363
  }
413
364
  else {
414
- this.events.emit("private-message", msg);
415
- }
416
- this.events.emit("message", msg);
417
- }));
418
- this.sock.ev.on("group-participants.update", (data) => __awaiter(this, void 0, void 0, function* () {
419
- const msg = Object.assign(Object.assign({}, data), { sessionId: this.sessionId });
420
- msg.replyWithText = (text, opts) => __awaiter(this, void 0, void 0, function* () {
421
- return yield this.sendText(Object.assign(Object.assign({}, opts), { text, to: data.id }));
422
- });
423
- msg.replyWithAudio = (media, opts) => __awaiter(this, void 0, void 0, function* () {
424
- return yield this.sendAudio(Object.assign(Object.assign({ media }, opts), { to: data.id }));
425
- });
426
- msg.replyWithImage = (media, opts) => __awaiter(this, void 0, void 0, function* () {
427
- return yield this.sendImage(Object.assign(Object.assign({ media }, opts), { to: data.id }));
428
- });
429
- msg.replyWithVideo = (media, opts) => __awaiter(this, void 0, void 0, function* () {
430
- return yield this.sendVideo(Object.assign(Object.assign({ media }, opts), { to: data.id }));
431
- });
432
- msg.replyWithSticker = (sticker, opts) => __awaiter(this, void 0, void 0, function* () {
433
- return yield this.sendSticker(Object.assign(Object.assign({ sticker }, opts), { to: data.id }));
434
- });
435
- msg.replyWithTyping = (callback) => __awaiter(this, void 0, void 0, function* () {
436
- return yield this.sendTyping({ to: data.id, callback });
437
- });
438
- msg.replyWithRecording = (callback) => __awaiter(this, void 0, void 0, function* () {
439
- return yield this.sendRecording({ to: data.id, callback });
440
- });
441
- this.events.emit("group-member-update", msg);
442
- }));
443
- return this.sock;
444
- }
445
- catch (error) {
446
- const msg = `Failed setup WASocket: ${error.message}`;
447
- this.logger.error(msg);
448
- throw new Error_1.AutoWAError(msg);
449
- }
450
- });
451
- }
452
- destroy(full) {
453
- return __awaiter(this, void 0, void 0, function* () {
454
- this.logger.info("Destroying...");
455
- let error = false;
456
- let msg = "";
457
- try {
458
- yield this.sock.logout();
459
- }
460
- catch (err) {
461
- msg = `Logout failed: ${err.message}`;
462
- error = true;
463
- }
464
- finally {
465
- this.sock.end(undefined);
466
- if (full) {
467
- const dir = path_1.default.resolve(Defaults_1.CREDENTIALS.DIR_NAME, this.sessionId + Defaults_1.CREDENTIALS.PREFIX);
468
- if (fs_1.default.existsSync(dir)) {
469
- fs_1.default.rmSync(dir, { force: true, recursive: true });
365
+ this.events.emit("private-message-received", msg);
470
366
  }
471
367
  }
472
- this.logger.info("Destroyed!");
473
- }
474
- if (error) {
475
- this.logger.error(msg);
476
- throw new Error_1.AutoWAError(msg);
477
- }
478
- });
479
- }
480
- isExist(_a) {
481
- return __awaiter(this, arguments, void 0, function* ({ from, isGroup = false }) {
482
- var _b, _c;
483
- try {
484
- const receiver = (0, helper_1.phoneToJid)({
485
- from: from,
486
- isGroup,
487
- });
488
- if (receiver.includes("@broadcast")) {
489
- return true;
368
+ if (isDeletedMsg) {
369
+ this.events.emit("message-deleted", msg);
370
+ }
371
+ else if (isStory) {
372
+ this.events.emit("story", msg);
490
373
  }
491
- else if (!receiver.includes("@g.us")) {
492
- 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);
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);
493
383
  }
494
384
  else {
495
- return Boolean((yield this.sock.groupMetadata(receiver)).id);
385
+ this.events.emit("private-message", msg);
496
386
  }
497
- }
498
- catch (error) {
499
- const msg = `Failed get exist status: ${error.message}`;
500
- this.logger.error(msg);
501
- throw new Error_1.AutoWAError(msg);
502
- }
503
- });
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
+ }
504
427
  }
505
- downloadMedia(msg, opts, ext) {
506
- return __awaiter(this, void 0, void 0, function* () {
507
- const filePath = path_1.default.join(process.cwd(), (opts.path || "my_media") + "." + ext);
508
- const buf = yield (0, baileys_1.downloadMediaMessage)(msg, "buffer", {});
509
- if (opts.asBuffer)
510
- return Promise.resolve(buf);
511
- fs_1.default.writeFileSync(filePath, buf);
512
- return Promise.resolve(filePath);
513
- });
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
+ }
514
453
  }
515
- validateReceiver(_a) {
516
- return __awaiter(this, arguments, void 0, function* ({ from, isGroup = false }) {
517
- const oldPhone = from;
518
- from = (0, helper_1.phoneToJid)({ from, isGroup });
519
- const isRegistered = yield this.isExist({
520
- from,
454
+ async isExist({ from, isGroup = false }) {
455
+ try {
456
+ const receiver = phoneToJid({
457
+ from: from,
521
458
  isGroup,
522
459
  });
523
- if (!isRegistered) {
524
- return {
525
- msg: `${oldPhone} is not registered on Whatsapp`,
526
- };
460
+ if (receiver.includes("@broadcast")) {
461
+ return true;
527
462
  }
463
+ else if (!receiver.includes("@g.us")) {
464
+ return Boolean((await this.sock.onWhatsApp(receiver))?.[0]?.exists);
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
+ this.logger.debug(JSON.stringify(msg, null, 2));
478
+ const filePath = path.join(process.cwd(), (opts.path || "my_media") + "." + ext);
479
+ const buf = await downloadMediaMessage(msg, "buffer", {});
480
+ if (opts.asBuffer)
481
+ return Promise.resolve(buf);
482
+ fs.writeFileSync(filePath, buf);
483
+ return Promise.resolve(filePath);
484
+ }
485
+ async validateReceiver({ from, isGroup = false }) {
486
+ const oldPhone = from;
487
+ from = phoneToJid({ from, isGroup });
488
+ const isRegistered = await this.isExist({
489
+ from,
490
+ isGroup,
491
+ });
492
+ if (!isRegistered) {
528
493
  return {
529
- receiver: from,
494
+ msg: `${oldPhone} is not registered on Whatsapp`,
530
495
  };
496
+ }
497
+ return {
498
+ receiver: from,
499
+ };
500
+ }
501
+ async sendText({ to, text = "", isGroup = false, ...props }) {
502
+ const { receiver, msg } = await this.validateReceiver({
503
+ from: to,
504
+ isGroup,
505
+ });
506
+ if (msg)
507
+ throw new AutoWAError(msg);
508
+ return await this.sock.sendMessage(receiver, {
509
+ text: text,
510
+ mentions: props.mentions,
511
+ }, {
512
+ quoted: props.answering,
531
513
  });
532
514
  }
533
- sendText(_a) {
534
- return __awaiter(this, void 0, void 0, function* () {
535
- var { to, text = "", isGroup = false } = _a, props = __rest(_a, ["to", "text", "isGroup"]);
536
- const { receiver, msg } = yield this.validateReceiver({
537
- from: to,
538
- isGroup,
539
- });
540
- if (msg)
541
- throw new Error_1.AutoWAError(msg);
542
- return yield this.sock.sendMessage(receiver, {
543
- text: text,
515
+ async sendImage({ to, text = "", isGroup = false, media, failMsg, ...props }) {
516
+ if (!media)
517
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
518
+ const { receiver, msg } = await this.validateReceiver({
519
+ from: to,
520
+ isGroup,
521
+ });
522
+ if (msg)
523
+ throw new AutoWAError(msg);
524
+ try {
525
+ return await this.sock.sendMessage(receiver, {
526
+ image: typeof media == "string"
527
+ ? {
528
+ url: media,
529
+ }
530
+ : media,
531
+ caption: text,
544
532
  mentions: props.mentions,
545
533
  }, {
546
534
  quoted: props.answering,
547
535
  });
548
- });
549
- }
550
- sendImage(_a) {
551
- return __awaiter(this, void 0, void 0, function* () {
552
- var { to, text = "", isGroup = false, media, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "failMsg"]);
553
- if (!media)
554
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
555
- const { receiver, msg } = yield this.validateReceiver({
556
- from: to,
557
- isGroup,
536
+ }
537
+ catch (error) {
538
+ this.logger.error("Failed send media:" + error.message);
539
+ return await this.sendText({
540
+ to: receiver,
541
+ text: failMsg || "There is error while trying to send the image🥹",
542
+ ...props,
558
543
  });
559
- if (msg)
560
- throw new Error_1.AutoWAError(msg);
561
- try {
562
- return yield this.sock.sendMessage(receiver, {
563
- image: typeof media == "string"
564
- ? {
565
- url: media,
566
- }
567
- : media,
568
- caption: text,
569
- mentions: props.mentions,
570
- }, {
571
- quoted: props.answering,
572
- });
573
- }
574
- catch (error) {
575
- this.logger.error("Failed send media:" + error.message);
576
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the image🥹" }, props));
577
- }
578
- });
544
+ }
579
545
  }
580
- sendVideo(_a) {
581
- return __awaiter(this, void 0, void 0, function* () {
582
- var { to, text = "", isGroup = false, media, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "failMsg"]);
583
- if (!media)
584
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
585
- const { receiver, msg } = yield this.validateReceiver({
586
- from: to,
587
- isGroup,
588
- });
589
- if (msg)
590
- throw new Error_1.AutoWAError(msg);
591
- try {
592
- return yield this.sock.sendMessage(receiver, {
593
- video: typeof media == "string"
594
- ? {
595
- url: media,
596
- }
597
- : media,
598
- caption: text,
599
- mentions: props.mentions,
600
- }, {
601
- quoted: props.answering,
602
- });
603
- }
604
- catch (error) {
605
- this.logger.error("Failed send media:" + error.message);
606
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the video🥹" }, props));
607
- }
546
+ async sendVideo({ to, text = "", isGroup = false, media, failMsg, ...props }) {
547
+ if (!media)
548
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
549
+ const { receiver, msg } = await this.validateReceiver({
550
+ from: to,
551
+ isGroup,
608
552
  });
609
- }
610
- sendDocument(_a) {
611
- return __awaiter(this, void 0, void 0, function* () {
612
- var { to, text = "", isGroup = false, media, filename, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "filename", "failMsg"]);
613
- if (!media)
614
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
615
- const mimetype = mime_1.default.getType(filename);
616
- if (!mimetype)
617
- throw new Error_1.AutoWAError(`Filename must include valid extension`);
618
- const { receiver, msg } = yield this.validateReceiver({
619
- from: to,
620
- isGroup,
553
+ if (msg)
554
+ throw new AutoWAError(msg);
555
+ try {
556
+ return await this.sock.sendMessage(receiver, {
557
+ video: typeof media == "string"
558
+ ? {
559
+ url: media,
560
+ }
561
+ : media,
562
+ caption: text,
563
+ mentions: props.mentions,
564
+ }, {
565
+ quoted: props.answering,
621
566
  });
622
- if (msg)
623
- throw new Error_1.AutoWAError(msg);
624
- try {
625
- return yield this.sock.sendMessage(receiver, {
626
- fileName: filename,
627
- document: typeof media == "string"
628
- ? {
629
- url: media,
630
- }
631
- : media,
632
- mimetype: mimetype,
633
- caption: text,
634
- mentions: props.mentions,
635
- }, {
636
- quoted: props.answering,
637
- });
638
- }
639
- catch (error) {
640
- this.logger.error("Failed send media:" + error.message);
641
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the document" }, props));
642
- }
643
- });
644
- }
645
- sendAudio(_a) {
646
- return __awaiter(this, void 0, void 0, function* () {
647
- var { to, isGroup = false, media, voiceNote = false, failMsg } = _a, props = __rest(_a, ["to", "isGroup", "media", "voiceNote", "failMsg"]);
648
- if (!media)
649
- throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL");
650
- const { receiver, msg } = yield this.validateReceiver({
651
- from: to,
652
- isGroup,
567
+ }
568
+ catch (error) {
569
+ this.logger.error("Failed send media:" + error.message);
570
+ return await this.sendText({
571
+ to: receiver,
572
+ text: failMsg || "There is error while trying to send the video🥹",
573
+ ...props,
653
574
  });
654
- if (msg)
655
- throw new Error_1.AutoWAError(msg);
656
- try {
657
- return yield this.sock.sendMessage(receiver, {
658
- audio: typeof media == "string"
659
- ? {
660
- url: media,
661
- }
662
- : media,
663
- ptt: voiceNote,
664
- mentions: props.mentions,
665
- }, {
666
- quoted: props.answering,
667
- });
668
- }
669
- catch (error) {
670
- this.logger.error("Failed send media:" + error.message);
671
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the audio🥹" }, props));
672
- }
673
- });
575
+ }
674
576
  }
675
- sendReaction(_a) {
676
- return __awaiter(this, arguments, void 0, function* ({ to, text, isGroup = false, answering }) {
677
- const { receiver, msg } = yield this.validateReceiver({
678
- from: to,
679
- isGroup,
577
+ async sendDocument({ to, text = "", isGroup = false, media, filename, failMsg, ...props }) {
578
+ if (!media)
579
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
580
+ const mimetype = mime.getType(filename);
581
+ if (!mimetype)
582
+ throw new AutoWAError(`Filename must include valid extension`);
583
+ const { receiver, msg } = await this.validateReceiver({
584
+ from: to,
585
+ isGroup,
586
+ });
587
+ if (msg)
588
+ throw new AutoWAError(msg);
589
+ try {
590
+ return await this.sock.sendMessage(receiver, {
591
+ fileName: filename,
592
+ document: typeof media == "string"
593
+ ? {
594
+ url: media,
595
+ }
596
+ : media,
597
+ mimetype: mimetype,
598
+ caption: text,
599
+ mentions: props.mentions,
600
+ }, {
601
+ quoted: props.answering,
680
602
  });
681
- if (msg)
682
- throw new Error_1.AutoWAError(msg);
683
- return yield this.sock.sendMessage(receiver, {
684
- react: {
685
- text,
686
- key: answering.key,
687
- },
603
+ }
604
+ catch (error) {
605
+ this.logger.error("Failed send media:" + error.message);
606
+ return await this.sendText({
607
+ to: receiver,
608
+ text: failMsg || "There is error while trying to send the document",
609
+ ...props,
688
610
  });
689
- });
611
+ }
690
612
  }
691
- sendTyping(_a) {
692
- return __awaiter(this, arguments, void 0, function* ({ to, callback, isGroup = false }) {
693
- const { receiver, msg } = yield this.validateReceiver({
694
- from: to,
695
- isGroup,
696
- });
697
- if (msg)
698
- throw new Error_1.AutoWAError(msg);
699
- yield this.sock.sendPresenceUpdate("composing", receiver);
700
- yield callback();
701
- yield this.sock.sendPresenceUpdate("available", receiver);
613
+ async sendAudio({ to, isGroup = false, media, voiceNote = false, failMsg, ...props }) {
614
+ if (!media)
615
+ throw new AutoWAError("'media' parameter must be Buffer or String URL");
616
+ const { receiver, msg } = await this.validateReceiver({
617
+ from: to,
618
+ isGroup,
702
619
  });
703
- }
704
- sendRecording(_a) {
705
- return __awaiter(this, arguments, void 0, function* ({ to, callback, isGroup = false }) {
706
- const { receiver, msg } = yield this.validateReceiver({
707
- from: to,
708
- isGroup,
620
+ if (msg)
621
+ throw new AutoWAError(msg);
622
+ try {
623
+ return await this.sock.sendMessage(receiver, {
624
+ audio: typeof media == "string"
625
+ ? {
626
+ url: media,
627
+ }
628
+ : media,
629
+ ptt: voiceNote,
630
+ mentions: props.mentions,
631
+ }, {
632
+ quoted: props.answering,
709
633
  });
710
- if (msg)
711
- throw new Error_1.AutoWAError(msg);
712
- yield this.sock.sendPresenceUpdate("recording", receiver);
713
- yield callback();
714
- yield this.sock.sendPresenceUpdate("available", receiver);
715
- });
634
+ }
635
+ catch (error) {
636
+ this.logger.error("Failed send media:" + error.message);
637
+ return await this.sendText({
638
+ to: receiver,
639
+ text: failMsg || "There is error while trying to send the audio🥹",
640
+ ...props,
641
+ });
642
+ }
716
643
  }
717
- readMessage(msgs) {
718
- return __awaiter(this, void 0, void 0, function* () {
719
- yield this.sock.readMessages(msgs.map((msg) => msg.key));
644
+ async sendReaction({ to, text, isGroup = false, answering }) {
645
+ const { receiver, msg } = await this.validateReceiver({
646
+ from: to,
647
+ isGroup,
720
648
  });
721
- }
722
- sendSticker(_a) {
723
- return __awaiter(this, void 0, void 0, function* () {
724
- var { to, isGroup, sticker, media, failMsg, hasMedia } = _a, props = __rest(_a, ["to", "isGroup", "sticker", "media", "failMsg", "hasMedia"]);
725
- const { receiver, msg } = yield this.validateReceiver({
726
- from: to,
727
- isGroup,
728
- });
729
- if (msg)
730
- throw new Error_1.AutoWAError(msg);
731
- if (!media && !sticker && !hasMedia)
732
- throw new Error_1.AutoWAError("'media' or 'sticker' parameter must be filled");
733
- if (!sticker) {
734
- if (!(typeof media === "string" || Buffer.isBuffer(media)) && !hasMedia) {
735
- throw new Error_1.AutoWAError("'media' parameter must be string or buffer");
736
- }
737
- const stickerProps = Object.assign(Object.assign(Object.assign({}, this.defaultStickerProps), { media }), props);
738
- sticker = yield (0, make_stiker_1.makeWebpBuffer)(stickerProps);
739
- }
740
- if (!sticker || !Buffer.isBuffer(sticker)) {
741
- return yield this.sendText(Object.assign({ to, text: failMsg || "There is error while creating the sticker🥹", isGroup }, props));
742
- }
743
- try {
744
- return yield this.sock.sendMessage(receiver, {
745
- sticker,
746
- mentions: props.mentions,
747
- }, {
748
- quoted: props.answering,
749
- });
750
- }
751
- catch (error) {
752
- this.logger.error("Failed send media:" + error.message);
753
- return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the sticker🥹" }, props));
754
- }
649
+ if (msg)
650
+ throw new AutoWAError(msg);
651
+ return await this.sock.sendMessage(receiver, {
652
+ react: {
653
+ text,
654
+ key: answering.key,
655
+ },
755
656
  });
756
657
  }
757
- forwardMessage(_a) {
758
- return __awaiter(this, void 0, void 0, function* () {
759
- var { to, msg, isGroup = false } = _a, props = __rest(_a, ["to", "msg", "isGroup"]);
760
- const { receiver, msg: err_msg } = yield this.validateReceiver({
761
- from: to,
658
+ async sendTyping({ to, callback, isGroup = false }) {
659
+ const { receiver, msg } = await this.validateReceiver({
660
+ from: to,
661
+ isGroup,
662
+ });
663
+ if (msg)
664
+ throw new AutoWAError(msg);
665
+ await this.sock.sendPresenceUpdate("composing", receiver);
666
+ await callback();
667
+ await this.sock.sendPresenceUpdate("available", receiver);
668
+ }
669
+ async sendRecording({ to, callback, isGroup = false }) {
670
+ const { receiver, msg } = await this.validateReceiver({
671
+ from: to,
672
+ isGroup,
673
+ });
674
+ if (msg)
675
+ throw new AutoWAError(msg);
676
+ await this.sock.sendPresenceUpdate("recording", receiver);
677
+ await callback();
678
+ await this.sock.sendPresenceUpdate("available", receiver);
679
+ }
680
+ async readMessage(msgs) {
681
+ await this.sock.readMessages(msgs.map((msg) => msg.key));
682
+ }
683
+ async sendSticker({ to, isGroup, sticker, media, failMsg, hasMedia, ...props }) {
684
+ const { receiver, msg } = await this.validateReceiver({
685
+ from: to,
686
+ isGroup,
687
+ });
688
+ if (msg)
689
+ throw new AutoWAError(msg);
690
+ if (!media && !sticker && !hasMedia)
691
+ throw new AutoWAError("'media' or 'sticker' parameter must be filled");
692
+ if (!sticker) {
693
+ if (!(typeof media === "string" || Buffer.isBuffer(media)) && !hasMedia) {
694
+ throw new AutoWAError("'media' parameter must be string or buffer");
695
+ }
696
+ const stickerProps = {
697
+ ...this.defaultStickerProps,
698
+ media,
699
+ ...props,
700
+ };
701
+ sticker = await makeWebpBuffer(stickerProps);
702
+ }
703
+ if (!sticker || !Buffer.isBuffer(sticker)) {
704
+ return await this.sendText({
705
+ to,
706
+ text: failMsg || "There is error while creating the sticker🥹",
762
707
  isGroup,
708
+ ...props,
763
709
  });
764
- if (err_msg)
765
- throw new Error_1.AutoWAError(err_msg);
766
- try {
767
- return yield this.sock.sendMessage(receiver, {
768
- forward: msg,
769
- mentions: props.mentions,
770
- force: true,
771
- });
772
- }
773
- catch (error) {
774
- this.logger.error("Failed forward a message!");
775
- }
776
- });
777
- }
778
- getProfileInfo(target) {
779
- return __awaiter(this, void 0, void 0, function* () {
780
- const { receiver, msg } = yield this.validateReceiver({
781
- from: target,
710
+ }
711
+ try {
712
+ return await this.sock.sendMessage(receiver, {
713
+ sticker,
714
+ mentions: props.mentions,
715
+ }, {
716
+ quoted: props.answering,
782
717
  });
783
- if (msg)
784
- throw new Error_1.AutoWAError(msg);
785
- try {
786
- const [profilePictureUrl, status] = yield Promise.allSettled([
787
- this.sock.profilePictureUrl(receiver, "image", 5000),
788
- this.sock.fetchStatus(receiver),
789
- ]);
790
- return {
791
- profilePictureUrl: profilePictureUrl.status === "fulfilled" ? profilePictureUrl.value || null : null,
792
- status: status.status === "fulfilled" ? status.value || null : null,
793
- };
794
- }
795
- catch (error) {
796
- const msg = `Failed get profile info: ${error.message}`;
797
- this.logger.error(msg);
798
- }
799
- return null;
800
- });
801
- }
802
- getGroupInfo(target) {
803
- return __awaiter(this, void 0, void 0, function* () {
804
- const { receiver, msg } = yield this.validateReceiver({
805
- from: target,
806
- isGroup: true,
718
+ }
719
+ catch (error) {
720
+ this.logger.error("Failed send media:" + error.message);
721
+ return await this.sendText({
722
+ to: receiver,
723
+ text: failMsg || "There is error while trying to send the sticker🥹",
724
+ ...props,
807
725
  });
808
- if (msg)
809
- throw new Error_1.AutoWAError(msg);
810
- try {
811
- return yield this.sock.groupMetadata(receiver);
812
- }
813
- catch (error) {
814
- const msg = `Failed get group info: ${error.message}`;
815
- this.logger.error(msg);
816
- }
817
- return null;
818
- });
726
+ }
819
727
  }
820
- addMemberToGroup(_a) {
821
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
822
- const { receiver: group, msg } = yield this.validateReceiver({
823
- from: to,
824
- isGroup: true,
825
- });
826
- if (msg)
827
- throw new Error_1.AutoWAError(msg);
828
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
829
- return yield this.sock.groupParticipantsUpdate(group, participants, "add");
728
+ async forwardMessage({ to, msg, isGroup = false, ...props }) {
729
+ const { receiver, msg: err_msg } = await this.validateReceiver({
730
+ from: to,
731
+ isGroup,
830
732
  });
831
- }
832
- removeMemberFromGroup(_a) {
833
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
834
- const { receiver: group, msg } = yield this.validateReceiver({
835
- from: to,
836
- isGroup: true,
733
+ if (err_msg)
734
+ throw new AutoWAError(err_msg);
735
+ try {
736
+ return await this.sock.sendMessage(receiver, {
737
+ forward: msg,
738
+ mentions: props.mentions,
739
+ force: true,
837
740
  });
838
- if (msg)
839
- throw new Error_1.AutoWAError(msg);
840
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
841
- return yield this.sock.groupParticipantsUpdate(group, participants, "remove");
741
+ }
742
+ catch (error) {
743
+ this.logger.error("Failed forward a message!");
744
+ }
745
+ }
746
+ async getProfileInfo(target) {
747
+ const { receiver, msg } = await this.validateReceiver({
748
+ from: target,
842
749
  });
750
+ if (msg)
751
+ throw new AutoWAError(msg);
752
+ try {
753
+ const [profilePictureUrl, status] = await Promise.allSettled([
754
+ this.sock.profilePictureUrl(receiver, "image", 5000),
755
+ this.sock.fetchStatus(receiver),
756
+ ]);
757
+ return {
758
+ profilePictureUrl: profilePictureUrl.status === "fulfilled" ? profilePictureUrl.value || null : null,
759
+ status: status.status === "fulfilled" ? status.value || null : null,
760
+ };
761
+ }
762
+ catch (error) {
763
+ const msg = `Failed get profile info: ${error.message}`;
764
+ this.logger.error(msg);
765
+ }
766
+ return null;
843
767
  }
844
- promoteMemberGroup(_a) {
845
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
846
- const { receiver: group, msg } = yield this.validateReceiver({
847
- from: to,
848
- isGroup: true,
849
- });
850
- if (msg)
851
- throw new Error_1.AutoWAError(msg);
852
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
853
- return yield this.sock.groupParticipantsUpdate(group, participants, "promote");
768
+ async getGroupInfo(target) {
769
+ const { receiver, msg } = await this.validateReceiver({
770
+ from: target,
771
+ isGroup: true,
854
772
  });
773
+ if (msg)
774
+ throw new AutoWAError(msg);
775
+ try {
776
+ return await this.sock.groupMetadata(receiver);
777
+ }
778
+ catch (error) {
779
+ const msg = `Failed get group info: ${error.message}`;
780
+ this.logger.error(msg);
781
+ }
782
+ return null;
855
783
  }
856
- demoteMemberGroup(_a) {
857
- return __awaiter(this, arguments, void 0, function* ({ participants, to }) {
858
- const { receiver: group, msg } = yield this.validateReceiver({
859
- from: to,
860
- isGroup: true,
861
- });
862
- if (msg)
863
- throw new Error_1.AutoWAError(msg);
864
- participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d }));
865
- return yield this.sock.groupParticipantsUpdate(group, participants, "demote");
784
+ async addMemberToGroup({ participants, to }) {
785
+ const { receiver: group, msg } = await this.validateReceiver({
786
+ from: to,
787
+ isGroup: true,
788
+ });
789
+ if (msg)
790
+ throw new AutoWAError(msg);
791
+ participants = participants.map((d) => phoneToJid({ from: d }));
792
+ return await this.sock.groupParticipantsUpdate(group, participants, "add");
793
+ }
794
+ async removeMemberFromGroup({ participants, to }) {
795
+ const { receiver: group, msg } = await this.validateReceiver({
796
+ from: to,
797
+ isGroup: true,
798
+ });
799
+ if (msg)
800
+ throw new AutoWAError(msg);
801
+ participants = participants.map((d) => phoneToJid({ from: d }));
802
+ return await this.sock.groupParticipantsUpdate(group, participants, "remove");
803
+ }
804
+ async promoteMemberGroup({ participants, to }) {
805
+ const { receiver: group, msg } = await this.validateReceiver({
806
+ from: to,
807
+ isGroup: true,
808
+ });
809
+ if (msg)
810
+ throw new AutoWAError(msg);
811
+ participants = participants.map((d) => phoneToJid({ from: d }));
812
+ return await this.sock.groupParticipantsUpdate(group, participants, "promote");
813
+ }
814
+ async demoteMemberGroup({ participants, to }) {
815
+ const { receiver: group, msg } = await this.validateReceiver({
816
+ from: to,
817
+ isGroup: true,
866
818
  });
819
+ if (msg)
820
+ throw new AutoWAError(msg);
821
+ participants = participants.map((d) => phoneToJid({ from: d }));
822
+ return await this.sock.groupParticipantsUpdate(group, participants, "demote");
867
823
  }
868
824
  on(event, listener) {
869
825
  this.events.on(event, listener);
@@ -881,4 +837,3 @@ class AutoWA {
881
837
  this.events.removeAllListeners(event);
882
838
  }
883
839
  }
884
- exports.AutoWA = AutoWA;