UNPKG

whatsauto.js

Version:

Easy WhatsApp Automation with Session

853 lines (852 loc) • 45.2 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AutoWA = void 0; const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); const baileys_1 = __importStar(require("@whiskeysockets/baileys")); const Defaults_1 = require("../Defaults"); const Error_1 = require("../Error"); const helper_1 = require("../Utils/helper"); const AutoWAEvent_1 = __importDefault(require("./AutoWAEvent")); const mime_1 = __importDefault(require("mime")); const Logger_1 = __importDefault(require("../Logger")); const make_stiker_1 = require("../Utils/make-stiker"); const _1 = require("."); const P = require("pino")({ level: "fatal", }); class AutoWA { constructor(sessionId, options) { this.defaultStickerProps = { pack: "whatsauto.js", author: "freack21", media: null, }; if ((0, helper_1.isSessionExist)(sessionId) && _1.sessions.get(sessionId)) throw new Error_1.ValidationError(Defaults_1.Messages.sessionAlreadyExist(sessionId)); const defaultOptions = { printQR: true, logging: true, }; this.sessionId = sessionId; this.options = Object.assign(Object.assign({}, defaultOptions), options); this.callback = new Map(); this.retryCount = 0; this.event = new AutoWAEvent_1.default(this.callback); this.logger = new Logger_1.default(sessionId, this); _1.sessions.set(sessionId, this); this.logger.info("Created!"); } setLogging(logging) { return __awaiter(this, void 0, void 0, function* () { this.options.logging = logging; }); } initialize() { return __awaiter(this, void 0, void 0, function* () { this.logger.info("Initializing..."); yield this.startWhatsApp(this.sessionId, this.options); }); } startWhatsApp() { return __awaiter(this, arguments, void 0, function* (sessionId = "mySession", options = { printQR: true }) { if (typeof options.phoneNumber == "string") { if (options.phoneNumber === "") throw new Error_1.ValidationError(Defaults_1.Messages.paremetersNotValid("phoneNumber")); options.printQR = false; options.phoneNumber = (0, helper_1.phoneToJid)({ from: options.phoneNumber, }); } return this.startSocket(sessionId, options); }); } startSocket(sessionId, options) { return __awaiter(this, void 0, void 0, function* () { try { const { version } = yield (0, baileys_1.fetchLatestBaileysVersion)(); const { state, saveCreds } = yield (0, baileys_1.useMultiFileAuthState)(path_1.default.resolve(Defaults_1.CREDENTIALS.DIR_NAME, sessionId + Defaults_1.CREDENTIALS.PREFIX)); this.sock = (0, baileys_1.default)({ version, printQRInTerminal: options.printQR, auth: state, logger: P, markOnlineOnConnect: false, browser: baileys_1.Browsers.baileys(this.sessionId), }); return this.setupWASocket(saveCreds); } catch (error) { const msg = `Failed initiliaze WASocket: ${error.message}`; this.logger.error(msg); throw new Error_1.AutoWAError(msg); } }); } setupWASocket(saveCreds) { return __awaiter(this, void 0, void 0, function* () { var _a; try { if (typeof this.options.phoneNumber == "string" && !this.options.printQR && !this.pairingCode && !this.sock.authState.creds.registered) { try { this.pairingCode = yield this.sock.requestPairingCode((0, helper_1.phoneToJid)({ from: this.options.phoneNumber, reverse: true })); this.logger.info(`Pairing Code: ${this.pairingCode}`); (_a = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PAIRING_CODE)) === null || _a === void 0 ? void 0 : _a(this.pairingCode); this.retryCount = 0; } catch (error) { this.logger.warn("Retry connecting for Pairing Code..."); yield (0, helper_1.createDelay)(5000); this.retryCount++; return yield this.startSocket(this.sessionId, this.options); } } this.sock.ev.on("connection.update", (update) => __awaiter(this, void 0, void 0, function* () { var _a, _b, _c, _d, _e, _f; const { connection, lastDisconnect, qr } = update; if (this.options.printQR && qr) { this.logger.info("QR Updated!"); (_a = this.callback.get(Defaults_1.CALLBACK_KEY.ON_QR)) === null || _a === void 0 ? void 0 : _a(qr); } if (connection == "connecting") { this.logger.info("Connecting..."); (_b = this.callback.get(Defaults_1.CALLBACK_KEY.ON_CONNECTING)) === null || _b === void 0 ? void 0 : _b(); } if (connection === "close" && !this.pairingCode) { const code = (_d = (_c = lastDisconnect === null || lastDisconnect === void 0 ? void 0 : lastDisconnect.error) === null || _c === void 0 ? void 0 : _c.output) === null || _d === void 0 ? void 0 : _d.statusCode; let shouldRetry = false; if (code != baileys_1.DisconnectReason.loggedOut && this.retryCount < 10) { shouldRetry = true; } if (shouldRetry) { this.logger.warn("Retry connecting..."); this.retryCount++; return yield this.startSocket(this.sessionId, this.options); } else { this.logger.warn("Disconnected!"); this.retryCount = 0; (_e = this.callback.get(Defaults_1.CALLBACK_KEY.ON_DISCONNECTED)) === null || _e === void 0 ? void 0 : _e(); try { yield this.destroy(); } catch (error) { } return; } } if (connection == "open") { this.logger.info("Connected!"); this.retryCount = 0; (_f = this.callback.get(Defaults_1.CALLBACK_KEY.ON_CONNECTED)) === null || _f === void 0 ? void 0 : _f(); } })); this.sock.ev.on("creds.update", () => __awaiter(this, void 0, void 0, function* () { yield saveCreds(); })); this.sock.ev.on("messages.update", (message) => __awaiter(this, void 0, void 0, function* () { var _a; const msg = message[0]; const data = Object.assign({ sessionId: this.sessionId, messageStatus: (0, helper_1.parseMessageStatusCodeToReadable)(msg.update.status) }, msg); (_a = this.callback.get(Defaults_1.CALLBACK_KEY.ON_MESSAGE_UPDATED)) === null || _a === void 0 ? void 0 : _a(data); })); this.sock.ev.on("messages.upsert", (new_message) => __awaiter(this, void 0, void 0, function* () { 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, _0, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13; if (new_message.type == "append") return; const myJid = (0, helper_1.phoneToJid)({ from: this.sock.user.id }); let msg = (_a = new_message.messages) === null || _a === void 0 ? void 0 : _a[0]; if ((_b = msg.message) === null || _b === void 0 ? void 0 : _b.documentWithCaptionMessage) msg = Object.assign(Object.assign({}, msg), { message: msg.message.documentWithCaptionMessage.message }); else if ((_c = msg.message) === null || _c === void 0 ? void 0 : _c.ephemeralMessage) msg = Object.assign(Object.assign({}, msg), { message: (_d = msg.message.ephemeralMessage) === null || _d === void 0 ? void 0 : _d.message }); msg.sessionId = this.sessionId; let quotedMessage = null; const msgContextInfo = ((_f = (_e = msg.message) === null || _e === void 0 ? void 0 : _e.extendedTextMessage) === null || _f === void 0 ? void 0 : _f.contextInfo) || ((_h = (_g = msg.message) === null || _g === void 0 ? void 0 : _g.imageMessage) === null || _h === void 0 ? void 0 : _h.contextInfo) || ((_k = (_j = msg.message) === null || _j === void 0 ? void 0 : _j.videoMessage) === null || _k === void 0 ? void 0 : _k.contextInfo) || ((_m = (_l = msg.message) === null || _l === void 0 ? void 0 : _l.stickerMessage) === null || _m === void 0 ? void 0 : _m.contextInfo) || ((_p = (_o = msg.message) === null || _o === void 0 ? void 0 : _o.documentMessage) === null || _p === void 0 ? void 0 : _p.contextInfo); if (msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.quotedMessage) { quotedMessage = { key: { remoteJid: (_q = msg.key) === null || _q === void 0 ? void 0 : _q.remoteJid, id: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.stanzaId, participant: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.participant, fromMe: (msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.participant) == myJid, }, message: msgContextInfo === null || msgContextInfo === void 0 ? void 0 : msgContextInfo.quotedMessage, }; } if ((_r = quotedMessage === null || quotedMessage === void 0 ? void 0 : quotedMessage.message) === null || _r === void 0 ? void 0 : _r.documentWithCaptionMessage) { quotedMessage = Object.assign(Object.assign({}, quotedMessage), { message: quotedMessage.message.documentWithCaptionMessage.message }); } msg.quotedMessage = quotedMessage; const mediaTypes = ["image", "audio", "video", "document"]; const setupMsg = (msg, parent) => { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; const text = ((_a = msg.message) === null || _a === void 0 ? void 0 : _a.conversation) || ((_c = (_b = msg.message) === null || _b === void 0 ? void 0 : _b.extendedTextMessage) === null || _c === void 0 ? void 0 : _c.text) || ((_e = (_d = msg.message) === null || _d === void 0 ? void 0 : _d.imageMessage) === null || _e === void 0 ? void 0 : _e.caption) || ((_g = (_f = msg.message) === null || _f === void 0 ? void 0 : _f.videoMessage) === null || _g === void 0 ? void 0 : _g.caption) || ((_j = (_h = msg.message) === null || _h === void 0 ? void 0 : _h.documentMessage) === null || _j === void 0 ? void 0 : _j.caption) || ""; msg.text = text; const mimeType = (0, helper_1.getMediaMimeType)(msg); const ext = mime_1.default.getExtension(mimeType); msg.hasMedia = mimeType !== ""; msg.mediaType = ""; if (mimeType) msg.mediaType = mediaTypes[mediaTypes.indexOf(mimeType.split("/")[0]) !== -1 ? mediaTypes.indexOf(mimeType.split("/")[0]) : 3]; msg.downloadMedia = () => __awaiter(this, void 0, void 0, function* () { return Promise.resolve(""); }); msg.toSticker = () => __awaiter(this, void 0, void 0, function* () { return Promise.resolve([null, false]); }); if (msg.hasMedia) { msg.downloadMedia = (...args_1) => __awaiter(this, [...args_1], void 0, function* (opts = {}) { return this.downloadMedia(msg, opts, ext); }); } if (msg.hasMedia || ((_k = msg.quotedMessage) === null || _k === void 0 ? void 0 : _k.hasMedia)) { msg.toSticker = (props) => __awaiter(this, void 0, void 0, function* () { let mediaBuf; if (msg.hasMedia && ["image", "video"].includes(msg.mediaType)) { mediaBuf = yield msg.downloadMedia({ asBuffer: true }); } else if (msg.quotedMessage && msg.quotedMessage.hasMedia && ["image", "video"].includes(msg.quotedMessage.mediaType)) { mediaBuf = yield msg.quotedMessage.downloadMedia({ asBuffer: true }); } if (!mediaBuf) return [null, false]; const stickerProps = Object.assign(Object.assign(Object.assign({}, this.defaultStickerProps), props), { media: mediaBuf }); const buffer = yield (0, make_stiker_1.makeWebpBuffer)(stickerProps); return [buffer, true]; }); } const from = ((_l = msg.key) === null || _l === void 0 ? void 0 : _l.remoteJid) || ""; const participant = ((_m = msg.key) === null || _m === void 0 ? void 0 : _m.participant) || ""; const isGroup = from.includes("@g.us"); const isStory = from.includes("status@broadcast"); const isReaction = ((_o = msg.message) === null || _o === void 0 ? void 0 : _o.reactionMessage) ? true : false; // if (!parent) if ((_p = msg.key) === null || _p === void 0 ? void 0 : _p.fromMe) { msg.from = from; msg.receiver = from; msg.author = myJid; } else { msg.from = from; msg.receiver = myJid; msg.author = from; if (isGroup || isStory) msg.author = participant; if (isGroup) msg.receiver = from; } msg.isGroup = isGroup; msg.isStory = isStory; msg.isReaction = isReaction; if (isReaction) msg.text = (_r = (_q = msg.message) === null || _q === void 0 ? void 0 : _q.reactionMessage) === null || _r === void 0 ? void 0 : _r.text; msg.replyWithText = (text, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendText(Object.assign(Object.assign({}, opts), { text, to: from, answering: msg })); }); msg.replyWithAudio = (media, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendAudio(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg })); }); msg.replyWithImage = (media, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendImage(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg })); }); msg.replyWithVideo = (media, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendVideo(Object.assign(Object.assign({ media }, opts), { to: from, answering: msg })); }); msg.replyWithSticker = (sticker, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendSticker(Object.assign(Object.assign({ sticker }, opts), { to: from, answering: msg })); }); msg.replyWithTyping = (duration) => __awaiter(this, void 0, void 0, function* () { return yield this.sendTyping({ to: from, duration }); }); msg.replyWithRecording = (duration) => __awaiter(this, void 0, void 0, function* () { return yield this.sendRecording({ to: from, duration }); }); msg.read = () => __awaiter(this, void 0, void 0, function* () { return yield this.readMessage([msg]); }); msg.react = (reaction) => __awaiter(this, void 0, void 0, function* () { return yield this.sendReaction({ to: from, answering: msg, text: reaction }); }); msg.forward = (to, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.forwardMessage(Object.assign({ to, msg }, opts)); }); }; msg.quotedMessage && setupMsg(msg.quotedMessage, msg); setupMsg(msg); const { isStory, isReaction, isGroup } = msg; if (msg.key.fromMe) { (_s = this.callback.get(Defaults_1.CALLBACK_KEY.ON_MESSAGE_SENT)) === null || _s === void 0 ? void 0 : _s(msg); if (isStory) { (_t = this.callback.get(Defaults_1.CALLBACK_KEY.ON_STORY_SENT)) === null || _t === void 0 ? void 0 : _t(msg); } else if (isReaction) { (_u = this.callback.get(Defaults_1.CALLBACK_KEY.ON_REACTION_SENT)) === null || _u === void 0 ? void 0 : _u(msg); if (isGroup) (_v = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_REACTION_SENT)) === null || _v === void 0 ? void 0 : _v(msg); else (_w = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PRIVATE_REACTION_SENT)) === null || _w === void 0 ? void 0 : _w(msg); } else if (isGroup) { (_x = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_MESSAGE_SENT)) === null || _x === void 0 ? void 0 : _x(msg); } else { (_y = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PRIVATE_MESSAGE_SENT)) === null || _y === void 0 ? void 0 : _y(msg); } } else { (_z = this.callback.get(Defaults_1.CALLBACK_KEY.ON_MESSAGE_RECEIVED)) === null || _z === void 0 ? void 0 : _z(msg); if (isStory) { (_0 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_STORY_RECEIVED)) === null || _0 === void 0 ? void 0 : _0(msg); } else if (isReaction) { (_2 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_REACTION_RECEIVED)) === null || _2 === void 0 ? void 0 : _2(msg); if (isGroup) (_3 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_REACTION_RECEIVED)) === null || _3 === void 0 ? void 0 : _3(msg); else (_4 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PRIVATE_REACTION_RECEIVED)) === null || _4 === void 0 ? void 0 : _4(msg); } else if (isGroup) { (_5 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_MESSAGE_RECEIVED)) === null || _5 === void 0 ? void 0 : _5(msg); } else { (_6 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PRIVATE_MESSAGE_RECEIVED)) === null || _6 === void 0 ? void 0 : _6(msg); } } if (isStory) { (_7 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_STORY)) === null || _7 === void 0 ? void 0 : _7(msg); } else if (isReaction) { (_8 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_REACTION)) === null || _8 === void 0 ? void 0 : _8(msg); if (isGroup) (_9 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_REACTION)) === null || _9 === void 0 ? void 0 : _9(msg); else (_10 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PRIVATE_REACTION)) === null || _10 === void 0 ? void 0 : _10(msg); } else if (isGroup) { (_11 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_MESSAGE)) === null || _11 === void 0 ? void 0 : _11(msg); } else { (_12 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_PRIVATE_MESSAGE)) === null || _12 === void 0 ? void 0 : _12(msg); } (_13 = this.callback.get(Defaults_1.CALLBACK_KEY.ON_MESSAGE)) === null || _13 === void 0 ? void 0 : _13(msg); })); this.sock.ev.on("group-participants.update", (data) => __awaiter(this, void 0, void 0, function* () { var _a; const msg = Object.assign(Object.assign({}, data), { sessionId: this.sessionId }); msg.replyWithText = (text, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendText(Object.assign(Object.assign({}, opts), { text, to: data.id })); }); msg.replyWithAudio = (media, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendAudio(Object.assign(Object.assign({ media }, opts), { to: data.id })); }); msg.replyWithImage = (media, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendImage(Object.assign(Object.assign({ media }, opts), { to: data.id })); }); msg.replyWithVideo = (media, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendVideo(Object.assign(Object.assign({ media }, opts), { to: data.id })); }); msg.replyWithSticker = (sticker, opts) => __awaiter(this, void 0, void 0, function* () { return yield this.sendSticker(Object.assign(Object.assign({ sticker }, opts), { to: data.id })); }); msg.replyWithTyping = (duration) => __awaiter(this, void 0, void 0, function* () { return yield this.sendTyping({ to: data.id, duration }); }); msg.replyWithRecording = (duration) => __awaiter(this, void 0, void 0, function* () { return yield this.sendRecording({ to: data.id, duration }); }); (_a = this.callback.get(Defaults_1.CALLBACK_KEY.ON_GROUP_MEMBER_UPDATE)) === null || _a === void 0 ? void 0 : _a(msg); })); return this.sock; } catch (error) { const msg = `Failed setup WASocket: ${error.message}`; this.logger.error(msg); throw new Error_1.AutoWAError(msg); } }); } destroy(full) { return __awaiter(this, void 0, void 0, function* () { this.logger.info("Destroying..."); let error = false; let msg = ""; try { yield this.sock.logout(); } catch (err) { msg = `Logout failed: ${err.message}`; error = true; } finally { this.sock.end(undefined); if (full) { const dir = path_1.default.resolve(Defaults_1.CREDENTIALS.DIR_NAME, this.sessionId + Defaults_1.CREDENTIALS.PREFIX); if (fs_1.default.existsSync(dir)) { fs_1.default.rmSync(dir, { force: true, recursive: true }); } } this.logger.info("Destroyed!"); } if (error) { this.logger.error(msg); throw new Error_1.AutoWAError(msg); } }); } isExist(_a) { return __awaiter(this, arguments, void 0, function* ({ from, isGroup = false }) { var _b, _c; try { const receiver = (0, helper_1.phoneToJid)({ from: from, isGroup, }); if (receiver.includes("@broadcast")) { return true; } else if (!receiver.includes("@g.us")) { 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); } else { return Boolean((yield this.sock.groupMetadata(receiver)).id); } } catch (error) { const msg = `Failed get exist status: ${error.message}`; this.logger.error(msg); throw new Error_1.AutoWAError(msg); } }); } downloadMedia(msg, opts, ext) { return __awaiter(this, void 0, void 0, function* () { const filePath = path_1.default.join(process.cwd(), (opts.path || "my_media") + "." + ext); const buf = yield (0, baileys_1.downloadMediaMessage)(msg, "buffer", {}); if (opts.asBuffer) return Promise.resolve(buf); fs_1.default.writeFileSync(filePath, buf); return Promise.resolve(filePath); }); } validateReceiver(_a) { return __awaiter(this, arguments, void 0, function* ({ from, isGroup = false }) { const oldPhone = from; from = (0, helper_1.phoneToJid)({ from, isGroup }); const isRegistered = yield this.isExist({ from, isGroup, }); if (!isRegistered) { return { msg: `${oldPhone} is not registered on Whatsapp`, }; } return { receiver: from, }; }); } sendText(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, text = "", isGroup = false } = _a, props = __rest(_a, ["to", "text", "isGroup"]); const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); return yield this.sock.sendMessage(receiver, { text: text, mentions: props.mentions, }, { quoted: props.answering, }); }); } sendImage(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, text = "", isGroup = false, media, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "failMsg"]); if (!media) throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL"); const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); try { return yield this.sock.sendMessage(receiver, { image: typeof media == "string" ? { url: media, } : media, caption: text, mentions: props.mentions, }, { quoted: props.answering, }); } catch (error) { this.logger.error("Failed send media:" + error.message); return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the image🄹" }, props)); } }); } sendVideo(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, text = "", isGroup = false, media, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "failMsg"]); if (!media) throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL"); const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); try { return yield this.sock.sendMessage(receiver, { video: typeof media == "string" ? { url: media, } : media, caption: text, mentions: props.mentions, }, { quoted: props.answering, }); } catch (error) { this.logger.error("Failed send media:" + error.message); return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the video🄹" }, props)); } }); } sendDocument(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, text = "", isGroup = false, media, filename, failMsg } = _a, props = __rest(_a, ["to", "text", "isGroup", "media", "filename", "failMsg"]); if (!media) throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL"); const mimetype = mime_1.default.getType(filename); if (!mimetype) throw new Error_1.AutoWAError(`Filename must include valid extension`); const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); try { return yield this.sock.sendMessage(receiver, { fileName: filename, document: typeof media == "string" ? { url: media, } : media, mimetype: mimetype, caption: text, mentions: props.mentions, }, { quoted: props.answering, }); } catch (error) { this.logger.error("Failed send media:" + error.message); return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the document" }, props)); } }); } sendAudio(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, isGroup = false, media, voiceNote = false, failMsg } = _a, props = __rest(_a, ["to", "isGroup", "media", "voiceNote", "failMsg"]); if (!media) throw new Error_1.AutoWAError("'media' parameter must be Buffer or String URL"); const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); try { return yield this.sock.sendMessage(receiver, { audio: typeof media == "string" ? { url: media, } : media, ptt: voiceNote, mentions: props.mentions, }, { quoted: props.answering, }); } catch (error) { this.logger.error("Failed send media:" + error.message); return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the audio🄹" }, props)); } }); } sendReaction(_a) { return __awaiter(this, arguments, void 0, function* ({ to, text, isGroup = false, answering }) { const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); return yield this.sock.sendMessage(receiver, { react: { text, key: answering.key, }, }); }); } sendTyping(_a) { return __awaiter(this, arguments, void 0, function* ({ to, duration = 1000, isGroup = false }) { const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); yield this.sock.sendPresenceUpdate("composing", receiver); yield (0, helper_1.createDelay)(duration); yield this.sock.sendPresenceUpdate("available", receiver); }); } sendRecording(_a) { return __awaiter(this, arguments, void 0, function* ({ to, duration = 1000, isGroup = false }) { const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); yield this.sock.sendPresenceUpdate("recording", receiver); yield (0, helper_1.createDelay)(duration); yield this.sock.sendPresenceUpdate("available", receiver); }); } readMessage(msgs) { return __awaiter(this, void 0, void 0, function* () { yield this.sock.readMessages(msgs.map((msg) => msg.key)); }); } sendSticker(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, isGroup, sticker, media, failMsg, hasMedia } = _a, props = __rest(_a, ["to", "isGroup", "sticker", "media", "failMsg", "hasMedia"]); const { receiver, msg } = yield this.validateReceiver({ from: to, isGroup, }); if (msg) throw new Error_1.AutoWAError(msg); if (!media && !sticker && !hasMedia) throw new Error_1.AutoWAError("'media' or 'sticker' parameter must be filled"); if (!sticker) { if (!(typeof media === "string" || Buffer.isBuffer(media)) && !hasMedia) { throw new Error_1.AutoWAError("'media' parameter must be string or buffer"); } const stickerProps = Object.assign(Object.assign(Object.assign({}, this.defaultStickerProps), { media }), props); sticker = yield (0, make_stiker_1.makeWebpBuffer)(stickerProps); } if (!sticker || !Buffer.isBuffer(sticker)) { return yield this.sendText(Object.assign({ to, text: failMsg || "There is error while creating the sticker🄹", isGroup }, props)); } try { return yield this.sock.sendMessage(receiver, { sticker, mentions: props.mentions, }, { quoted: props.answering, }); } catch (error) { this.logger.error("Failed send media:" + error.message); return yield this.sendText(Object.assign({ to: receiver, text: failMsg || "There is error while trying to send the sticker🄹" }, props)); } }); } forwardMessage(_a) { return __awaiter(this, void 0, void 0, function* () { var { to, msg, isGroup = false } = _a, props = __rest(_a, ["to", "msg", "isGroup"]); const { receiver, msg: err_msg } = yield this.validateReceiver({ from: to, isGroup, }); if (err_msg) throw new Error_1.AutoWAError(err_msg); try { return yield this.sock.sendMessage(receiver, { forward: msg, mentions: props.mentions, force: true, }); } catch (error) { this.logger.error("Failed forward a message!"); } }); } getProfileInfo(target) { return __awaiter(this, void 0, void 0, function* () { const { receiver, msg } = yield this.validateReceiver({ from: target, }); if (msg) throw new Error_1.AutoWAError(msg); try { const [profilePictureUrl, status] = yield Promise.allSettled([ this.sock.profilePictureUrl(receiver, "image", 5000), this.sock.fetchStatus(receiver), ]); return { profilePictureUrl: profilePictureUrl.status === "fulfilled" ? profilePictureUrl.value || null : null, status: status.status === "fulfilled" ? status.value || null : null, }; } catch (error) { const msg = `Failed get profile info: ${error.message}`; this.logger.error(msg); } return null; }); } getGroupInfo(target) { return __awaiter(this, void 0, void 0, function* () { const { receiver, msg } = yield this.validateReceiver({ from: target, isGroup: true, }); if (msg) throw new Error_1.AutoWAError(msg); try { return yield this.sock.groupMetadata(receiver); } catch (error) { const msg = `Failed get group info: ${error.message}`; this.logger.error(msg); } return null; }); } addMemberToGroup(_a) { return __awaiter(this, arguments, void 0, function* ({ participants, to }) { const { receiver: group, msg } = yield this.validateReceiver({ from: to, isGroup: true, }); if (msg) throw new Error_1.AutoWAError(msg); participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d })); return yield this.sock.groupParticipantsUpdate(group, participants, "add"); }); } removeMemberFromGroup(_a) { return __awaiter(this, arguments, void 0, function* ({ participants, to }) { const { receiver: group, msg } = yield this.validateReceiver({ from: to, isGroup: true, }); if (msg) throw new Error_1.AutoWAError(msg); participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d })); return yield this.sock.groupParticipantsUpdate(group, participants, "remove"); }); } promoteMemberGroup(_a) { return __awaiter(this, arguments, void 0, function* ({ participants, to }) { const { receiver: group, msg } = yield this.validateReceiver({ from: to, isGroup: true, }); if (msg) throw new Error_1.AutoWAError(msg); participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d })); return yield this.sock.groupParticipantsUpdate(group, participants, "promote"); }); } demoteMemberGroup(_a) { return __awaiter(this, arguments, void 0, function* ({ participants, to }) { const { receiver: group, msg } = yield this.validateReceiver({ from: to, isGroup: true, }); if (msg) throw new Error_1.AutoWAError(msg); participants = participants.map((d) => (0, helper_1.phoneToJid)({ from: d })); return yield this.sock.groupParticipantsUpdate(group, participants, "demote"); }); } } exports.AutoWA = AutoWA;