@green-api/whatsapp-api-client
Version:
Library to integrate with WhatsApp API. For details have look at https://green-api.com
2 lines (1 loc) • 20.5 kB
JavaScript
!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={};this.addMessageIdParam(s,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,a=null){c.validateChatIdPhoneNumber(e,void 0);const t={chatId:e};null!==a&&a>0&&(t.count=a),this.addChadIdParam(t,e);return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getChatHistory"),t)).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}.us`)}addMessageIdParam(e,a){a&&(e.idMessage=a)}}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.messageID=e.messageID,this.messagesIDs=e.messagesIDs,this.type=e.type,this.body=e.body}}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 deleteMessage(e,a){c.validateString("chatId",e),c.validateString("idMessage",a);const t={chatId:e,idMessage:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"deleteMessage"),t)).data}async editMessage(e,a,t){c.validateString("chatId",e),c.validateString("idMessage",a),c.validateString("message",t);const s={chatId:e,idMessage:a,message:t};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"editMessage"),s)).data}async getAuthorizationCode(e){c.validateInteger("phoneNumber",e);const a={phoneNumber:e};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"getAuthorizationCode"),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};this.addChadIdParam(s,a),this.addPhoneParam(s,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};this.addChadIdParam(s,a),this.addPhoneParam(s,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=null){c.validateString("groupId",e);const s={groupId:e,participantChatId:a};return(await n.default.post(c.generateMethodURL(this._restAPI.params,"setGroupAdmin"),s)).data}async removeAdmin(e,a,t=null){c.validateString("groupId",e);const s={groupId:e,participantChatId:a};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,"leaveGroup"),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}addChadIdParam(e,a){a&&(e.participantChatId=a)}addPhoneParam(e,a){a&&(e.participantChatId=`${a}.us`)}}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",onReceivingEditedMessage:"onReceivingEditedMessage",onReceivingDeletedMessage:"onReceivingDeletedMessage"},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)}onReceivingEditedMessage(e){this._callbacks.set(this.callbackTypes.onReceivingEditedMessage,e)}onReceivingDeletedMessage(e){this._callbacks.set(this.callbackTypes.onReceivingDeletedMessage,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",R="https://media.green-api.com";class f{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=R,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 f(e,a);return t.init(),t}}}));