From 873a18c718d85e484d9d6d21e447540684ff9a8a Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Wed, 21 Feb 2024 20:18:01 -0300 Subject: [PATCH 1/7] add sendMessageExtended --- src/utils/MessageAPI.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/utils/MessageAPI.js b/src/utils/MessageAPI.js index 9c24850..066f097 100644 --- a/src/utils/MessageAPI.js +++ b/src/utils/MessageAPI.js @@ -17,6 +17,10 @@ class MessageAPI { * @param {String} message - text message */ async sendMessage(chatId, phoneNumber, message) { + return this.sendMessageExtended(chatId, phoneNumber, message, "", true) + } + + async sendMessageExtended(chatId, phoneNumber, message, quotedMessageId, linkPreview) { CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); CommonUtils.validateString('message', message); @@ -24,6 +28,8 @@ class MessageAPI { const postData = { 'message': message, + 'quotedMessageId': quotedMessageId, + 'linkPreview': linkPreview } this.addChadIdParam(postData, chatId) From 32dbe22ccebc3e5ee81477ec7e320c4824b71284 Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Thu, 22 Feb 2024 12:45:26 -0300 Subject: [PATCH 2/7] add setGroupPicture --- .gitignore | 1 - lib/bundle.js | 1338 ++++++++++++++++++++++++++++++++ lib/whatsapp-api-client.min.js | 1 + package-lock.json | 4 +- package.json | 3 +- src/utils/GroupAPI.js | 41 +- 6 files changed, 1377 insertions(+), 11 deletions(-) create mode 100644 lib/bundle.js create mode 100644 lib/whatsapp-api-client.min.js diff --git a/.gitignore b/.gitignore index ac9045e..9a3c89c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ .vscode/ node_modules -lib .* !/.gitignore diff --git a/lib/bundle.js b/lib/bundle.js new file mode 100644 index 0000000..dabbd39 --- /dev/null +++ b/lib/bundle.js @@ -0,0 +1,1338 @@ +'use strict'; + +var axios = require('axios'); +var fs = require('fs'); +var mime = require('mime'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios); +var fs__namespace = /*#__PURE__*/_interopNamespace(fs); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); +var mime__default = /*#__PURE__*/_interopDefaultLegacy(mime); + +class CommonUtils { + static validateString(name, val) { + if (!val || Object.prototype.toString.call(val) !== '[object String]') + throw new Error(`${name} must be a String!`) + } + + static validateInteger(name, val) { + if (!Number.isInteger(val)) + throw new Error(`${name} must be an integer!`) + } + + static validateNumber(name, val) { + if (!val || !Number(val)) + throw new Error(`${name} must be a number!`) + } + + static validateObject(name, val) { + if (!val || Object.prototype.toString.call(val) !== '[object Object]') + throw new Error(`${name} must be an Object!`) + } + + static generateMethodURL(params, method) { + if (method === "sendFileByUpload" || method === "uploadFile") { + return `${params.media}/waInstance${params.idInstance}/${method}/${params.apiTokenInstance}` + } else { + return `${params.host}/waInstance${params.idInstance}/${method}/${params.apiTokenInstance}` + } + } + + static validateChatIdPhoneNumber(chatId, phoneNumber) { + if (!chatId) { + CommonUtils.validateInteger('phoneNumber', phoneNumber); + } + if (!phoneNumber) { + CommonUtils.validateString('chatId', chatId); + } + } + + static validateArray(name, val) { + if (!val || !Array.isArray(val)) + throw new Error(`${name} must be an Array!`) + } + + static validatePath(name, val) { + if (!val || !fs__namespace.existsSync(val)) + throw new Error(`${name} not found!`) + } +} + +class MessageAPI { + + constructor(restAPI) { + this._restAPI = restAPI; + } + + /** Send text message to chat or phone. Method call adds message to sending queue + * + * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). + * Mandatory if phoneNumber is empty + * @param {Number} phoneNumber - receiver phone number using international format without + sign. + * Mandatory if chatId is empty + * @param {String} message - text message + */ + async sendMessage(chatId, phoneNumber, message) { + return this.sendMessageExtended(chatId, phoneNumber, message, "", true) + } + + async sendMessageExtended(chatId, phoneNumber, message, quotedMessageId, linkPreview) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + CommonUtils.validateString('message', message); + + const method = 'sendMessage'; + + const postData = { + 'message': message, + 'quotedMessageId': quotedMessageId, + 'linkPreview': linkPreview + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** Send text message to chat or phone. Method call adds message to sending queue + * + * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). + * Mandatory if phoneNumber is empty + * @param {String} phoneNumber - number (77077771515@c.us - for private messages). + * @param {String} message - text message + * @param {array} options - array of objects + * @param {boolean} multipleAnswers - allow answers + * @param {String} quotedMessageId - id of message + */ + + async sendPoll(chatId, phoneNumber, message, options, multipleAnswers = null, quotedMessageId = null) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + CommonUtils.validateString('message', message); + CommonUtils.validateArray('options', options); + + const method = 'sendPoll'; + + const postData = { + 'message': message, + 'options': options, + }; + + if (multipleAnswers !== null) { + postData['multipleAnswers'] = multipleAnswers; + } + if (quotedMessageId !== null) { + postData['quotedMessageId'] = quotedMessageId; + } + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** Send buttons message to chat. Method call adds message to sending queue + * + * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). + * Mandatory if phoneNumber is empty + * @param {String} message - text message + * @param {footer} footer - footer message + * @param {array} buttons - buttons, for example [{"buttonId": "1", "buttonText": "green"}, {"buttonId": "2", "buttonText": "red"}, {"buttonId": "3", "buttonText": "blue"}] + */ + async sendButtons(chatId, message, footer, buttons) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + CommonUtils.validateString('message', message); + + const method = 'sendButtons'; + + const postData = { + 'message': message, + 'footer': footer, + 'buttons': buttons + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** Send buttons message to chat. Method call adds message to sending queue + * + * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). + * @param {String} message - text message + * @param {footer} footer - footer message + * @param {array} templateButtons - buttons, for example [ + {"index": 1, "urlButton": {"displayText": "⭐ Star us on GitHub!", "url": "/~https://github.com/green-api"}}, + {"index": 2, "callButton": {"displayText": "Call us", "phoneNumber": "+1 (234) 5678-901"}}, + {"index": 3, "quickReplyButton": {"displayText": "Plain button", "id": "plainButtonId"}} + ] + */ + async sendTemplateButtons(chatId, message, footer = null, templateButtons) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + CommonUtils.validateString('message', message); + + const method = 'sendTemplateButtons'; + + const postData = { + 'message': message, + 'templateButtons': templateButtons + }; + + if (footer !== null) { + postData.footer = footer; + } + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** Send buttons message to chat. Method call adds message to sending queue + * + * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). + * @param {String} message - text message + * @param {String} buttonText - action list + * @param {String} title - title + * @param {footer} footer - footer message + * @param {array} sections - sections, for example [ + { + "title": "Секция 1", + "rows": [ + { + "title": "Вариант 1", + "rowId": "option1" + }, + { + "title": "Вариант 2", + "rowId": "option2", + "description": "Пояснение" + } + ] + } + */ + async sendListMessage(chatId, message, buttonText, title, footer, sections) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + CommonUtils.validateString('message', message); + + const method = 'sendListMessage'; + + const postData = { + 'message': message, + 'buttonText': buttonText, + 'title': title, + 'footer': footer, + 'sections': sections, + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * @param {String} chatId + * @param {Number} phoneNumber + * @param {String} nameLocation + * @param {String} address + * @param {Number} latitude + * @param {Number} longitude + */ + async sendLocation(chatId, phoneNumber, nameLocation, address, latitude, longitude) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + CommonUtils.validateString('nameLocation', nameLocation); + CommonUtils.validateString('address', address); + CommonUtils.validateNumber('latitude', latitude); + CommonUtils.validateNumber('longitude', longitude); + + const method = 'sendLocation'; + + const postData = { + 'nameLocation': nameLocation, + 'address': address, + 'latitude': latitude, + 'longitude': longitude, + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * @param {String} chatId + * @param {Number} phoneNumber + * @param {Object} contact - object with one or more fields + */ + async sendContact(chatId, phoneNumber, contact) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + CommonUtils.validateObject('contact', contact); + + const method = 'sendContact'; + + const postData = { + 'contact': contact, + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * @param {String} chatId + * @param {Number} phoneNumber + * @param {String} urlLink + */ + async sendLink(chatId, phoneNumber, urlLink) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + CommonUtils.validateString('urlLink', urlLink); + + const method = 'sendLink'; + + const postData = { + 'urlLink': urlLink, + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * @param {String} chatId + * @param {Number} phoneNumber + * @param {String} idMessage + */ + async readChat(chatId, phoneNumber, idMessage = null) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + + const method = 'readChat'; + + const postData = { + 'idMessage': idMessage, + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * Returns array of QueueMessage objects + */ + async showMessagesQueue() { + const method = 'showMessagesQueue'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data.map((msg) => new QueueMessage(msg)) + } + + async clearMessagesQueue() { + const method = 'clearMessagesQueue'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + /** + * Returns array of Message objects + */ + async lastIncomingMessages() { + const method = 'lastIncomingMessages'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data.map((msg) => new Message(msg)) + } + + /** + * Returns array of Message objects + */ + async lastOutgoingMessages() { + const method = 'lastOutgoingMessages'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data.map((msg) => new Message(msg)) + } + + /** + * Returns history of chat + */ + async getChatHistory(chatId) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + + const method = 'getChatHistory'; + + const postData = { + 'chatId': chatId, + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * The method returns the chat message. + * + * @param {String} chatId + * @param {String} idMessage + * + */ + async getMessage(chatId, idMessage) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + CommonUtils.validateString("idMessage", idMessage); + + const method = "getMessage"; + + const postData = { + "idMessage": idMessage, + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * The method is intended for forwarding messages to a personal or group chat + * @param {String} chatId + * @param {String} chatIdFrom + * @param {Array} messages + */ + async forwardMessages(chatId, chatIdFrom, messages) { + CommonUtils.validateString('chatId', chatId); + CommonUtils.validateString('chatIdFrom', chatIdFrom); + CommonUtils.validateArray('messages', messages); + + const method = 'ForwardMessages'; + + const postData = { + 'chatId': chatId, + 'chatIdFrom': chatIdFrom, + 'messages': messages, + }; + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + addChadIdParam(postData, chatId) { + if (chatId) { + postData.chatId = chatId; + } + } + + addPhoneParam(postData, phoneNumber) { + if (phoneNumber) { + postData.chatId = `${phoneNumber}@c.us`; + } + } +} + +class Message { + constructor(data) { + this.chatId = data.chatId; + this.idMessage = data.idMessage; + this.statusMessage = data.statusMessage; + this.textMessage = data.textMessage; + this.timestamp = data.timestamp; + this.typeMessage = data.typeMessage; + } +} + +class QueueMessage { + constructor(data) { + this.chatId = data.chatId; + this.fileName = data.fileName; + this.typeMessage = data.typeMessage; + } +} + +class FileAPI { + + constructor(restAPI) { + this._restAPI = restAPI; + } + + /** + * @param {String} chatId + * @param {Number} phoneNumber + * @param {String} urlFile + * @param {String} fileName + * @param {String} caption Optional + */ + async sendFileByUrl(chatId, phoneNumber, urlFile, fileName, caption = '') { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + CommonUtils.validateString('urlFile', urlFile); + CommonUtils.validateString('filename', fileName); + + const method = 'sendFileByUrl'; + const postData = { + 'urlFile': urlFile, + 'fileName': fileName, + 'caption': caption, + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * @param {String} filePath + */ + async uploadFile(filePath) { + CommonUtils.validateString("filePath", filePath); + + const method = "uploadFile"; + + const fileData = fs__default["default"].readFileSync(filePath); + + const response = await axios__default["default"]({ + method: "post", + url: CommonUtils.generateMethodURL(this._restAPI.params, method), + data: fileData, + headers: {"Content-Type": mime__default["default"].getType(filePath)} + }); + return response.data; + } + + /** + * @param {FormData} formData + */ + async sendFileByUpload(formData) { + const method = 'sendFileByUpload'; + const response = await axios__default["default"]({ + method: 'post', + url: CommonUtils.generateMethodURL(this._restAPI.params, method), + data: formData, + headers: formData.getHeaders() + }); + return response.data; + } + + /** + * @param {String} chatId + * @param {String} idMessage + */ + async downloadFile(chatId, idMessage) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + CommonUtils.validateString('message', idMessage); + + const method = 'downloadFile'; + + const postData = { + 'idMessage': idMessage, + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + addChadIdParam(postData, chatId) { + if (chatId) { + postData.chatId = chatId; + } + } + + addPhoneParam(postData, phoneNumber) { + if (phoneNumber) { + postData.phoneNumber = phoneNumber; + } + } +} + +class InstanceAPI { + + constructor(restAPI) { + this._restAPI = restAPI; + } + + async qr() { + const method = 'qr'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + async logout() { + const method = 'logout'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + async reboot() { + const method = 'reboot'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + async getStateInstance() { + const method = 'getStateInstance'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + async getDeviceInfo() { + const method = 'getDeviceInfo'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + /** + * + * @param {Number} phoneNumber + */ + async checkWhatsapp(phoneNumber) { + CommonUtils.validateInteger('phoneNumber', phoneNumber); + + const method = 'checkWhatsapp'; + const postData = { + 'phoneNumber': phoneNumber, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * + * @param {String} chatId + * @param {Number} phoneNumber + */ + async getAvatar(chatId, phoneNumber) { + CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); + + const method = 'getAvatar'; + const postData = { + }; + + this.addChadIdParam(postData, chatId); + this.addPhoneParam(postData, phoneNumber); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * + * @param {String} chatId + */ + async archiveChat(chatId) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + + const method = 'archiveChat'; + const postData = { + + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * + * @param {String} chatId + */ + async unarchiveChat(chatId) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + + const method = 'unarchiveChat'; + const postData = { + + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + /** + * + * @param {String} chatId + */ + async getContactInfo(chatId) { + CommonUtils.validateChatIdPhoneNumber(chatId, undefined); + + const method = 'getContactInfo'; + const postData = { + + }; + + this.addChadIdParam(postData, chatId); + + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data + } + + async getContacts() { + const method = 'getContacts'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + async getChats() { + const method = 'getChats'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + addChadIdParam(postData, chatId) { + if (chatId) { + postData.chatId = chatId; + } + } + + addPhoneParam(postData, phoneNumber) { + if (phoneNumber) { + postData.phoneNumber = phoneNumber; + } + } + +} + +class SettingsAPI { + + constructor(restAPI) { + this._restAPI = restAPI; + } + + async getSettings() { + const method = 'getSettings'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data; + } + + /** + * Change instance account settings. You can specify which settings to update. + * Instance will be restarted as a result of method. + * + * @param {Object} settings - js object that consists of one or more props: + * countryInstance, webhookUrl, delaySendMessagesMilliseconds, markIncomingMessagesReaded, + * for example: + * + * settings = { + * countryInstance: "ru", + * delaySendMessagesMilliseconds: 500 + * } + * + */ + async setSettings(settings) { + CommonUtils.validateObject("settings", settings); + + const method = 'setSettings'; + const postData = settings; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + + async getWaSettings () { + const method = 'getWaSettings'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + +} + +class GroupAPI { + + constructor(restAPI) { + this._restAPI = restAPI; + } + /** + * + * @param {String} groupName + * @param {Array} chatIds + */ + async createGroup(groupName, chatIds) { + CommonUtils.validateString('groupName', groupName); + CommonUtils.validateArray('chatIds', chatIds); + + const method = 'createGroup'; + const postData = { + 'groupName': groupName, + 'chatIds': chatIds + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + * @param {String} participantChatId + * @param {Number} participantPhone + */ + async addGroupParticipant(groupId, participantChatId, participantPhone) { + CommonUtils.validateString('groupId', groupId); + CommonUtils.validateChatIdPhoneNumber(participantChatId, participantPhone); + + const method = 'addGroupParticipant'; + const postData = { + 'groupId': groupId, + 'participantChatId': participantChatId, + 'participantPhone': participantPhone, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + */ + async getGroupData(groupId) { + CommonUtils.validateString('groupId', groupId); + + const method = 'getGroupData'; + const postData = { + 'groupId': groupId, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + * @param {String} participantChatId + * @param {Number} participantPhone + */ + async removeGroupParticipant(groupId, participantChatId, participantPhone) { + CommonUtils.validateString('groupId', groupId); + CommonUtils.validateChatIdPhoneNumber(participantChatId, participantPhone); + + const method = 'removeGroupParticipant'; + const postData = { + 'groupId': groupId, + 'participantChatId': participantChatId, + 'participantPhone': participantPhone, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + * @param {String} groupName + */ + async updateGroupName(groupId, groupName) { + CommonUtils.validateString('groupId', groupId); + CommonUtils.validateString('groupName', groupName); + + const method = 'updateGroupName'; + const postData = { + 'groupId': groupId, + 'groupName': groupName, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + * @param {String} participantChatId + * @param {Number} participantPhone + */ + async setGroupAdmin(groupId, participantChatId, participantPhone) { + CommonUtils.validateString('groupId', groupId); + + const method = 'setGroupAdmin'; + const postData = { + 'groupId': groupId, + 'participantChatId': participantChatId, + 'participantPhone': participantPhone, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + * @param {String} participantChatId + * @param {Number} participantPhone + */ + async removeAdmin(groupId, participantChatId, participantPhone) { + CommonUtils.validateString('groupId', groupId); + + const method = 'removeAdmin'; + const postData = { + 'groupId': groupId, + 'participantChatId': participantChatId, + 'participantPhone': participantPhone, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * + * @param {String} groupId + */ + async leaveGroup(groupId) { + CommonUtils.validateString('groupId', groupId); + + const method = 'removeAdmin'; + const postData = { + 'groupId': groupId, + }; + const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); + return response.data; + } + + /** + * @param {String} filePath + * @param {String} groupId + */ + async setGroupPicture(groupId, filePath) { + CommonUtils.validateString("filePath", filePath); + + const method = "setGroupPicture"; + + const fileStream = fs__default["default"].createReadStream(filePath); + const fileData = []; + + for await (const data of fileStream) { + fileData.push(data); + } + + const blob = new Blob(fileData, { type: 'image/jpeg' }); + + const formData = new FormData(); + formData.append('groupId', groupId); + formData.append('file', blob, "group_avatar.jpeg"); + + const response = await axios__default["default"]({ + method: "post", + url: CommonUtils.generateMethodURL(this._restAPI.params, method), + data: formData, + headers: {"Content-Type": "multipart/form-data"} + }); + return response.data; + } +} + +class SingleThreadJobScheduler { + + initJobs(jobs = []) { + this.jobs = jobs; + } + + reschedule() { + this.jobs.forEach(job => { + job.needInterrupt = false; + clearInterval(job.timerId); + job.timerId = setInterval(job.run, job.intervalSec * 1000); + }); + } + + unschedule() { + this.jobs.forEach(job => { + job.needInterrupt = true; + clearInterval(job.timerId); + }); + } +} + +class ReceiveNotificationsJob { + + timerId; + intervalSec; + needInterrupt = false + + constructor(webhookServiceApi) { + this.webhookServiceApi = webhookServiceApi; + this.intervalSec = Number.parseInt('1'); + } + + run = async () => { + clearInterval(this.timerId); + try { + let response; + while (response = await this.webhookServiceApi.receiveNotification()) { + let webhookBody = response.body; + if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.incomingMessageReceived) { + if (webhookBody.messageData.typeMessage == "imageMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageImage, webhookBody); + } else if (webhookBody.messageData.typeMessage == "videoMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageVideo, webhookBody); + } else if (webhookBody.messageData.typeMessage == "documentMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument, webhookBody); + } else if (webhookBody.messageData.typeMessage == "audioMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageAudio, webhookBody); + } else if (webhookBody.messageData.typeMessage == "documentMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument, webhookBody); + } else if (webhookBody.messageData.typeMessage == "textMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageText, webhookBody); + } else if (webhookBody.messageData.typeMessage == "extendedTextMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageTextURL, webhookBody); + } else if (webhookBody.messageData.typeMessage == "contactMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageContact, webhookBody); + } else if (webhookBody.messageData.typeMessage == "locationMessage") { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageLocation, webhookBody); + } + } else if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.stateInstanceChanged) { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingAccountStatus, webhookBody); + } else if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.outgoingMessageStatus) { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingOutboundMessageStatus, webhookBody); + } else if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.deviceInfo) { + this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingDeviceStatus, webhookBody); + } + await this.webhookServiceApi.deleteNotification(response.receiptId); + } + } catch (ex) { + console.error(ex.toString()); + } + if (!this.needInterrupt) { + this.timerId = setInterval(this.run, this.intervalSec * 1000); + } + } + + callCallback(webhookType, body) { + const callback = this.webhookServiceApi._callbacks.get(webhookType); + if (callback) { + // Found webhook callback; + callback.call(this, body); + // Callback invoked successfully; + } } + +} + +class WebhookServiceAPI { + + constructor(restAPI) { + this._restAPI = restAPI; + this._jobScheduler = new SingleThreadJobScheduler(); + this.noteTypes = { + incomingMessageReceived : 'incomingMessageReceived', + outgoingMessageStatus : 'outgoingMessageStatus', + stateInstanceChanged : 'stateInstanceChanged', + deviceInfo: 'deviceInfo', + }; + this.callbackTypes = { + onReceivingMessageText : 'onReceivingMessageText', + onReceivingMessageImage : 'onReceivingMessageImage', + onReceivingMessageVideo : 'onReceivingMessageVideo', + onReceivingMessageDocument: 'onReceivingMessageDocument', + onReceivingMessageAudio: 'onReceivingMessageAudio', + onReceivingOutboundMessageStatus: 'onReceivingOutboundMessageStatus', + onReceivingAccountStatus: 'onReceivingAccountStatus', + onReceivingDeviceStatus: 'onReceivingDeviceStatus', + onReceivingMessageTextURL: 'onReceivingMessageTextURL', + onReceivingMessageContact: 'onReceivingMessageContact', + onReceivingMessageLocation: 'onReceivingMessageLocation', + }; + this._callbacks = new Map(); + } + + async receiveNotification() { + const method = 'receiveNotification'; + const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); + return response.data + } + + /** + * + * @param {Number} receiptId + */ + async deleteNotification(receiptId) { + CommonUtils.validateInteger('receiptId', receiptId); + + const method = 'deleteNotification'; + const response = await axios__default["default"].delete(`${CommonUtils.generateMethodURL(this._restAPI.params, method)}/${receiptId}`); + return response.data + } + + async startReceivingNotifications() { + this._jobScheduler.initJobs([new ReceiveNotificationsJob(this)]); + this._jobScheduler.reschedule(); + } + + async stopReceivingNotifications() { + this._jobScheduler.unschedule(); + } + + onReceivingMessageText(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageText, callback); + } + onReceivingMessageImage(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageImage, callback); + } + onReceivingMessageVideo(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageVideo, callback); + } + onReceivingMessageDocument(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageDocument, callback); + } + onReceivingMessageAudio(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageAudio, callback); + } + onReceivingOutboundMessageStatus(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingOutboundMessageStatus, callback); + } + onReceivingAccountStatus(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingAccountStatus, callback); + } + onReceivingDeviceStatus(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingDeviceStatus, callback); + } + onReceivingMessageTextURL(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageTextURL, callback); + } + onReceivingMessageContact(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageContact, callback); + } + onReceivingMessageLocation(callback) + { + this._callbacks.set(this.callbackTypes.onReceivingMessageLocation, callback); + } +} + +class RestAPI { + + constructor(params) { + + this.params = { + host: "", + media: "", + idInstance: "", + apiTokenInstance: "", + credentialsPath: null, + }; + + Object.assign(this.params, params); + + if (params.credentialsPath) { + fs__namespace.readFileSync(params.credentialsPath) + .toString('utf8') + .split('\n') + .map(item => item.split(" ").join("")) // replaceAll equivalent + .forEach(item => { + if (item.startsWith('API_TOKEN_INSTANCE=')) { + this.params.apiTokenInstance = item.replace('API_TOKEN_INSTANCE=', '').trim(); + } else if (item.startsWith('ID_INSTANCE=')) { + this.params.idInstance = item.replace('ID_INSTANCE=', '').trim(); + } + }); + } + + this.message = new MessageAPI(this); + this.file = new FileAPI(this); + this.instance = new InstanceAPI(this); + this.settings = new SettingsAPI(this); + this.group = new GroupAPI(this); + this.webhookService = new WebhookServiceAPI(this); + } +} + +var configuration = { + defaultHost: "https://api.green-api.com", + defaultMediaHost: "https://media.green-api.com" +}; + +class WebhooksCallbackAPI { + + constructor(express, webhookRoutePath) { + this._app = express; + this._webhookRoutePath = webhookRoutePath; + this._callbacks = new Map(); + } + + init() { + this._app.post(this._webhookRoutePath, async (req, res, next) => { + try { + console.log(`Received webhook ${req.body.typeWebhook}`); + let webhookType = null; + if (req.body.messageData && req.body.messageData.typeMessage) { + webhookType = `${req.body.typeWebhook}_${req.body.messageData.typeMessage}`; + } else { + webhookType = req.body.typeWebhook; + } + + const callback = this._callbacks.get(webhookType); + if (callback) { + // Found webhook callback; + callback.call(this, req.body); + // Callback invoked successfully; + } else { + // Callback not found; + }; + return res.send(); + } catch (err) { + next(err); + } + }); + } + + /** + * + * @param {Function} callback function + */ + onStateInstance(callback) { + this._callbacks.set("stateInstanceChanged", callback); + } + + /** + * + * @param {Function} callback function + */ + onOutgoingMessageStatus(callback) { + this._callbacks.set("outgoingMessageStatus", (data) => { + callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.status); + }); + } + + /** + * + * @param {Function} callback function + */ + onIncomingMessageText(callback) { + this._callbacks.set("incomingMessageReceived_textMessage", (data) => { + callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, + data.messageData.textMessageData.textMessage); + }); + } + + /** + * + * @param {Function} callback function + */ + onIncomingMessageFile(callback) { + this._callbacks.set("incomingMessageReceived_imageMessage", (data) => { + callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, + data.messageData.downloadUrl); + }); + } + + /** + * + * @param {Function} callback function + */ + onIncomingMessageLocation(callback) { + this._callbacks.set("incomingMessageReceived_locationMessage", (data) => { + callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, + data.messageData.locationMessageData.latitude, data.messageData.locationMessageData.longitude, data.messageData.locationMessageData.jpegThumbnail); + }); + } + + /** + * + * @param {Function} callback function + */ + onIncomingMessageContact(callback) { + this._callbacks.set("incomingMessageReceived_contactMessage", (data) => { + callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, + data.messageData.contactMessageData.displayName, data.messageData.contactMessageData.vcard); + }); + } + + /** + * + * @param {Function} callback function + */ + onIncomingMessageExtendedText(callback) { + this._callbacks.set("incomingMessageReceived_extendedTextMessage", (data) => { + callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, + data.extendedTextMessageData); + }); + } + + /** + * + * @param {Function} callback function + */ + onDeviceInfo(callback) { + this._callbacks.set("deviceInfo", callback); + } + +} + +function checkInitParams(params = {}) { + + if (params.host) { + CommonUtils.validateString("host", params.host); + } else { + params.host = configuration.defaultHost; + } + + if (params.media) { + CommonUtils.validateString("media", params.media); + } else { + params.media = configuration.defaultMediaHost; + } + + if (params.credentialsPath) { + CommonUtils.validatePath("credentialsPath", params.credentialsPath); + } else { + CommonUtils.validateString("idInstance", params.idInstance); + CommonUtils.validateString("apiTokenInstance", params.apiTokenInstance); + } +} + +const restAPI = (params = {}) => { + checkInitParams(params); + return new RestAPI(params) +}; + +const webhookAPI = (express, webhookRoutePath) => { + const api = new WebhooksCallbackAPI(express, webhookRoutePath); + api.init(); + return api; +}; + +var index = { + restAPI, + webhookAPI +}; + +module.exports = index; diff --git a/lib/whatsapp-api-client.min.js b/lib/whatsapp-api-client.min.js new file mode 100644 index 0000000..02db9cc --- /dev/null +++ b/lib/whatsapp-api-client.min.js @@ -0,0 +1 @@ +!function(e,a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a(require("axios"),require("fs"),require("mime")):"function"==typeof define&&define.amd?define(["axios","fs","mime"],a):(e="undefined"!=typeof globalThis?globalThis:e||self).whatsAppClient=a(e.axios,e.fs,e.mime)}(this,(function(e,a,t){"use strict";function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var a=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}})),a.default=e,Object.freeze(a)}var n=s(e),r=i(a),o=s(a),d=s(t);class c{static validateString(e,a){if(!a||"[object String]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be a String!`)}static validateInteger(e,a){if(!Number.isInteger(a))throw new Error(`${e} must be an integer!`)}static validateNumber(e,a){if(!a||!Number(a))throw new Error(`${e} must be a number!`)}static validateObject(e,a){if(!a||"[object Object]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be an Object!`)}static generateMethodURL(e,a){return"sendFileByUpload"===a||"uploadFile"===a?`${e.media}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`:`${e.host}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`}static validateChatIdPhoneNumber(e,a){e||c.validateInteger("phoneNumber",a),a||c.validateString("chatId",e)}static validateArray(e,a){if(!a||!Array.isArray(a))throw new Error(`${e} must be an Array!`)}static validatePath(e,a){if(!a||!r.existsSync(a))throw new Error(`${e} not found!`)}}class g{constructor(e){this._restAPI=e}async sendMessage(e,a,t){return this.sendMessageExtended(e,a,t,"",!0)}async sendMessageExtended(e,a,t,s,i){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t);const r={message:t,quotedMessageId:s,linkPreview:i};this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendMessage"),r)).data}async sendPoll(e,a,t,s,i=null,r=null){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t),c.validateArray("options",s);const o={message:t,options:s};null!==i&&(o.multipleAnswers=i),null!==r&&(o.quotedMessageId=r),this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendPoll"),o)).data}async sendButtons(e,a,t,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,footer:t,buttons:s};this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendButtons"),i)).data}async sendTemplateButtons(e,a,t=null,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,templateButtons:s};null!==t&&(i.footer=t),this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendTemplateButtons"),i)).data}async sendListMessage(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const o={message:a,buttonText:t,title:s,footer:i,sections:r};this.addChadIdParam(o,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendListMessage"),o)).data}async sendLocation(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,a),c.validateString("nameLocation",t),c.validateString("address",s),c.validateNumber("latitude",i),c.validateNumber("longitude",r);const o={nameLocation:t,address:s,latitude:i,longitude:r};this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLocation"),o)).data}async sendContact(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateObject("contact",t);const s={contact:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendContact"),s)).data}async sendLink(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateString("urlLink",t);const s={urlLink:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLink"),s)).data}async readChat(e,a,t=null){c.validateChatIdPhoneNumber(e,a);const s={idMessage:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"readChat"),s)).data}async showMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"showMessagesQueue"))).data.map((e=>new l(e)))}async clearMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"clearMessagesQueue"))).data}async lastIncomingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastIncomingMessages"))).data.map((e=>new h(e)))}async lastOutgoingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastOutgoingMessages"))).data.map((e=>new h(e)))}async getChatHistory(e){c.validateChatIdPhoneNumber(e,void 0);const a={chatId:e};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getChatHistory"),a)).data}async getMessage(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("idMessage",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getMessage"),t)).data}async forwardMessages(e,a,t){c.validateString("chatId",e),c.validateString("chatIdFrom",a),c.validateArray("messages",t);const s={chatId:e,chatIdFrom:a,messages:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"ForwardMessages"),s)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.chatId=`${a}@c.us`)}}class h{constructor(e){this.chatId=e.chatId,this.idMessage=e.idMessage,this.statusMessage=e.statusMessage,this.textMessage=e.textMessage,this.timestamp=e.timestamp,this.typeMessage=e.typeMessage}}class l{constructor(e){this.chatId=e.chatId,this.fileName=e.fileName,this.typeMessage=e.typeMessage}}class u{constructor(e){this._restAPI=e}async sendFileByUrl(e,a,t,s,i=""){c.validateChatIdPhoneNumber(e,a),c.validateString("urlFile",t),c.validateString("filename",s);const r={urlFile:t,fileName:s,caption:i};this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendFileByUrl"),r)).data}async uploadFile(e){c.validateString("filePath",e);const a=o.default.readFileSync(e);return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"uploadFile"),data:a,headers:{"Content-Type":d.default.getType(e)}})).data}async sendFileByUpload(e){return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"sendFileByUpload"),data:e,headers:e.getHeaders()})).data}async downloadFile(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"downloadFile"),t)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class p{constructor(e){this._restAPI=e}async qr(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"qr"))).data}async logout(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"logout"))).data}async reboot(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"reboot"))).data}async getStateInstance(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getStateInstance"))).data}async getDeviceInfo(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getDeviceInfo"))).data}async checkWhatsapp(e){c.validateInteger("phoneNumber",e);const a={phoneNumber:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"checkWhatsapp"),a)).data}async getAvatar(e,a){c.validateChatIdPhoneNumber(e,a);const t={};this.addChadIdParam(t,e),this.addPhoneParam(t,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getAvatar"),t)).data}async archiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"archiveChat"),a)).data}async unarchiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"unarchiveChat"),a)).data}async getContactInfo(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getContactInfo"),a)).data}async getContacts(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getContacts"))).data}async getChats(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getChats"))).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class m{constructor(e){this._restAPI=e}async getSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getSettings"))).data}async setSettings(e){c.validateObject("settings",e);const a=e;return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setSettings"),a)).data}async getWaSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getWaSettings"))).data}}class I{constructor(e){this._restAPI=e}async createGroup(e,a){c.validateString("groupName",e),c.validateArray("chatIds",a);const t={groupName:e,chatIds:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"createGroup"),t)).data}async addGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"addGroupParticipant"),s)).data}async getGroupData(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getGroupData"),a)).data}async removeGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeGroupParticipant"),s)).data}async updateGroupName(e,a){c.validateString("groupId",e),c.validateString("groupName",a);const t={groupId:e,groupName:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"updateGroupName"),t)).data}async setGroupAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setGroupAdmin"),s)).data}async removeAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),s)).data}async leaveGroup(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),a)).data}async setGroupPicture(e,a){c.validateString("filePath",a);const t=o.default.createReadStream(a),s=[];for await(const e of t)s.push(e);const i=new Blob(s,{type:"image/jpeg"}),r=new FormData;r.append("groupId",e),r.append("file",i,"group_avatar.jpeg");return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"setGroupPicture"),data:r,headers:{"Content-Type":"multipart/form-data"}})).data}}class v{initJobs(e=[]){this.jobs=e}reschedule(){this.jobs.forEach((e=>{e.needInterrupt=!1,clearInterval(e.timerId),e.timerId=setInterval(e.run,1e3*e.intervalSec)}))}unschedule(){this.jobs.forEach((e=>{e.needInterrupt=!0,clearInterval(e.timerId)}))}}class M{timerId;intervalSec;needInterrupt=!1;constructor(e){this.webhookServiceApi=e,this.intervalSec=Number.parseInt("1")}run=async()=>{clearInterval(this.timerId);try{let e;for(;e=await this.webhookServiceApi.receiveNotification();){let a=e.body;a.typeWebhook===this.webhookServiceApi.noteTypes.incomingMessageReceived?"imageMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageImage,a):"videoMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageVideo,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"audioMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageAudio,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"textMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageText,a):"extendedTextMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageTextURL,a):"contactMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageContact,a):"locationMessage"==a.messageData.typeMessage&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageLocation,a):a.typeWebhook===this.webhookServiceApi.noteTypes.stateInstanceChanged?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingAccountStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.outgoingMessageStatus?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingOutboundMessageStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.deviceInfo&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingDeviceStatus,a),await this.webhookServiceApi.deleteNotification(e.receiptId)}}catch(e){console.error(e.toString())}this.needInterrupt||(this.timerId=setInterval(this.run,1e3*this.intervalSec))};callCallback(e,a){const t=this.webhookServiceApi._callbacks.get(e);t&&t.call(this,a)}}class b{constructor(e){this._restAPI=e,this._jobScheduler=new v,this.noteTypes={incomingMessageReceived:"incomingMessageReceived",outgoingMessageStatus:"outgoingMessageStatus",stateInstanceChanged:"stateInstanceChanged",deviceInfo:"deviceInfo"},this.callbackTypes={onReceivingMessageText:"onReceivingMessageText",onReceivingMessageImage:"onReceivingMessageImage",onReceivingMessageVideo:"onReceivingMessageVideo",onReceivingMessageDocument:"onReceivingMessageDocument",onReceivingMessageAudio:"onReceivingMessageAudio",onReceivingOutboundMessageStatus:"onReceivingOutboundMessageStatus",onReceivingAccountStatus:"onReceivingAccountStatus",onReceivingDeviceStatus:"onReceivingDeviceStatus",onReceivingMessageTextURL:"onReceivingMessageTextURL",onReceivingMessageContact:"onReceivingMessageContact",onReceivingMessageLocation:"onReceivingMessageLocation"},this._callbacks=new Map}async receiveNotification(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"receiveNotification"))).data}async deleteNotification(e){c.validateInteger("receiptId",e);return(await n.default.delete(`${c.generateMethodURL(this._restAPI.params,"deleteNotification")}/${e}`)).data}async startReceivingNotifications(){this._jobScheduler.initJobs([new M(this)]),this._jobScheduler.reschedule()}async stopReceivingNotifications(){this._jobScheduler.unschedule()}onReceivingMessageText(e){this._callbacks.set(this.callbackTypes.onReceivingMessageText,e)}onReceivingMessageImage(e){this._callbacks.set(this.callbackTypes.onReceivingMessageImage,e)}onReceivingMessageVideo(e){this._callbacks.set(this.callbackTypes.onReceivingMessageVideo,e)}onReceivingMessageDocument(e){this._callbacks.set(this.callbackTypes.onReceivingMessageDocument,e)}onReceivingMessageAudio(e){this._callbacks.set(this.callbackTypes.onReceivingMessageAudio,e)}onReceivingOutboundMessageStatus(e){this._callbacks.set(this.callbackTypes.onReceivingOutboundMessageStatus,e)}onReceivingAccountStatus(e){this._callbacks.set(this.callbackTypes.onReceivingAccountStatus,e)}onReceivingDeviceStatus(e){this._callbacks.set(this.callbackTypes.onReceivingDeviceStatus,e)}onReceivingMessageTextURL(e){this._callbacks.set(this.callbackTypes.onReceivingMessageTextURL,e)}onReceivingMessageContact(e){this._callbacks.set(this.callbackTypes.onReceivingMessageContact,e)}onReceivingMessageLocation(e){this._callbacks.set(this.callbackTypes.onReceivingMessageLocation,e)}}class y{constructor(e){this.params={host:"",media:"",idInstance:"",apiTokenInstance:"",credentialsPath:null},Object.assign(this.params,e),e.credentialsPath&&r.readFileSync(e.credentialsPath).toString("utf8").split("\n").map((e=>e.split(" ").join(""))).forEach((e=>{e.startsWith("API_TOKEN_INSTANCE=")?this.params.apiTokenInstance=e.replace("API_TOKEN_INSTANCE=","").trim():e.startsWith("ID_INSTANCE=")&&(this.params.idInstance=e.replace("ID_INSTANCE=","").trim())})),this.message=new g(this),this.file=new u(this),this.instance=new p(this),this.settings=new m(this),this.group=new I(this),this.webhookService=new b(this)}}var P="https://api.green-api.com",f="https://media.green-api.com";class R{constructor(e,a){this._app=e,this._webhookRoutePath=a,this._callbacks=new Map}init(){this._app.post(this._webhookRoutePath,(async(e,a,t)=>{try{console.log(`Received webhook ${e.body.typeWebhook}`);let t=null;t=e.body.messageData&&e.body.messageData.typeMessage?`${e.body.typeWebhook}_${e.body.messageData.typeMessage}`:e.body.typeWebhook;const s=this._callbacks.get(t);return s&&s.call(this,e.body),a.send()}catch(e){t(e)}}))}onStateInstance(e){this._callbacks.set("stateInstanceChanged",e)}onOutgoingMessageStatus(e){this._callbacks.set("outgoingMessageStatus",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.status)}))}onIncomingMessageText(e){this._callbacks.set("incomingMessageReceived_textMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.textMessageData.textMessage)}))}onIncomingMessageFile(e){this._callbacks.set("incomingMessageReceived_imageMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.downloadUrl)}))}onIncomingMessageLocation(e){this._callbacks.set("incomingMessageReceived_locationMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.locationMessageData.latitude,a.messageData.locationMessageData.longitude,a.messageData.locationMessageData.jpegThumbnail)}))}onIncomingMessageContact(e){this._callbacks.set("incomingMessageReceived_contactMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.contactMessageData.displayName,a.messageData.contactMessageData.vcard)}))}onIncomingMessageExtendedText(e){this._callbacks.set("incomingMessageReceived_extendedTextMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.extendedTextMessageData)}))}onDeviceInfo(e){this._callbacks.set("deviceInfo",e)}}return{restAPI:(e={})=>(function(e={}){e.host?c.validateString("host",e.host):e.host=P,e.media?c.validateString("media",e.media):e.media=f,e.credentialsPath?c.validatePath("credentialsPath",e.credentialsPath):(c.validateString("idInstance",e.idInstance),c.validateString("apiTokenInstance",e.apiTokenInstance))}(e),new y(e)),webhookAPI:(e,a)=>{const t=new R(e,a);return t.init(),t}}})); diff --git a/package-lock.json b/package-lock.json index 2fa65f6..8208084 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@green-api/whatsapp-api-client", - "version": "0.3.38", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@green-api/whatsapp-api-client", - "version": "0.3.38", + "version": "1.0.0", "license": "MIT", "dependencies": { "axios": "1.5.0", diff --git a/package.json b/package.json index 5fa7b9b..32ef02b 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,6 @@ }, "author": "Green API team", "files": [ - "lib", "bundle.js", "whatsapp-api-client.min.js" ], @@ -47,4 +46,4 @@ "mime": "^3.0.0", "rollup": "^2.79.1" } -} +} \ No newline at end of file diff --git a/src/utils/GroupAPI.js b/src/utils/GroupAPI.js index 42674b1..c3013ac 100644 --- a/src/utils/GroupAPI.js +++ b/src/utils/GroupAPI.js @@ -1,6 +1,8 @@ 'use strict' import axios from 'axios'; import CommonUtils from './CommonUtils.js' +import fs from "fs"; +import mime from "mime"; class GroupAPI { @@ -10,19 +12,16 @@ class GroupAPI { /** * * @param {String} groupName - * @param {Array} chatIds - * @param {Array} phones + * @param {Array} chatIds */ - async createGroup(groupName, chatIds, phones) { + async createGroup(groupName, chatIds) { CommonUtils.validateString('groupName', groupName); CommonUtils.validateArray('chatIds', chatIds); - CommonUtils.validateArray('phones', phones); const method = 'createGroup'; const postData = { 'groupName': groupName, - 'chatIds': chatIds, - 'phones': phones, + 'chatIds': chatIds } const response = await axios.post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); return response.data; @@ -154,6 +153,36 @@ class GroupAPI { return response.data; } + /** + * @param {String} filePath + * @param {String} groupId + */ + async setGroupPicture(groupId, filePath) { + CommonUtils.validateString("filePath", filePath) + + const method = "setGroupPicture"; + + const fileStream = fs.createReadStream(filePath) + const fileData = []; + + for await (const data of fileStream) { + fileData.push(data); + } + + const blob = new Blob(fileData, { type: 'image/jpeg' }); + + const formData = new FormData() + formData.append('groupId', groupId) + formData.append('file', blob, "group_avatar.jpeg") + + const response = await axios({ + method: "post", + url: CommonUtils.generateMethodURL(this._restAPI.params, method), + data: formData, + headers: {"Content-Type": "multipart/form-data"} + }) + return response.data; + } } export default GroupAPI; \ No newline at end of file From 120461023c487def94c7bf9d9d28b8d1b6af5af4 Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Thu, 29 Feb 2024 14:07:59 -0300 Subject: [PATCH 3/7] fix package json and requests --- package.json | 1 + src/utils/GroupAPI.js | 5 +++-- src/utils/MessageAPI.js | 17 ++++++++++------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 32ef02b..d388f71 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ }, "author": "Green API team", "files": [ + "lib", "bundle.js", "whatsapp-api-client.min.js" ], diff --git a/src/utils/GroupAPI.js b/src/utils/GroupAPI.js index c3013ac..bc395ce 100644 --- a/src/utils/GroupAPI.js +++ b/src/utils/GroupAPI.js @@ -159,6 +159,7 @@ class GroupAPI { */ async setGroupPicture(groupId, filePath) { CommonUtils.validateString("filePath", filePath) + CommonUtils.validateString('groupId', groupId); const method = "setGroupPicture"; @@ -173,13 +174,13 @@ class GroupAPI { const formData = new FormData() formData.append('groupId', groupId) - formData.append('file', blob, "group_avatar.jpeg") + formData.append('file', blob, "group_avatar.jpg") const response = await axios({ method: "post", url: CommonUtils.generateMethodURL(this._restAPI.params, method), data: formData, - headers: {"Content-Type": "multipart/form-data"} + headers: {"Content-Type": "image/jpeg"} }) return response.data; } diff --git a/src/utils/MessageAPI.js b/src/utils/MessageAPI.js index 066f097..aff1feb 100644 --- a/src/utils/MessageAPI.js +++ b/src/utils/MessageAPI.js @@ -15,12 +15,10 @@ class MessageAPI { * @param {Number} phoneNumber - receiver phone number using international format without + sign. * Mandatory if chatId is empty * @param {String} message - text message + * @param {boolean} linkPreview - allow preview + * @param {String} quotedMessageId - id of message */ - async sendMessage(chatId, phoneNumber, message) { - return this.sendMessageExtended(chatId, phoneNumber, message, "", true) - } - - async sendMessageExtended(chatId, phoneNumber, message, quotedMessageId, linkPreview) { + async sendMessage(chatId, phoneNumber, message, quotedMessageId = null, linkPreview = null) { CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); CommonUtils.validateString('message', message); @@ -28,8 +26,13 @@ class MessageAPI { const postData = { 'message': message, - 'quotedMessageId': quotedMessageId, - 'linkPreview': linkPreview + } + + if (quotedMessageId !== null) { + postData['quotedMessageId'] = quotedMessageId + } + if (linkPreview !== null) { + postData['linkPreview'] = linkPreview } this.addChadIdParam(postData, chatId) From e26a6f9c186deee1ee24474f15cfb46852275d5f Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Thu, 29 Feb 2024 14:48:56 -0300 Subject: [PATCH 4/7] rebuild --- lib/bundle.js | 22 +++++++++++++--------- lib/whatsapp-api-client.min.js | 2 +- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/lib/bundle.js b/lib/bundle.js index dabbd39..d57d57a 100644 --- a/lib/bundle.js +++ b/lib/bundle.js @@ -91,12 +91,10 @@ class MessageAPI { * @param {Number} phoneNumber - receiver phone number using international format without + sign. * Mandatory if chatId is empty * @param {String} message - text message + * @param {boolean} linkPreview - allow preview + * @param {String} quotedMessageId - id of message */ - async sendMessage(chatId, phoneNumber, message) { - return this.sendMessageExtended(chatId, phoneNumber, message, "", true) - } - - async sendMessageExtended(chatId, phoneNumber, message, quotedMessageId, linkPreview) { + async sendMessage(chatId, phoneNumber, message, quotedMessageId = null, linkPreview = null) { CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); CommonUtils.validateString('message', message); @@ -104,10 +102,15 @@ class MessageAPI { const postData = { 'message': message, - 'quotedMessageId': quotedMessageId, - 'linkPreview': linkPreview }; + if (quotedMessageId !== null) { + postData['quotedMessageId'] = quotedMessageId; + } + if (linkPreview !== null) { + postData['linkPreview'] = linkPreview; + } + this.addChadIdParam(postData, chatId); this.addPhoneParam(postData, phoneNumber); @@ -926,6 +929,7 @@ class GroupAPI { */ async setGroupPicture(groupId, filePath) { CommonUtils.validateString("filePath", filePath); + CommonUtils.validateString('groupId', groupId); const method = "setGroupPicture"; @@ -940,13 +944,13 @@ class GroupAPI { const formData = new FormData(); formData.append('groupId', groupId); - formData.append('file', blob, "group_avatar.jpeg"); + formData.append('file', blob, "group_avatar.jpg"); const response = await axios__default["default"]({ method: "post", url: CommonUtils.generateMethodURL(this._restAPI.params, method), data: formData, - headers: {"Content-Type": "multipart/form-data"} + headers: {"Content-Type": "image/jpeg"} }); return response.data; } diff --git a/lib/whatsapp-api-client.min.js b/lib/whatsapp-api-client.min.js index 02db9cc..4618fe4 100644 --- a/lib/whatsapp-api-client.min.js +++ b/lib/whatsapp-api-client.min.js @@ -1 +1 @@ -!function(e,a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a(require("axios"),require("fs"),require("mime")):"function"==typeof define&&define.amd?define(["axios","fs","mime"],a):(e="undefined"!=typeof globalThis?globalThis:e||self).whatsAppClient=a(e.axios,e.fs,e.mime)}(this,(function(e,a,t){"use strict";function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var a=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}})),a.default=e,Object.freeze(a)}var n=s(e),r=i(a),o=s(a),d=s(t);class c{static validateString(e,a){if(!a||"[object String]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be a String!`)}static validateInteger(e,a){if(!Number.isInteger(a))throw new Error(`${e} must be an integer!`)}static validateNumber(e,a){if(!a||!Number(a))throw new Error(`${e} must be a number!`)}static validateObject(e,a){if(!a||"[object Object]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be an Object!`)}static generateMethodURL(e,a){return"sendFileByUpload"===a||"uploadFile"===a?`${e.media}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`:`${e.host}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`}static validateChatIdPhoneNumber(e,a){e||c.validateInteger("phoneNumber",a),a||c.validateString("chatId",e)}static validateArray(e,a){if(!a||!Array.isArray(a))throw new Error(`${e} must be an Array!`)}static validatePath(e,a){if(!a||!r.existsSync(a))throw new Error(`${e} not found!`)}}class g{constructor(e){this._restAPI=e}async sendMessage(e,a,t){return this.sendMessageExtended(e,a,t,"",!0)}async sendMessageExtended(e,a,t,s,i){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t);const r={message:t,quotedMessageId:s,linkPreview:i};this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendMessage"),r)).data}async sendPoll(e,a,t,s,i=null,r=null){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t),c.validateArray("options",s);const o={message:t,options:s};null!==i&&(o.multipleAnswers=i),null!==r&&(o.quotedMessageId=r),this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendPoll"),o)).data}async sendButtons(e,a,t,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,footer:t,buttons:s};this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendButtons"),i)).data}async sendTemplateButtons(e,a,t=null,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,templateButtons:s};null!==t&&(i.footer=t),this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendTemplateButtons"),i)).data}async sendListMessage(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const o={message:a,buttonText:t,title:s,footer:i,sections:r};this.addChadIdParam(o,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendListMessage"),o)).data}async sendLocation(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,a),c.validateString("nameLocation",t),c.validateString("address",s),c.validateNumber("latitude",i),c.validateNumber("longitude",r);const o={nameLocation:t,address:s,latitude:i,longitude:r};this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLocation"),o)).data}async sendContact(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateObject("contact",t);const s={contact:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendContact"),s)).data}async sendLink(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateString("urlLink",t);const s={urlLink:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLink"),s)).data}async readChat(e,a,t=null){c.validateChatIdPhoneNumber(e,a);const s={idMessage:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"readChat"),s)).data}async showMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"showMessagesQueue"))).data.map((e=>new l(e)))}async clearMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"clearMessagesQueue"))).data}async lastIncomingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastIncomingMessages"))).data.map((e=>new h(e)))}async lastOutgoingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastOutgoingMessages"))).data.map((e=>new h(e)))}async getChatHistory(e){c.validateChatIdPhoneNumber(e,void 0);const a={chatId:e};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getChatHistory"),a)).data}async getMessage(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("idMessage",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getMessage"),t)).data}async forwardMessages(e,a,t){c.validateString("chatId",e),c.validateString("chatIdFrom",a),c.validateArray("messages",t);const s={chatId:e,chatIdFrom:a,messages:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"ForwardMessages"),s)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.chatId=`${a}@c.us`)}}class h{constructor(e){this.chatId=e.chatId,this.idMessage=e.idMessage,this.statusMessage=e.statusMessage,this.textMessage=e.textMessage,this.timestamp=e.timestamp,this.typeMessage=e.typeMessage}}class l{constructor(e){this.chatId=e.chatId,this.fileName=e.fileName,this.typeMessage=e.typeMessage}}class u{constructor(e){this._restAPI=e}async sendFileByUrl(e,a,t,s,i=""){c.validateChatIdPhoneNumber(e,a),c.validateString("urlFile",t),c.validateString("filename",s);const r={urlFile:t,fileName:s,caption:i};this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendFileByUrl"),r)).data}async uploadFile(e){c.validateString("filePath",e);const a=o.default.readFileSync(e);return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"uploadFile"),data:a,headers:{"Content-Type":d.default.getType(e)}})).data}async sendFileByUpload(e){return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"sendFileByUpload"),data:e,headers:e.getHeaders()})).data}async downloadFile(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"downloadFile"),t)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class p{constructor(e){this._restAPI=e}async qr(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"qr"))).data}async logout(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"logout"))).data}async reboot(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"reboot"))).data}async getStateInstance(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getStateInstance"))).data}async getDeviceInfo(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getDeviceInfo"))).data}async checkWhatsapp(e){c.validateInteger("phoneNumber",e);const a={phoneNumber:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"checkWhatsapp"),a)).data}async getAvatar(e,a){c.validateChatIdPhoneNumber(e,a);const t={};this.addChadIdParam(t,e),this.addPhoneParam(t,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getAvatar"),t)).data}async archiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"archiveChat"),a)).data}async unarchiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"unarchiveChat"),a)).data}async getContactInfo(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getContactInfo"),a)).data}async getContacts(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getContacts"))).data}async getChats(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getChats"))).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class m{constructor(e){this._restAPI=e}async getSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getSettings"))).data}async setSettings(e){c.validateObject("settings",e);const a=e;return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setSettings"),a)).data}async getWaSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getWaSettings"))).data}}class I{constructor(e){this._restAPI=e}async createGroup(e,a){c.validateString("groupName",e),c.validateArray("chatIds",a);const t={groupName:e,chatIds:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"createGroup"),t)).data}async addGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"addGroupParticipant"),s)).data}async getGroupData(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getGroupData"),a)).data}async removeGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeGroupParticipant"),s)).data}async updateGroupName(e,a){c.validateString("groupId",e),c.validateString("groupName",a);const t={groupId:e,groupName:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"updateGroupName"),t)).data}async setGroupAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setGroupAdmin"),s)).data}async removeAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),s)).data}async leaveGroup(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),a)).data}async setGroupPicture(e,a){c.validateString("filePath",a);const t=o.default.createReadStream(a),s=[];for await(const e of t)s.push(e);const i=new Blob(s,{type:"image/jpeg"}),r=new FormData;r.append("groupId",e),r.append("file",i,"group_avatar.jpeg");return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"setGroupPicture"),data:r,headers:{"Content-Type":"multipart/form-data"}})).data}}class v{initJobs(e=[]){this.jobs=e}reschedule(){this.jobs.forEach((e=>{e.needInterrupt=!1,clearInterval(e.timerId),e.timerId=setInterval(e.run,1e3*e.intervalSec)}))}unschedule(){this.jobs.forEach((e=>{e.needInterrupt=!0,clearInterval(e.timerId)}))}}class M{timerId;intervalSec;needInterrupt=!1;constructor(e){this.webhookServiceApi=e,this.intervalSec=Number.parseInt("1")}run=async()=>{clearInterval(this.timerId);try{let e;for(;e=await this.webhookServiceApi.receiveNotification();){let a=e.body;a.typeWebhook===this.webhookServiceApi.noteTypes.incomingMessageReceived?"imageMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageImage,a):"videoMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageVideo,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"audioMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageAudio,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"textMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageText,a):"extendedTextMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageTextURL,a):"contactMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageContact,a):"locationMessage"==a.messageData.typeMessage&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageLocation,a):a.typeWebhook===this.webhookServiceApi.noteTypes.stateInstanceChanged?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingAccountStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.outgoingMessageStatus?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingOutboundMessageStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.deviceInfo&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingDeviceStatus,a),await this.webhookServiceApi.deleteNotification(e.receiptId)}}catch(e){console.error(e.toString())}this.needInterrupt||(this.timerId=setInterval(this.run,1e3*this.intervalSec))};callCallback(e,a){const t=this.webhookServiceApi._callbacks.get(e);t&&t.call(this,a)}}class b{constructor(e){this._restAPI=e,this._jobScheduler=new v,this.noteTypes={incomingMessageReceived:"incomingMessageReceived",outgoingMessageStatus:"outgoingMessageStatus",stateInstanceChanged:"stateInstanceChanged",deviceInfo:"deviceInfo"},this.callbackTypes={onReceivingMessageText:"onReceivingMessageText",onReceivingMessageImage:"onReceivingMessageImage",onReceivingMessageVideo:"onReceivingMessageVideo",onReceivingMessageDocument:"onReceivingMessageDocument",onReceivingMessageAudio:"onReceivingMessageAudio",onReceivingOutboundMessageStatus:"onReceivingOutboundMessageStatus",onReceivingAccountStatus:"onReceivingAccountStatus",onReceivingDeviceStatus:"onReceivingDeviceStatus",onReceivingMessageTextURL:"onReceivingMessageTextURL",onReceivingMessageContact:"onReceivingMessageContact",onReceivingMessageLocation:"onReceivingMessageLocation"},this._callbacks=new Map}async receiveNotification(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"receiveNotification"))).data}async deleteNotification(e){c.validateInteger("receiptId",e);return(await n.default.delete(`${c.generateMethodURL(this._restAPI.params,"deleteNotification")}/${e}`)).data}async startReceivingNotifications(){this._jobScheduler.initJobs([new M(this)]),this._jobScheduler.reschedule()}async stopReceivingNotifications(){this._jobScheduler.unschedule()}onReceivingMessageText(e){this._callbacks.set(this.callbackTypes.onReceivingMessageText,e)}onReceivingMessageImage(e){this._callbacks.set(this.callbackTypes.onReceivingMessageImage,e)}onReceivingMessageVideo(e){this._callbacks.set(this.callbackTypes.onReceivingMessageVideo,e)}onReceivingMessageDocument(e){this._callbacks.set(this.callbackTypes.onReceivingMessageDocument,e)}onReceivingMessageAudio(e){this._callbacks.set(this.callbackTypes.onReceivingMessageAudio,e)}onReceivingOutboundMessageStatus(e){this._callbacks.set(this.callbackTypes.onReceivingOutboundMessageStatus,e)}onReceivingAccountStatus(e){this._callbacks.set(this.callbackTypes.onReceivingAccountStatus,e)}onReceivingDeviceStatus(e){this._callbacks.set(this.callbackTypes.onReceivingDeviceStatus,e)}onReceivingMessageTextURL(e){this._callbacks.set(this.callbackTypes.onReceivingMessageTextURL,e)}onReceivingMessageContact(e){this._callbacks.set(this.callbackTypes.onReceivingMessageContact,e)}onReceivingMessageLocation(e){this._callbacks.set(this.callbackTypes.onReceivingMessageLocation,e)}}class y{constructor(e){this.params={host:"",media:"",idInstance:"",apiTokenInstance:"",credentialsPath:null},Object.assign(this.params,e),e.credentialsPath&&r.readFileSync(e.credentialsPath).toString("utf8").split("\n").map((e=>e.split(" ").join(""))).forEach((e=>{e.startsWith("API_TOKEN_INSTANCE=")?this.params.apiTokenInstance=e.replace("API_TOKEN_INSTANCE=","").trim():e.startsWith("ID_INSTANCE=")&&(this.params.idInstance=e.replace("ID_INSTANCE=","").trim())})),this.message=new g(this),this.file=new u(this),this.instance=new p(this),this.settings=new m(this),this.group=new I(this),this.webhookService=new b(this)}}var P="https://api.green-api.com",f="https://media.green-api.com";class R{constructor(e,a){this._app=e,this._webhookRoutePath=a,this._callbacks=new Map}init(){this._app.post(this._webhookRoutePath,(async(e,a,t)=>{try{console.log(`Received webhook ${e.body.typeWebhook}`);let t=null;t=e.body.messageData&&e.body.messageData.typeMessage?`${e.body.typeWebhook}_${e.body.messageData.typeMessage}`:e.body.typeWebhook;const s=this._callbacks.get(t);return s&&s.call(this,e.body),a.send()}catch(e){t(e)}}))}onStateInstance(e){this._callbacks.set("stateInstanceChanged",e)}onOutgoingMessageStatus(e){this._callbacks.set("outgoingMessageStatus",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.status)}))}onIncomingMessageText(e){this._callbacks.set("incomingMessageReceived_textMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.textMessageData.textMessage)}))}onIncomingMessageFile(e){this._callbacks.set("incomingMessageReceived_imageMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.downloadUrl)}))}onIncomingMessageLocation(e){this._callbacks.set("incomingMessageReceived_locationMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.locationMessageData.latitude,a.messageData.locationMessageData.longitude,a.messageData.locationMessageData.jpegThumbnail)}))}onIncomingMessageContact(e){this._callbacks.set("incomingMessageReceived_contactMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.contactMessageData.displayName,a.messageData.contactMessageData.vcard)}))}onIncomingMessageExtendedText(e){this._callbacks.set("incomingMessageReceived_extendedTextMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.extendedTextMessageData)}))}onDeviceInfo(e){this._callbacks.set("deviceInfo",e)}}return{restAPI:(e={})=>(function(e={}){e.host?c.validateString("host",e.host):e.host=P,e.media?c.validateString("media",e.media):e.media=f,e.credentialsPath?c.validatePath("credentialsPath",e.credentialsPath):(c.validateString("idInstance",e.idInstance),c.validateString("apiTokenInstance",e.apiTokenInstance))}(e),new y(e)),webhookAPI:(e,a)=>{const t=new R(e,a);return t.init(),t}}})); +!function(e,a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a(require("axios"),require("fs"),require("mime")):"function"==typeof define&&define.amd?define(["axios","fs","mime"],a):(e="undefined"!=typeof globalThis?globalThis:e||self).whatsAppClient=a(e.axios,e.fs,e.mime)}(this,(function(e,a,t){"use strict";function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var a=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}})),a.default=e,Object.freeze(a)}var n=s(e),r=i(a),o=s(a),d=s(t);class c{static validateString(e,a){if(!a||"[object String]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be a String!`)}static validateInteger(e,a){if(!Number.isInteger(a))throw new Error(`${e} must be an integer!`)}static validateNumber(e,a){if(!a||!Number(a))throw new Error(`${e} must be a number!`)}static validateObject(e,a){if(!a||"[object Object]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be an Object!`)}static generateMethodURL(e,a){return"sendFileByUpload"===a||"uploadFile"===a?`${e.media}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`:`${e.host}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`}static validateChatIdPhoneNumber(e,a){e||c.validateInteger("phoneNumber",a),a||c.validateString("chatId",e)}static validateArray(e,a){if(!a||!Array.isArray(a))throw new Error(`${e} must be an Array!`)}static validatePath(e,a){if(!a||!r.existsSync(a))throw new Error(`${e} not found!`)}}class g{constructor(e){this._restAPI=e}async sendMessage(e,a,t,s=null,i=null){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t);const r={message:t};null!==s&&(r.quotedMessageId=s),null!==i&&(r.linkPreview=i),this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendMessage"),r)).data}async sendPoll(e,a,t,s,i=null,r=null){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t),c.validateArray("options",s);const o={message:t,options:s};null!==i&&(o.multipleAnswers=i),null!==r&&(o.quotedMessageId=r),this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendPoll"),o)).data}async sendButtons(e,a,t,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,footer:t,buttons:s};this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendButtons"),i)).data}async sendTemplateButtons(e,a,t=null,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,templateButtons:s};null!==t&&(i.footer=t),this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendTemplateButtons"),i)).data}async sendListMessage(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const o={message:a,buttonText:t,title:s,footer:i,sections:r};this.addChadIdParam(o,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendListMessage"),o)).data}async sendLocation(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,a),c.validateString("nameLocation",t),c.validateString("address",s),c.validateNumber("latitude",i),c.validateNumber("longitude",r);const o={nameLocation:t,address:s,latitude:i,longitude:r};this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLocation"),o)).data}async sendContact(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateObject("contact",t);const s={contact:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendContact"),s)).data}async sendLink(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateString("urlLink",t);const s={urlLink:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLink"),s)).data}async readChat(e,a,t=null){c.validateChatIdPhoneNumber(e,a);const s={idMessage:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"readChat"),s)).data}async showMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"showMessagesQueue"))).data.map((e=>new h(e)))}async clearMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"clearMessagesQueue"))).data}async lastIncomingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastIncomingMessages"))).data.map((e=>new l(e)))}async lastOutgoingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastOutgoingMessages"))).data.map((e=>new l(e)))}async getChatHistory(e){c.validateChatIdPhoneNumber(e,void 0);const a={chatId:e};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getChatHistory"),a)).data}async getMessage(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("idMessage",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getMessage"),t)).data}async forwardMessages(e,a,t){c.validateString("chatId",e),c.validateString("chatIdFrom",a),c.validateArray("messages",t);const s={chatId:e,chatIdFrom:a,messages:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"ForwardMessages"),s)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.chatId=`${a}@c.us`)}}class l{constructor(e){this.chatId=e.chatId,this.idMessage=e.idMessage,this.statusMessage=e.statusMessage,this.textMessage=e.textMessage,this.timestamp=e.timestamp,this.typeMessage=e.typeMessage}}class h{constructor(e){this.chatId=e.chatId,this.fileName=e.fileName,this.typeMessage=e.typeMessage}}class u{constructor(e){this._restAPI=e}async sendFileByUrl(e,a,t,s,i=""){c.validateChatIdPhoneNumber(e,a),c.validateString("urlFile",t),c.validateString("filename",s);const r={urlFile:t,fileName:s,caption:i};this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendFileByUrl"),r)).data}async uploadFile(e){c.validateString("filePath",e);const a=o.default.readFileSync(e);return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"uploadFile"),data:a,headers:{"Content-Type":d.default.getType(e)}})).data}async sendFileByUpload(e){return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"sendFileByUpload"),data:e,headers:e.getHeaders()})).data}async downloadFile(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"downloadFile"),t)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class p{constructor(e){this._restAPI=e}async qr(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"qr"))).data}async logout(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"logout"))).data}async reboot(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"reboot"))).data}async getStateInstance(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getStateInstance"))).data}async getDeviceInfo(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getDeviceInfo"))).data}async checkWhatsapp(e){c.validateInteger("phoneNumber",e);const a={phoneNumber:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"checkWhatsapp"),a)).data}async getAvatar(e,a){c.validateChatIdPhoneNumber(e,a);const t={};this.addChadIdParam(t,e),this.addPhoneParam(t,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getAvatar"),t)).data}async archiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"archiveChat"),a)).data}async unarchiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"unarchiveChat"),a)).data}async getContactInfo(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getContactInfo"),a)).data}async getContacts(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getContacts"))).data}async getChats(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getChats"))).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class m{constructor(e){this._restAPI=e}async getSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getSettings"))).data}async setSettings(e){c.validateObject("settings",e);const a=e;return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setSettings"),a)).data}async getWaSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getWaSettings"))).data}}class I{constructor(e){this._restAPI=e}async createGroup(e,a){c.validateString("groupName",e),c.validateArray("chatIds",a);const t={groupName:e,chatIds:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"createGroup"),t)).data}async addGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"addGroupParticipant"),s)).data}async getGroupData(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getGroupData"),a)).data}async removeGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeGroupParticipant"),s)).data}async updateGroupName(e,a){c.validateString("groupId",e),c.validateString("groupName",a);const t={groupId:e,groupName:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"updateGroupName"),t)).data}async setGroupAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setGroupAdmin"),s)).data}async removeAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),s)).data}async leaveGroup(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),a)).data}async setGroupPicture(e,a){c.validateString("filePath",a),c.validateString("groupId",e);const t=o.default.createReadStream(a),s=[];for await(const e of t)s.push(e);const i=new Blob(s,{type:"image/jpeg"}),r=new FormData;r.append("groupId",e),r.append("file",i,"group_avatar.jpg");return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"setGroupPicture"),data:r,headers:{"Content-Type":"image/jpeg"}})).data}}class v{initJobs(e=[]){this.jobs=e}reschedule(){this.jobs.forEach((e=>{e.needInterrupt=!1,clearInterval(e.timerId),e.timerId=setInterval(e.run,1e3*e.intervalSec)}))}unschedule(){this.jobs.forEach((e=>{e.needInterrupt=!0,clearInterval(e.timerId)}))}}class M{timerId;intervalSec;needInterrupt=!1;constructor(e){this.webhookServiceApi=e,this.intervalSec=Number.parseInt("1")}run=async()=>{clearInterval(this.timerId);try{let e;for(;e=await this.webhookServiceApi.receiveNotification();){let a=e.body;a.typeWebhook===this.webhookServiceApi.noteTypes.incomingMessageReceived?"imageMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageImage,a):"videoMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageVideo,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"audioMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageAudio,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"textMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageText,a):"extendedTextMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageTextURL,a):"contactMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageContact,a):"locationMessage"==a.messageData.typeMessage&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageLocation,a):a.typeWebhook===this.webhookServiceApi.noteTypes.stateInstanceChanged?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingAccountStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.outgoingMessageStatus?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingOutboundMessageStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.deviceInfo&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingDeviceStatus,a),await this.webhookServiceApi.deleteNotification(e.receiptId)}}catch(e){console.error(e.toString())}this.needInterrupt||(this.timerId=setInterval(this.run,1e3*this.intervalSec))};callCallback(e,a){const t=this.webhookServiceApi._callbacks.get(e);t&&t.call(this,a)}}class b{constructor(e){this._restAPI=e,this._jobScheduler=new v,this.noteTypes={incomingMessageReceived:"incomingMessageReceived",outgoingMessageStatus:"outgoingMessageStatus",stateInstanceChanged:"stateInstanceChanged",deviceInfo:"deviceInfo"},this.callbackTypes={onReceivingMessageText:"onReceivingMessageText",onReceivingMessageImage:"onReceivingMessageImage",onReceivingMessageVideo:"onReceivingMessageVideo",onReceivingMessageDocument:"onReceivingMessageDocument",onReceivingMessageAudio:"onReceivingMessageAudio",onReceivingOutboundMessageStatus:"onReceivingOutboundMessageStatus",onReceivingAccountStatus:"onReceivingAccountStatus",onReceivingDeviceStatus:"onReceivingDeviceStatus",onReceivingMessageTextURL:"onReceivingMessageTextURL",onReceivingMessageContact:"onReceivingMessageContact",onReceivingMessageLocation:"onReceivingMessageLocation"},this._callbacks=new Map}async receiveNotification(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"receiveNotification"))).data}async deleteNotification(e){c.validateInteger("receiptId",e);return(await n.default.delete(`${c.generateMethodURL(this._restAPI.params,"deleteNotification")}/${e}`)).data}async startReceivingNotifications(){this._jobScheduler.initJobs([new M(this)]),this._jobScheduler.reschedule()}async stopReceivingNotifications(){this._jobScheduler.unschedule()}onReceivingMessageText(e){this._callbacks.set(this.callbackTypes.onReceivingMessageText,e)}onReceivingMessageImage(e){this._callbacks.set(this.callbackTypes.onReceivingMessageImage,e)}onReceivingMessageVideo(e){this._callbacks.set(this.callbackTypes.onReceivingMessageVideo,e)}onReceivingMessageDocument(e){this._callbacks.set(this.callbackTypes.onReceivingMessageDocument,e)}onReceivingMessageAudio(e){this._callbacks.set(this.callbackTypes.onReceivingMessageAudio,e)}onReceivingOutboundMessageStatus(e){this._callbacks.set(this.callbackTypes.onReceivingOutboundMessageStatus,e)}onReceivingAccountStatus(e){this._callbacks.set(this.callbackTypes.onReceivingAccountStatus,e)}onReceivingDeviceStatus(e){this._callbacks.set(this.callbackTypes.onReceivingDeviceStatus,e)}onReceivingMessageTextURL(e){this._callbacks.set(this.callbackTypes.onReceivingMessageTextURL,e)}onReceivingMessageContact(e){this._callbacks.set(this.callbackTypes.onReceivingMessageContact,e)}onReceivingMessageLocation(e){this._callbacks.set(this.callbackTypes.onReceivingMessageLocation,e)}}class y{constructor(e){this.params={host:"",media:"",idInstance:"",apiTokenInstance:"",credentialsPath:null},Object.assign(this.params,e),e.credentialsPath&&r.readFileSync(e.credentialsPath).toString("utf8").split("\n").map((e=>e.split(" ").join(""))).forEach((e=>{e.startsWith("API_TOKEN_INSTANCE=")?this.params.apiTokenInstance=e.replace("API_TOKEN_INSTANCE=","").trim():e.startsWith("ID_INSTANCE=")&&(this.params.idInstance=e.replace("ID_INSTANCE=","").trim())})),this.message=new g(this),this.file=new u(this),this.instance=new p(this),this.settings=new m(this),this.group=new I(this),this.webhookService=new b(this)}}var P="https://api.green-api.com",f="https://media.green-api.com";class R{constructor(e,a){this._app=e,this._webhookRoutePath=a,this._callbacks=new Map}init(){this._app.post(this._webhookRoutePath,(async(e,a,t)=>{try{console.log(`Received webhook ${e.body.typeWebhook}`);let t=null;t=e.body.messageData&&e.body.messageData.typeMessage?`${e.body.typeWebhook}_${e.body.messageData.typeMessage}`:e.body.typeWebhook;const s=this._callbacks.get(t);return s&&s.call(this,e.body),a.send()}catch(e){t(e)}}))}onStateInstance(e){this._callbacks.set("stateInstanceChanged",e)}onOutgoingMessageStatus(e){this._callbacks.set("outgoingMessageStatus",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.status)}))}onIncomingMessageText(e){this._callbacks.set("incomingMessageReceived_textMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.textMessageData.textMessage)}))}onIncomingMessageFile(e){this._callbacks.set("incomingMessageReceived_imageMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.downloadUrl)}))}onIncomingMessageLocation(e){this._callbacks.set("incomingMessageReceived_locationMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.locationMessageData.latitude,a.messageData.locationMessageData.longitude,a.messageData.locationMessageData.jpegThumbnail)}))}onIncomingMessageContact(e){this._callbacks.set("incomingMessageReceived_contactMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.contactMessageData.displayName,a.messageData.contactMessageData.vcard)}))}onIncomingMessageExtendedText(e){this._callbacks.set("incomingMessageReceived_extendedTextMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.extendedTextMessageData)}))}onDeviceInfo(e){this._callbacks.set("deviceInfo",e)}}return{restAPI:(e={})=>(function(e={}){e.host?c.validateString("host",e.host):e.host=P,e.media?c.validateString("media",e.media):e.media=f,e.credentialsPath?c.validatePath("credentialsPath",e.credentialsPath):(c.validateString("idInstance",e.idInstance),c.validateString("apiTokenInstance",e.apiTokenInstance))}(e),new y(e)),webhookAPI:(e,a)=>{const t=new R(e,a);return t.init(),t}}})); From 6f90e3623dc95be0f5ff8175658e32c98c8ea279 Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Thu, 29 Feb 2024 19:26:46 -0300 Subject: [PATCH 5/7] update getChatHistory --- src/utils/MessageAPI.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/utils/MessageAPI.js b/src/utils/MessageAPI.js index aff1feb..0efe688 100644 --- a/src/utils/MessageAPI.js +++ b/src/utils/MessageAPI.js @@ -312,7 +312,7 @@ class MessageAPI { /** * Returns history of chat */ - async getChatHistory(chatId) { + async getChatHistory(chatId, count) { CommonUtils.validateChatIdPhoneNumber(chatId, undefined); const method = 'getChatHistory'; @@ -321,6 +321,10 @@ class MessageAPI { 'chatId': chatId, } + if (count && count > 0) { + postData.count = count; + } + this.addChadIdParam(postData, chatId) const response = await axios.post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); From f32c3460055c4e31b27d73a1493d23831dfb3777 Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Mon, 4 Mar 2024 13:49:31 -0300 Subject: [PATCH 6/7] update getChatHistory fix --- .gitignore | 1 + package.json | 2 +- src/utils/MessageAPI.js | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 9a3c89c..ac9045e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .vscode/ node_modules +lib .* !/.gitignore diff --git a/package.json b/package.json index d388f71..5fa7b9b 100644 --- a/package.json +++ b/package.json @@ -47,4 +47,4 @@ "mime": "^3.0.0", "rollup": "^2.79.1" } -} \ No newline at end of file +} diff --git a/src/utils/MessageAPI.js b/src/utils/MessageAPI.js index 0efe688..f3d6136 100644 --- a/src/utils/MessageAPI.js +++ b/src/utils/MessageAPI.js @@ -312,7 +312,7 @@ class MessageAPI { /** * Returns history of chat */ - async getChatHistory(chatId, count) { + async getChatHistory(chatId, count = null) { CommonUtils.validateChatIdPhoneNumber(chatId, undefined); const method = 'getChatHistory'; @@ -321,8 +321,8 @@ class MessageAPI { 'chatId': chatId, } - if (count && count > 0) { - postData.count = count; + if (count !== null && count > 0) { + postData['count'] = count; } this.addChadIdParam(postData, chatId) From 85036a48b3bc4e2e667580dab110c9517da2a252 Mon Sep 17 00:00:00 2001 From: dany47788 <65661948+dany47788@users.noreply.github.com> Date: Wed, 6 Mar 2024 17:31:49 -0300 Subject: [PATCH 7/7] delete lib --- lib/bundle.js | 1342 -------------------------------- lib/whatsapp-api-client.min.js | 1 - 2 files changed, 1343 deletions(-) delete mode 100644 lib/bundle.js delete mode 100644 lib/whatsapp-api-client.min.js diff --git a/lib/bundle.js b/lib/bundle.js deleted file mode 100644 index d57d57a..0000000 --- a/lib/bundle.js +++ /dev/null @@ -1,1342 +0,0 @@ -'use strict'; - -var axios = require('axios'); -var fs = require('fs'); -var mime = require('mime'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - } - n["default"] = e; - return Object.freeze(n); -} - -var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios); -var fs__namespace = /*#__PURE__*/_interopNamespace(fs); -var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); -var mime__default = /*#__PURE__*/_interopDefaultLegacy(mime); - -class CommonUtils { - static validateString(name, val) { - if (!val || Object.prototype.toString.call(val) !== '[object String]') - throw new Error(`${name} must be a String!`) - } - - static validateInteger(name, val) { - if (!Number.isInteger(val)) - throw new Error(`${name} must be an integer!`) - } - - static validateNumber(name, val) { - if (!val || !Number(val)) - throw new Error(`${name} must be a number!`) - } - - static validateObject(name, val) { - if (!val || Object.prototype.toString.call(val) !== '[object Object]') - throw new Error(`${name} must be an Object!`) - } - - static generateMethodURL(params, method) { - if (method === "sendFileByUpload" || method === "uploadFile") { - return `${params.media}/waInstance${params.idInstance}/${method}/${params.apiTokenInstance}` - } else { - return `${params.host}/waInstance${params.idInstance}/${method}/${params.apiTokenInstance}` - } - } - - static validateChatIdPhoneNumber(chatId, phoneNumber) { - if (!chatId) { - CommonUtils.validateInteger('phoneNumber', phoneNumber); - } - if (!phoneNumber) { - CommonUtils.validateString('chatId', chatId); - } - } - - static validateArray(name, val) { - if (!val || !Array.isArray(val)) - throw new Error(`${name} must be an Array!`) - } - - static validatePath(name, val) { - if (!val || !fs__namespace.existsSync(val)) - throw new Error(`${name} not found!`) - } -} - -class MessageAPI { - - constructor(restAPI) { - this._restAPI = restAPI; - } - - /** Send text message to chat or phone. Method call adds message to sending queue - * - * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). - * Mandatory if phoneNumber is empty - * @param {Number} phoneNumber - receiver phone number using international format without + sign. - * Mandatory if chatId is empty - * @param {String} message - text message - * @param {boolean} linkPreview - allow preview - * @param {String} quotedMessageId - id of message - */ - async sendMessage(chatId, phoneNumber, message, quotedMessageId = null, linkPreview = null) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - CommonUtils.validateString('message', message); - - const method = 'sendMessage'; - - const postData = { - 'message': message, - }; - - if (quotedMessageId !== null) { - postData['quotedMessageId'] = quotedMessageId; - } - if (linkPreview !== null) { - postData['linkPreview'] = linkPreview; - } - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** Send text message to chat or phone. Method call adds message to sending queue - * - * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). - * Mandatory if phoneNumber is empty - * @param {String} phoneNumber - number (77077771515@c.us - for private messages). - * @param {String} message - text message - * @param {array} options - array of objects - * @param {boolean} multipleAnswers - allow answers - * @param {String} quotedMessageId - id of message - */ - - async sendPoll(chatId, phoneNumber, message, options, multipleAnswers = null, quotedMessageId = null) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - CommonUtils.validateString('message', message); - CommonUtils.validateArray('options', options); - - const method = 'sendPoll'; - - const postData = { - 'message': message, - 'options': options, - }; - - if (multipleAnswers !== null) { - postData['multipleAnswers'] = multipleAnswers; - } - if (quotedMessageId !== null) { - postData['quotedMessageId'] = quotedMessageId; - } - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** Send buttons message to chat. Method call adds message to sending queue - * - * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). - * Mandatory if phoneNumber is empty - * @param {String} message - text message - * @param {footer} footer - footer message - * @param {array} buttons - buttons, for example [{"buttonId": "1", "buttonText": "green"}, {"buttonId": "2", "buttonText": "red"}, {"buttonId": "3", "buttonText": "blue"}] - */ - async sendButtons(chatId, message, footer, buttons) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - CommonUtils.validateString('message', message); - - const method = 'sendButtons'; - - const postData = { - 'message': message, - 'footer': footer, - 'buttons': buttons - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** Send buttons message to chat. Method call adds message to sending queue - * - * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). - * @param {String} message - text message - * @param {footer} footer - footer message - * @param {array} templateButtons - buttons, for example [ - {"index": 1, "urlButton": {"displayText": "⭐ Star us on GitHub!", "url": "/~https://github.com/green-api"}}, - {"index": 2, "callButton": {"displayText": "Call us", "phoneNumber": "+1 (234) 5678-901"}}, - {"index": 3, "quickReplyButton": {"displayText": "Plain button", "id": "plainButtonId"}} - ] - */ - async sendTemplateButtons(chatId, message, footer = null, templateButtons) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - CommonUtils.validateString('message', message); - - const method = 'sendTemplateButtons'; - - const postData = { - 'message': message, - 'templateButtons': templateButtons - }; - - if (footer !== null) { - postData.footer = footer; - } - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** Send buttons message to chat. Method call adds message to sending queue - * - * @param {String} chatId - chat id using Whatsapp format (17633123456@c.us - for private messages). - * @param {String} message - text message - * @param {String} buttonText - action list - * @param {String} title - title - * @param {footer} footer - footer message - * @param {array} sections - sections, for example [ - { - "title": "Секция 1", - "rows": [ - { - "title": "Вариант 1", - "rowId": "option1" - }, - { - "title": "Вариант 2", - "rowId": "option2", - "description": "Пояснение" - } - ] - } - */ - async sendListMessage(chatId, message, buttonText, title, footer, sections) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - CommonUtils.validateString('message', message); - - const method = 'sendListMessage'; - - const postData = { - 'message': message, - 'buttonText': buttonText, - 'title': title, - 'footer': footer, - 'sections': sections, - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * @param {String} chatId - * @param {Number} phoneNumber - * @param {String} nameLocation - * @param {String} address - * @param {Number} latitude - * @param {Number} longitude - */ - async sendLocation(chatId, phoneNumber, nameLocation, address, latitude, longitude) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - CommonUtils.validateString('nameLocation', nameLocation); - CommonUtils.validateString('address', address); - CommonUtils.validateNumber('latitude', latitude); - CommonUtils.validateNumber('longitude', longitude); - - const method = 'sendLocation'; - - const postData = { - 'nameLocation': nameLocation, - 'address': address, - 'latitude': latitude, - 'longitude': longitude, - }; - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * @param {String} chatId - * @param {Number} phoneNumber - * @param {Object} contact - object with one or more fields - */ - async sendContact(chatId, phoneNumber, contact) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - CommonUtils.validateObject('contact', contact); - - const method = 'sendContact'; - - const postData = { - 'contact': contact, - }; - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * @param {String} chatId - * @param {Number} phoneNumber - * @param {String} urlLink - */ - async sendLink(chatId, phoneNumber, urlLink) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - CommonUtils.validateString('urlLink', urlLink); - - const method = 'sendLink'; - - const postData = { - 'urlLink': urlLink, - }; - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * @param {String} chatId - * @param {Number} phoneNumber - * @param {String} idMessage - */ - async readChat(chatId, phoneNumber, idMessage = null) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - - const method = 'readChat'; - - const postData = { - 'idMessage': idMessage, - }; - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * Returns array of QueueMessage objects - */ - async showMessagesQueue() { - const method = 'showMessagesQueue'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data.map((msg) => new QueueMessage(msg)) - } - - async clearMessagesQueue() { - const method = 'clearMessagesQueue'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - /** - * Returns array of Message objects - */ - async lastIncomingMessages() { - const method = 'lastIncomingMessages'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data.map((msg) => new Message(msg)) - } - - /** - * Returns array of Message objects - */ - async lastOutgoingMessages() { - const method = 'lastOutgoingMessages'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data.map((msg) => new Message(msg)) - } - - /** - * Returns history of chat - */ - async getChatHistory(chatId) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - - const method = 'getChatHistory'; - - const postData = { - 'chatId': chatId, - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * The method returns the chat message. - * - * @param {String} chatId - * @param {String} idMessage - * - */ - async getMessage(chatId, idMessage) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - CommonUtils.validateString("idMessage", idMessage); - - const method = "getMessage"; - - const postData = { - "idMessage": idMessage, - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * The method is intended for forwarding messages to a personal or group chat - * @param {String} chatId - * @param {String} chatIdFrom - * @param {Array} messages - */ - async forwardMessages(chatId, chatIdFrom, messages) { - CommonUtils.validateString('chatId', chatId); - CommonUtils.validateString('chatIdFrom', chatIdFrom); - CommonUtils.validateArray('messages', messages); - - const method = 'ForwardMessages'; - - const postData = { - 'chatId': chatId, - 'chatIdFrom': chatIdFrom, - 'messages': messages, - }; - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - addChadIdParam(postData, chatId) { - if (chatId) { - postData.chatId = chatId; - } - } - - addPhoneParam(postData, phoneNumber) { - if (phoneNumber) { - postData.chatId = `${phoneNumber}@c.us`; - } - } -} - -class Message { - constructor(data) { - this.chatId = data.chatId; - this.idMessage = data.idMessage; - this.statusMessage = data.statusMessage; - this.textMessage = data.textMessage; - this.timestamp = data.timestamp; - this.typeMessage = data.typeMessage; - } -} - -class QueueMessage { - constructor(data) { - this.chatId = data.chatId; - this.fileName = data.fileName; - this.typeMessage = data.typeMessage; - } -} - -class FileAPI { - - constructor(restAPI) { - this._restAPI = restAPI; - } - - /** - * @param {String} chatId - * @param {Number} phoneNumber - * @param {String} urlFile - * @param {String} fileName - * @param {String} caption Optional - */ - async sendFileByUrl(chatId, phoneNumber, urlFile, fileName, caption = '') { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - CommonUtils.validateString('urlFile', urlFile); - CommonUtils.validateString('filename', fileName); - - const method = 'sendFileByUrl'; - const postData = { - 'urlFile': urlFile, - 'fileName': fileName, - 'caption': caption, - }; - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * @param {String} filePath - */ - async uploadFile(filePath) { - CommonUtils.validateString("filePath", filePath); - - const method = "uploadFile"; - - const fileData = fs__default["default"].readFileSync(filePath); - - const response = await axios__default["default"]({ - method: "post", - url: CommonUtils.generateMethodURL(this._restAPI.params, method), - data: fileData, - headers: {"Content-Type": mime__default["default"].getType(filePath)} - }); - return response.data; - } - - /** - * @param {FormData} formData - */ - async sendFileByUpload(formData) { - const method = 'sendFileByUpload'; - const response = await axios__default["default"]({ - method: 'post', - url: CommonUtils.generateMethodURL(this._restAPI.params, method), - data: formData, - headers: formData.getHeaders() - }); - return response.data; - } - - /** - * @param {String} chatId - * @param {String} idMessage - */ - async downloadFile(chatId, idMessage) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - CommonUtils.validateString('message', idMessage); - - const method = 'downloadFile'; - - const postData = { - 'idMessage': idMessage, - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - addChadIdParam(postData, chatId) { - if (chatId) { - postData.chatId = chatId; - } - } - - addPhoneParam(postData, phoneNumber) { - if (phoneNumber) { - postData.phoneNumber = phoneNumber; - } - } -} - -class InstanceAPI { - - constructor(restAPI) { - this._restAPI = restAPI; - } - - async qr() { - const method = 'qr'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - async logout() { - const method = 'logout'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - async reboot() { - const method = 'reboot'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - async getStateInstance() { - const method = 'getStateInstance'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - async getDeviceInfo() { - const method = 'getDeviceInfo'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - /** - * - * @param {Number} phoneNumber - */ - async checkWhatsapp(phoneNumber) { - CommonUtils.validateInteger('phoneNumber', phoneNumber); - - const method = 'checkWhatsapp'; - const postData = { - 'phoneNumber': phoneNumber, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * - * @param {String} chatId - * @param {Number} phoneNumber - */ - async getAvatar(chatId, phoneNumber) { - CommonUtils.validateChatIdPhoneNumber(chatId, phoneNumber); - - const method = 'getAvatar'; - const postData = { - }; - - this.addChadIdParam(postData, chatId); - this.addPhoneParam(postData, phoneNumber); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * - * @param {String} chatId - */ - async archiveChat(chatId) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - - const method = 'archiveChat'; - const postData = { - - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * - * @param {String} chatId - */ - async unarchiveChat(chatId) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - - const method = 'unarchiveChat'; - const postData = { - - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - /** - * - * @param {String} chatId - */ - async getContactInfo(chatId) { - CommonUtils.validateChatIdPhoneNumber(chatId, undefined); - - const method = 'getContactInfo'; - const postData = { - - }; - - this.addChadIdParam(postData, chatId); - - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data - } - - async getContacts() { - const method = 'getContacts'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - async getChats() { - const method = 'getChats'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - addChadIdParam(postData, chatId) { - if (chatId) { - postData.chatId = chatId; - } - } - - addPhoneParam(postData, phoneNumber) { - if (phoneNumber) { - postData.phoneNumber = phoneNumber; - } - } - -} - -class SettingsAPI { - - constructor(restAPI) { - this._restAPI = restAPI; - } - - async getSettings() { - const method = 'getSettings'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data; - } - - /** - * Change instance account settings. You can specify which settings to update. - * Instance will be restarted as a result of method. - * - * @param {Object} settings - js object that consists of one or more props: - * countryInstance, webhookUrl, delaySendMessagesMilliseconds, markIncomingMessagesReaded, - * for example: - * - * settings = { - * countryInstance: "ru", - * delaySendMessagesMilliseconds: 500 - * } - * - */ - async setSettings(settings) { - CommonUtils.validateObject("settings", settings); - - const method = 'setSettings'; - const postData = settings; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - - async getWaSettings () { - const method = 'getWaSettings'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - -} - -class GroupAPI { - - constructor(restAPI) { - this._restAPI = restAPI; - } - /** - * - * @param {String} groupName - * @param {Array} chatIds - */ - async createGroup(groupName, chatIds) { - CommonUtils.validateString('groupName', groupName); - CommonUtils.validateArray('chatIds', chatIds); - - const method = 'createGroup'; - const postData = { - 'groupName': groupName, - 'chatIds': chatIds - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - * @param {String} participantChatId - * @param {Number} participantPhone - */ - async addGroupParticipant(groupId, participantChatId, participantPhone) { - CommonUtils.validateString('groupId', groupId); - CommonUtils.validateChatIdPhoneNumber(participantChatId, participantPhone); - - const method = 'addGroupParticipant'; - const postData = { - 'groupId': groupId, - 'participantChatId': participantChatId, - 'participantPhone': participantPhone, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - */ - async getGroupData(groupId) { - CommonUtils.validateString('groupId', groupId); - - const method = 'getGroupData'; - const postData = { - 'groupId': groupId, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - * @param {String} participantChatId - * @param {Number} participantPhone - */ - async removeGroupParticipant(groupId, participantChatId, participantPhone) { - CommonUtils.validateString('groupId', groupId); - CommonUtils.validateChatIdPhoneNumber(participantChatId, participantPhone); - - const method = 'removeGroupParticipant'; - const postData = { - 'groupId': groupId, - 'participantChatId': participantChatId, - 'participantPhone': participantPhone, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - * @param {String} groupName - */ - async updateGroupName(groupId, groupName) { - CommonUtils.validateString('groupId', groupId); - CommonUtils.validateString('groupName', groupName); - - const method = 'updateGroupName'; - const postData = { - 'groupId': groupId, - 'groupName': groupName, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - * @param {String} participantChatId - * @param {Number} participantPhone - */ - async setGroupAdmin(groupId, participantChatId, participantPhone) { - CommonUtils.validateString('groupId', groupId); - - const method = 'setGroupAdmin'; - const postData = { - 'groupId': groupId, - 'participantChatId': participantChatId, - 'participantPhone': participantPhone, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - * @param {String} participantChatId - * @param {Number} participantPhone - */ - async removeAdmin(groupId, participantChatId, participantPhone) { - CommonUtils.validateString('groupId', groupId); - - const method = 'removeAdmin'; - const postData = { - 'groupId': groupId, - 'participantChatId': participantChatId, - 'participantPhone': participantPhone, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * - * @param {String} groupId - */ - async leaveGroup(groupId) { - CommonUtils.validateString('groupId', groupId); - - const method = 'removeAdmin'; - const postData = { - 'groupId': groupId, - }; - const response = await axios__default["default"].post(CommonUtils.generateMethodURL(this._restAPI.params, method), postData); - return response.data; - } - - /** - * @param {String} filePath - * @param {String} groupId - */ - async setGroupPicture(groupId, filePath) { - CommonUtils.validateString("filePath", filePath); - CommonUtils.validateString('groupId', groupId); - - const method = "setGroupPicture"; - - const fileStream = fs__default["default"].createReadStream(filePath); - const fileData = []; - - for await (const data of fileStream) { - fileData.push(data); - } - - const blob = new Blob(fileData, { type: 'image/jpeg' }); - - const formData = new FormData(); - formData.append('groupId', groupId); - formData.append('file', blob, "group_avatar.jpg"); - - const response = await axios__default["default"]({ - method: "post", - url: CommonUtils.generateMethodURL(this._restAPI.params, method), - data: formData, - headers: {"Content-Type": "image/jpeg"} - }); - return response.data; - } -} - -class SingleThreadJobScheduler { - - initJobs(jobs = []) { - this.jobs = jobs; - } - - reschedule() { - this.jobs.forEach(job => { - job.needInterrupt = false; - clearInterval(job.timerId); - job.timerId = setInterval(job.run, job.intervalSec * 1000); - }); - } - - unschedule() { - this.jobs.forEach(job => { - job.needInterrupt = true; - clearInterval(job.timerId); - }); - } -} - -class ReceiveNotificationsJob { - - timerId; - intervalSec; - needInterrupt = false - - constructor(webhookServiceApi) { - this.webhookServiceApi = webhookServiceApi; - this.intervalSec = Number.parseInt('1'); - } - - run = async () => { - clearInterval(this.timerId); - try { - let response; - while (response = await this.webhookServiceApi.receiveNotification()) { - let webhookBody = response.body; - if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.incomingMessageReceived) { - if (webhookBody.messageData.typeMessage == "imageMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageImage, webhookBody); - } else if (webhookBody.messageData.typeMessage == "videoMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageVideo, webhookBody); - } else if (webhookBody.messageData.typeMessage == "documentMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument, webhookBody); - } else if (webhookBody.messageData.typeMessage == "audioMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageAudio, webhookBody); - } else if (webhookBody.messageData.typeMessage == "documentMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument, webhookBody); - } else if (webhookBody.messageData.typeMessage == "textMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageText, webhookBody); - } else if (webhookBody.messageData.typeMessage == "extendedTextMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageTextURL, webhookBody); - } else if (webhookBody.messageData.typeMessage == "contactMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageContact, webhookBody); - } else if (webhookBody.messageData.typeMessage == "locationMessage") { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageLocation, webhookBody); - } - } else if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.stateInstanceChanged) { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingAccountStatus, webhookBody); - } else if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.outgoingMessageStatus) { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingOutboundMessageStatus, webhookBody); - } else if (webhookBody.typeWebhook === this.webhookServiceApi.noteTypes.deviceInfo) { - this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingDeviceStatus, webhookBody); - } - await this.webhookServiceApi.deleteNotification(response.receiptId); - } - } catch (ex) { - console.error(ex.toString()); - } - if (!this.needInterrupt) { - this.timerId = setInterval(this.run, this.intervalSec * 1000); - } - } - - callCallback(webhookType, body) { - const callback = this.webhookServiceApi._callbacks.get(webhookType); - if (callback) { - // Found webhook callback; - callback.call(this, body); - // Callback invoked successfully; - } } - -} - -class WebhookServiceAPI { - - constructor(restAPI) { - this._restAPI = restAPI; - this._jobScheduler = new SingleThreadJobScheduler(); - this.noteTypes = { - incomingMessageReceived : 'incomingMessageReceived', - outgoingMessageStatus : 'outgoingMessageStatus', - stateInstanceChanged : 'stateInstanceChanged', - deviceInfo: 'deviceInfo', - }; - this.callbackTypes = { - onReceivingMessageText : 'onReceivingMessageText', - onReceivingMessageImage : 'onReceivingMessageImage', - onReceivingMessageVideo : 'onReceivingMessageVideo', - onReceivingMessageDocument: 'onReceivingMessageDocument', - onReceivingMessageAudio: 'onReceivingMessageAudio', - onReceivingOutboundMessageStatus: 'onReceivingOutboundMessageStatus', - onReceivingAccountStatus: 'onReceivingAccountStatus', - onReceivingDeviceStatus: 'onReceivingDeviceStatus', - onReceivingMessageTextURL: 'onReceivingMessageTextURL', - onReceivingMessageContact: 'onReceivingMessageContact', - onReceivingMessageLocation: 'onReceivingMessageLocation', - }; - this._callbacks = new Map(); - } - - async receiveNotification() { - const method = 'receiveNotification'; - const response = await axios__default["default"].get(CommonUtils.generateMethodURL(this._restAPI.params, method)); - return response.data - } - - /** - * - * @param {Number} receiptId - */ - async deleteNotification(receiptId) { - CommonUtils.validateInteger('receiptId', receiptId); - - const method = 'deleteNotification'; - const response = await axios__default["default"].delete(`${CommonUtils.generateMethodURL(this._restAPI.params, method)}/${receiptId}`); - return response.data - } - - async startReceivingNotifications() { - this._jobScheduler.initJobs([new ReceiveNotificationsJob(this)]); - this._jobScheduler.reschedule(); - } - - async stopReceivingNotifications() { - this._jobScheduler.unschedule(); - } - - onReceivingMessageText(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageText, callback); - } - onReceivingMessageImage(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageImage, callback); - } - onReceivingMessageVideo(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageVideo, callback); - } - onReceivingMessageDocument(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageDocument, callback); - } - onReceivingMessageAudio(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageAudio, callback); - } - onReceivingOutboundMessageStatus(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingOutboundMessageStatus, callback); - } - onReceivingAccountStatus(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingAccountStatus, callback); - } - onReceivingDeviceStatus(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingDeviceStatus, callback); - } - onReceivingMessageTextURL(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageTextURL, callback); - } - onReceivingMessageContact(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageContact, callback); - } - onReceivingMessageLocation(callback) - { - this._callbacks.set(this.callbackTypes.onReceivingMessageLocation, callback); - } -} - -class RestAPI { - - constructor(params) { - - this.params = { - host: "", - media: "", - idInstance: "", - apiTokenInstance: "", - credentialsPath: null, - }; - - Object.assign(this.params, params); - - if (params.credentialsPath) { - fs__namespace.readFileSync(params.credentialsPath) - .toString('utf8') - .split('\n') - .map(item => item.split(" ").join("")) // replaceAll equivalent - .forEach(item => { - if (item.startsWith('API_TOKEN_INSTANCE=')) { - this.params.apiTokenInstance = item.replace('API_TOKEN_INSTANCE=', '').trim(); - } else if (item.startsWith('ID_INSTANCE=')) { - this.params.idInstance = item.replace('ID_INSTANCE=', '').trim(); - } - }); - } - - this.message = new MessageAPI(this); - this.file = new FileAPI(this); - this.instance = new InstanceAPI(this); - this.settings = new SettingsAPI(this); - this.group = new GroupAPI(this); - this.webhookService = new WebhookServiceAPI(this); - } -} - -var configuration = { - defaultHost: "https://api.green-api.com", - defaultMediaHost: "https://media.green-api.com" -}; - -class WebhooksCallbackAPI { - - constructor(express, webhookRoutePath) { - this._app = express; - this._webhookRoutePath = webhookRoutePath; - this._callbacks = new Map(); - } - - init() { - this._app.post(this._webhookRoutePath, async (req, res, next) => { - try { - console.log(`Received webhook ${req.body.typeWebhook}`); - let webhookType = null; - if (req.body.messageData && req.body.messageData.typeMessage) { - webhookType = `${req.body.typeWebhook}_${req.body.messageData.typeMessage}`; - } else { - webhookType = req.body.typeWebhook; - } - - const callback = this._callbacks.get(webhookType); - if (callback) { - // Found webhook callback; - callback.call(this, req.body); - // Callback invoked successfully; - } else { - // Callback not found; - }; - return res.send(); - } catch (err) { - next(err); - } - }); - } - - /** - * - * @param {Function} callback function - */ - onStateInstance(callback) { - this._callbacks.set("stateInstanceChanged", callback); - } - - /** - * - * @param {Function} callback function - */ - onOutgoingMessageStatus(callback) { - this._callbacks.set("outgoingMessageStatus", (data) => { - callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.status); - }); - } - - /** - * - * @param {Function} callback function - */ - onIncomingMessageText(callback) { - this._callbacks.set("incomingMessageReceived_textMessage", (data) => { - callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, - data.messageData.textMessageData.textMessage); - }); - } - - /** - * - * @param {Function} callback function - */ - onIncomingMessageFile(callback) { - this._callbacks.set("incomingMessageReceived_imageMessage", (data) => { - callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, - data.messageData.downloadUrl); - }); - } - - /** - * - * @param {Function} callback function - */ - onIncomingMessageLocation(callback) { - this._callbacks.set("incomingMessageReceived_locationMessage", (data) => { - callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, - data.messageData.locationMessageData.latitude, data.messageData.locationMessageData.longitude, data.messageData.locationMessageData.jpegThumbnail); - }); - } - - /** - * - * @param {Function} callback function - */ - onIncomingMessageContact(callback) { - this._callbacks.set("incomingMessageReceived_contactMessage", (data) => { - callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, - data.messageData.contactMessageData.displayName, data.messageData.contactMessageData.vcard); - }); - } - - /** - * - * @param {Function} callback function - */ - onIncomingMessageExtendedText(callback) { - this._callbacks.set("incomingMessageReceived_extendedTextMessage", (data) => { - callback.call(this, data, data.instanceData.idInstance, data.idMessage, data.senderData.sender, data.messageData.typeMessage, - data.extendedTextMessageData); - }); - } - - /** - * - * @param {Function} callback function - */ - onDeviceInfo(callback) { - this._callbacks.set("deviceInfo", callback); - } - -} - -function checkInitParams(params = {}) { - - if (params.host) { - CommonUtils.validateString("host", params.host); - } else { - params.host = configuration.defaultHost; - } - - if (params.media) { - CommonUtils.validateString("media", params.media); - } else { - params.media = configuration.defaultMediaHost; - } - - if (params.credentialsPath) { - CommonUtils.validatePath("credentialsPath", params.credentialsPath); - } else { - CommonUtils.validateString("idInstance", params.idInstance); - CommonUtils.validateString("apiTokenInstance", params.apiTokenInstance); - } -} - -const restAPI = (params = {}) => { - checkInitParams(params); - return new RestAPI(params) -}; - -const webhookAPI = (express, webhookRoutePath) => { - const api = new WebhooksCallbackAPI(express, webhookRoutePath); - api.init(); - return api; -}; - -var index = { - restAPI, - webhookAPI -}; - -module.exports = index; diff --git a/lib/whatsapp-api-client.min.js b/lib/whatsapp-api-client.min.js deleted file mode 100644 index 4618fe4..0000000 --- a/lib/whatsapp-api-client.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a(require("axios"),require("fs"),require("mime")):"function"==typeof define&&define.amd?define(["axios","fs","mime"],a):(e="undefined"!=typeof globalThis?globalThis:e||self).whatsAppClient=a(e.axios,e.fs,e.mime)}(this,(function(e,a,t){"use strict";function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var a=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}})),a.default=e,Object.freeze(a)}var n=s(e),r=i(a),o=s(a),d=s(t);class c{static validateString(e,a){if(!a||"[object String]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be a String!`)}static validateInteger(e,a){if(!Number.isInteger(a))throw new Error(`${e} must be an integer!`)}static validateNumber(e,a){if(!a||!Number(a))throw new Error(`${e} must be a number!`)}static validateObject(e,a){if(!a||"[object Object]"!==Object.prototype.toString.call(a))throw new Error(`${e} must be an Object!`)}static generateMethodURL(e,a){return"sendFileByUpload"===a||"uploadFile"===a?`${e.media}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`:`${e.host}/waInstance${e.idInstance}/${a}/${e.apiTokenInstance}`}static validateChatIdPhoneNumber(e,a){e||c.validateInteger("phoneNumber",a),a||c.validateString("chatId",e)}static validateArray(e,a){if(!a||!Array.isArray(a))throw new Error(`${e} must be an Array!`)}static validatePath(e,a){if(!a||!r.existsSync(a))throw new Error(`${e} not found!`)}}class g{constructor(e){this._restAPI=e}async sendMessage(e,a,t,s=null,i=null){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t);const r={message:t};null!==s&&(r.quotedMessageId=s),null!==i&&(r.linkPreview=i),this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendMessage"),r)).data}async sendPoll(e,a,t,s,i=null,r=null){c.validateChatIdPhoneNumber(e,a),c.validateString("message",t),c.validateArray("options",s);const o={message:t,options:s};null!==i&&(o.multipleAnswers=i),null!==r&&(o.quotedMessageId=r),this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendPoll"),o)).data}async sendButtons(e,a,t,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,footer:t,buttons:s};this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendButtons"),i)).data}async sendTemplateButtons(e,a,t=null,s){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const i={message:a,templateButtons:s};null!==t&&(i.footer=t),this.addChadIdParam(i,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendTemplateButtons"),i)).data}async sendListMessage(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const o={message:a,buttonText:t,title:s,footer:i,sections:r};this.addChadIdParam(o,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendListMessage"),o)).data}async sendLocation(e,a,t,s,i,r){c.validateChatIdPhoneNumber(e,a),c.validateString("nameLocation",t),c.validateString("address",s),c.validateNumber("latitude",i),c.validateNumber("longitude",r);const o={nameLocation:t,address:s,latitude:i,longitude:r};this.addChadIdParam(o,e),this.addPhoneParam(o,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLocation"),o)).data}async sendContact(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateObject("contact",t);const s={contact:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendContact"),s)).data}async sendLink(e,a,t){c.validateChatIdPhoneNumber(e,a),c.validateString("urlLink",t);const s={urlLink:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendLink"),s)).data}async readChat(e,a,t=null){c.validateChatIdPhoneNumber(e,a);const s={idMessage:t};this.addChadIdParam(s,e),this.addPhoneParam(s,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"readChat"),s)).data}async showMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"showMessagesQueue"))).data.map((e=>new h(e)))}async clearMessagesQueue(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"clearMessagesQueue"))).data}async lastIncomingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastIncomingMessages"))).data.map((e=>new l(e)))}async lastOutgoingMessages(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"lastOutgoingMessages"))).data.map((e=>new l(e)))}async getChatHistory(e){c.validateChatIdPhoneNumber(e,void 0);const a={chatId:e};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getChatHistory"),a)).data}async getMessage(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("idMessage",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getMessage"),t)).data}async forwardMessages(e,a,t){c.validateString("chatId",e),c.validateString("chatIdFrom",a),c.validateArray("messages",t);const s={chatId:e,chatIdFrom:a,messages:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"ForwardMessages"),s)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.chatId=`${a}@c.us`)}}class l{constructor(e){this.chatId=e.chatId,this.idMessage=e.idMessage,this.statusMessage=e.statusMessage,this.textMessage=e.textMessage,this.timestamp=e.timestamp,this.typeMessage=e.typeMessage}}class h{constructor(e){this.chatId=e.chatId,this.fileName=e.fileName,this.typeMessage=e.typeMessage}}class u{constructor(e){this._restAPI=e}async sendFileByUrl(e,a,t,s,i=""){c.validateChatIdPhoneNumber(e,a),c.validateString("urlFile",t),c.validateString("filename",s);const r={urlFile:t,fileName:s,caption:i};this.addChadIdParam(r,e),this.addPhoneParam(r,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"sendFileByUrl"),r)).data}async uploadFile(e){c.validateString("filePath",e);const a=o.default.readFileSync(e);return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"uploadFile"),data:a,headers:{"Content-Type":d.default.getType(e)}})).data}async sendFileByUpload(e){return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"sendFileByUpload"),data:e,headers:e.getHeaders()})).data}async downloadFile(e,a){c.validateChatIdPhoneNumber(e,void 0),c.validateString("message",a);const t={idMessage:a};this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"downloadFile"),t)).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class p{constructor(e){this._restAPI=e}async qr(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"qr"))).data}async logout(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"logout"))).data}async reboot(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"reboot"))).data}async getStateInstance(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getStateInstance"))).data}async getDeviceInfo(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getDeviceInfo"))).data}async checkWhatsapp(e){c.validateInteger("phoneNumber",e);const a={phoneNumber:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"checkWhatsapp"),a)).data}async getAvatar(e,a){c.validateChatIdPhoneNumber(e,a);const t={};this.addChadIdParam(t,e),this.addPhoneParam(t,a);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getAvatar"),t)).data}async archiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"archiveChat"),a)).data}async unarchiveChat(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"unarchiveChat"),a)).data}async getContactInfo(e){c.validateChatIdPhoneNumber(e,void 0);const a={};this.addChadIdParam(a,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getContactInfo"),a)).data}async getContacts(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getContacts"))).data}async getChats(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getChats"))).data}addChadIdParam(e,a){a&&(e.chatId=a)}addPhoneParam(e,a){a&&(e.phoneNumber=a)}}class m{constructor(e){this._restAPI=e}async getSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getSettings"))).data}async setSettings(e){c.validateObject("settings",e);const a=e;return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setSettings"),a)).data}async getWaSettings(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"getWaSettings"))).data}}class I{constructor(e){this._restAPI=e}async createGroup(e,a){c.validateString("groupName",e),c.validateArray("chatIds",a);const t={groupName:e,chatIds:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"createGroup"),t)).data}async addGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"addGroupParticipant"),s)).data}async getGroupData(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getGroupData"),a)).data}async removeGroupParticipant(e,a,t){c.validateString("groupId",e),c.validateChatIdPhoneNumber(a,t);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeGroupParticipant"),s)).data}async updateGroupName(e,a){c.validateString("groupId",e),c.validateString("groupName",a);const t={groupId:e,groupName:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"updateGroupName"),t)).data}async setGroupAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setGroupAdmin"),s)).data}async removeAdmin(e,a,t){c.validateString("groupId",e);const s={groupId:e,participantChatId:a,participantPhone:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),s)).data}async leaveGroup(e){c.validateString("groupId",e);const a={groupId:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"removeAdmin"),a)).data}async setGroupPicture(e,a){c.validateString("filePath",a),c.validateString("groupId",e);const t=o.default.createReadStream(a),s=[];for await(const e of t)s.push(e);const i=new Blob(s,{type:"image/jpeg"}),r=new FormData;r.append("groupId",e),r.append("file",i,"group_avatar.jpg");return(await n.default({method:"post",url:c.generateMethodURL(this._restAPI.params,"setGroupPicture"),data:r,headers:{"Content-Type":"image/jpeg"}})).data}}class v{initJobs(e=[]){this.jobs=e}reschedule(){this.jobs.forEach((e=>{e.needInterrupt=!1,clearInterval(e.timerId),e.timerId=setInterval(e.run,1e3*e.intervalSec)}))}unschedule(){this.jobs.forEach((e=>{e.needInterrupt=!0,clearInterval(e.timerId)}))}}class M{timerId;intervalSec;needInterrupt=!1;constructor(e){this.webhookServiceApi=e,this.intervalSec=Number.parseInt("1")}run=async()=>{clearInterval(this.timerId);try{let e;for(;e=await this.webhookServiceApi.receiveNotification();){let a=e.body;a.typeWebhook===this.webhookServiceApi.noteTypes.incomingMessageReceived?"imageMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageImage,a):"videoMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageVideo,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"audioMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageAudio,a):"documentMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageDocument,a):"textMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageText,a):"extendedTextMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageTextURL,a):"contactMessage"==a.messageData.typeMessage?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageContact,a):"locationMessage"==a.messageData.typeMessage&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingMessageLocation,a):a.typeWebhook===this.webhookServiceApi.noteTypes.stateInstanceChanged?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingAccountStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.outgoingMessageStatus?this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingOutboundMessageStatus,a):a.typeWebhook===this.webhookServiceApi.noteTypes.deviceInfo&&this.callCallback(this.webhookServiceApi.callbackTypes.onReceivingDeviceStatus,a),await this.webhookServiceApi.deleteNotification(e.receiptId)}}catch(e){console.error(e.toString())}this.needInterrupt||(this.timerId=setInterval(this.run,1e3*this.intervalSec))};callCallback(e,a){const t=this.webhookServiceApi._callbacks.get(e);t&&t.call(this,a)}}class b{constructor(e){this._restAPI=e,this._jobScheduler=new v,this.noteTypes={incomingMessageReceived:"incomingMessageReceived",outgoingMessageStatus:"outgoingMessageStatus",stateInstanceChanged:"stateInstanceChanged",deviceInfo:"deviceInfo"},this.callbackTypes={onReceivingMessageText:"onReceivingMessageText",onReceivingMessageImage:"onReceivingMessageImage",onReceivingMessageVideo:"onReceivingMessageVideo",onReceivingMessageDocument:"onReceivingMessageDocument",onReceivingMessageAudio:"onReceivingMessageAudio",onReceivingOutboundMessageStatus:"onReceivingOutboundMessageStatus",onReceivingAccountStatus:"onReceivingAccountStatus",onReceivingDeviceStatus:"onReceivingDeviceStatus",onReceivingMessageTextURL:"onReceivingMessageTextURL",onReceivingMessageContact:"onReceivingMessageContact",onReceivingMessageLocation:"onReceivingMessageLocation"},this._callbacks=new Map}async receiveNotification(){return(await n.default.get(c.generateMethodURL(this._restAPI.params,"receiveNotification"))).data}async deleteNotification(e){c.validateInteger("receiptId",e);return(await n.default.delete(`${c.generateMethodURL(this._restAPI.params,"deleteNotification")}/${e}`)).data}async startReceivingNotifications(){this._jobScheduler.initJobs([new M(this)]),this._jobScheduler.reschedule()}async stopReceivingNotifications(){this._jobScheduler.unschedule()}onReceivingMessageText(e){this._callbacks.set(this.callbackTypes.onReceivingMessageText,e)}onReceivingMessageImage(e){this._callbacks.set(this.callbackTypes.onReceivingMessageImage,e)}onReceivingMessageVideo(e){this._callbacks.set(this.callbackTypes.onReceivingMessageVideo,e)}onReceivingMessageDocument(e){this._callbacks.set(this.callbackTypes.onReceivingMessageDocument,e)}onReceivingMessageAudio(e){this._callbacks.set(this.callbackTypes.onReceivingMessageAudio,e)}onReceivingOutboundMessageStatus(e){this._callbacks.set(this.callbackTypes.onReceivingOutboundMessageStatus,e)}onReceivingAccountStatus(e){this._callbacks.set(this.callbackTypes.onReceivingAccountStatus,e)}onReceivingDeviceStatus(e){this._callbacks.set(this.callbackTypes.onReceivingDeviceStatus,e)}onReceivingMessageTextURL(e){this._callbacks.set(this.callbackTypes.onReceivingMessageTextURL,e)}onReceivingMessageContact(e){this._callbacks.set(this.callbackTypes.onReceivingMessageContact,e)}onReceivingMessageLocation(e){this._callbacks.set(this.callbackTypes.onReceivingMessageLocation,e)}}class y{constructor(e){this.params={host:"",media:"",idInstance:"",apiTokenInstance:"",credentialsPath:null},Object.assign(this.params,e),e.credentialsPath&&r.readFileSync(e.credentialsPath).toString("utf8").split("\n").map((e=>e.split(" ").join(""))).forEach((e=>{e.startsWith("API_TOKEN_INSTANCE=")?this.params.apiTokenInstance=e.replace("API_TOKEN_INSTANCE=","").trim():e.startsWith("ID_INSTANCE=")&&(this.params.idInstance=e.replace("ID_INSTANCE=","").trim())})),this.message=new g(this),this.file=new u(this),this.instance=new p(this),this.settings=new m(this),this.group=new I(this),this.webhookService=new b(this)}}var P="https://api.green-api.com",f="https://media.green-api.com";class R{constructor(e,a){this._app=e,this._webhookRoutePath=a,this._callbacks=new Map}init(){this._app.post(this._webhookRoutePath,(async(e,a,t)=>{try{console.log(`Received webhook ${e.body.typeWebhook}`);let t=null;t=e.body.messageData&&e.body.messageData.typeMessage?`${e.body.typeWebhook}_${e.body.messageData.typeMessage}`:e.body.typeWebhook;const s=this._callbacks.get(t);return s&&s.call(this,e.body),a.send()}catch(e){t(e)}}))}onStateInstance(e){this._callbacks.set("stateInstanceChanged",e)}onOutgoingMessageStatus(e){this._callbacks.set("outgoingMessageStatus",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.status)}))}onIncomingMessageText(e){this._callbacks.set("incomingMessageReceived_textMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.textMessageData.textMessage)}))}onIncomingMessageFile(e){this._callbacks.set("incomingMessageReceived_imageMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.downloadUrl)}))}onIncomingMessageLocation(e){this._callbacks.set("incomingMessageReceived_locationMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.locationMessageData.latitude,a.messageData.locationMessageData.longitude,a.messageData.locationMessageData.jpegThumbnail)}))}onIncomingMessageContact(e){this._callbacks.set("incomingMessageReceived_contactMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.messageData.contactMessageData.displayName,a.messageData.contactMessageData.vcard)}))}onIncomingMessageExtendedText(e){this._callbacks.set("incomingMessageReceived_extendedTextMessage",(a=>{e.call(this,a,a.instanceData.idInstance,a.idMessage,a.senderData.sender,a.messageData.typeMessage,a.extendedTextMessageData)}))}onDeviceInfo(e){this._callbacks.set("deviceInfo",e)}}return{restAPI:(e={})=>(function(e={}){e.host?c.validateString("host",e.host):e.host=P,e.media?c.validateString("media",e.media):e.media=f,e.credentialsPath?c.validatePath("credentialsPath",e.credentialsPath):(c.validateString("idInstance",e.idInstance),c.validateString("apiTokenInstance",e.apiTokenInstance))}(e),new y(e)),webhookAPI:(e,a)=>{const t=new R(e,a);return t.init(),t}}}));