Open agencia904 opened 2 months ago
Confirmo que tenho exatamente o mesmo erro na versão 2.1.1
[Evolution API] v2.1.1 184 - Fri Oct 04 2024 09:10:41 ERROR [OpenaiController] [object]
PrismaClientKnownRequestError:
Invalid `this.prismaRepository.integrationSession.findFirst()` invocation in
/evolution/dist/main.js:236:45545
233 END:VCARD`,n};return e.contact.length===1?t.contactMessage={displayName:e.contact[0].fullName,vcard:s(e.contact[0])}:t.contactsArrayMessage={displayName:`${e.contact.length} contacts`,contacts:e.contact.map(o=>({displayName:o.fullName,vcard:s(o)}))},await this.sendMessageWithTyping(e.number,{...t},{})}async reactionMessage(e){return await this.sendMessageWithTyping(e.key.remoteJid,{reactionMessage:{key:e.key,text:e.reaction}})}async whatsappNumber(e){let t={groups:[],broadcast:[],users:[]};e.numbers.forEach(l=>{let g=this.createJid(l);(0,A.isJidGroup)(g)?t.groups.push({number:l,jid:g}):g==="status@broadcast"?t.broadcast.push({number:l,jid:g}):t.users.push({number:l,jid:g})});let s=[];s.push(...t.broadcast.map(({jid:l,number:g})=>new tt(l,!1,g)));let o=await Promise.all(t.groups.map(async({jid:l,number:g})=>{let h=await this.findGroup({groupJid:l},"inner");return h||new tt(l,!1,g),new tt(h.id,!!h?.id,g,h?.subject)}));s.push(...o);let n=await this.prismaRepository.contact.findMany({where:{instanceId:this.instanceId,remoteJid:{in:t.users.map(({jid:l})=>l)}}}),r=t.users.map(({jid:l})=>l.replace("+","")),a=await Ko(r),c=r.filter(l=>!a.some(g=>g.jidOptions.includes(l))),u=await this.client.onWhatsApp(...c),d=await Promise.all(t.users.map(async l=>{let g=null,h=a.find(f=>f.jidOptions.includes(l.jid.replace("+","")));if(h)return{exists:!0,jid:h.remoteJid,name:n.find(f=>f.remoteJid===h.remoteJid)?.pushName,number:l.number};if(l.number.startsWith("55")){let f=l.number.slice(4,5)==="9"&&l.number.length===13?l.number:`${l.number.slice(0,4)}9${l.number.slice(4)}`,w=l.number.length===12?l.number:l.number.slice(0,4)+l.number.slice(5);g=u.find(M=>M.jid===`${f}@s.whatsapp.net`||M.jid===`${w}@s.whatsapp.net`)}if(!g&&(l.number.startsWith("52")||l.number.startsWith("54"))){let f="";l.number.startsWith("52")&&(f="1"),l.number.startsWith("54")&&(f="9");let w=l.number.slice(2,3)===f&&l.number.length===13?l.number:`${l.number.slice(0,2)}${f}${l.number.slice(2)}`,M=l.number.length===12?l.number:l.number.slice(0,2)+l.number.slice(3);g=u.find(b=>b.jid===`${w}@s.whatsapp.net`||b.jid===`${M}@s.whatsapp.net`)}g||(g=u.find(f=>f.jid===l.jid));let y=g?.jid||l.jid;return{exists:!!g?.exists,jid:y,name:n.find(f=>f.remoteJid===y)?.pushName,number:l.number}}));return await $e(d.filter(l=>l.exists).map(l=>({remoteJid:l.jid}))),s.push(...d),s}async markMessageAsRead(e){try{let t=[];return e.readMessages.forEach(s=>{((0,A.isJidGroup)(s.remoteJid)||(0,A.isJidUser)(s.remoteJid))&&t.push({remoteJid:s.remoteJid,fromMe:s.fromMe,id:s.id})}),await this.client.readMessages(t),{message:"Read messages",read:"success"}}catch(t){throw this.logger.error("line 2818"),new N("Read messages fail",t.toString())}}async getLastMessage(e){let t={key:{remoteJid:e},instanceId:this.instance.id},s=await this.prismaRepository.message.findMany({where:t,orderBy:{messageTimestamp:"desc"},take:1});if(s.length===0)throw new _("Messages not found");let o=s.pop();for(let n of s)n.messageTimestamp>=o.messageTimestamp&&(o=n);return o}async archiveChat(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new _("Last message not found");return await this.client.chatModify({archive:e.archive,lastMessages:[t]},this.createJid(s)),{chatId:s,archived:!0}}catch(t){throw this.logger.error("line 2884"),new N({archived:!1,message:["An error occurred while archiving the chat. Open a calling.",t.toString()]})}}async markChatUnread(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new _("Last message not found");return await this.client.chatModify({markRead:!1,lastMessages:[t]},this.createJid(s)),{chatId:s,markedChatUnread:!0}}catch(t){throw this.logger.error("line 2922"),new N({markedChatUnread:!1,message:["An error occurred while marked unread the chat. Open a calling.",t.toString()]})}}async deleteMessage(e){try{return await this.client.sendMessage(e.remoteJid,{delete:e})}catch(t){throw this.logger.error("line 2934"),new N("Error while deleting message for everyone",t?.toString())}}async getBase64FromMediaMessage(e,t=!1){try{let s=e?.message,o=e?.convertToMp4??!1,n=s?.message?s:await this.getMessage(s.key,!0);if(!n)throw"Message not found";for(let g of Oo)n.message[g]&&(n.message=n.message[g].message);let r,a;for(let g of Ro)if(r=n.message[g],r){a=g;break}if(!r)throw"The message is not of the media type";typeof r.mediaKey=="object"&&(n.message=JSON.parse(JSON.stringify(n.message)));let c=await(0,A.downloadMediaMessage)({key:n?.key,message:n?.message},"buffer",{},{logger:(0,it.default)({level:"error"}),reuploadRequest:this.client.updateMediaMessage}),u=(0,A.getContentType)(n.message),d=Tt.default.getExtension(r?.mimetype),l=r?.fileName||`${n.key.id}.${d}`||`${(0,cr.v4)()}.${d}`;if(o&&u==="audioMessage"){let g=await this.processAudioMp4(c.toString("base64"));if(Buffer.isBuffer(g))return{mediaType:a,fileName:l,caption:r.caption,size:{fileLength:r.fileLength,height:r.height,width:r.width},mimetype:"audio/mp4",base64:g,buffer:t?g:null}}return{mediaType:a,fileName:l,caption:r.caption,size:{fileLength:r.fileLength,height:r.height,width:r.width},mimetype:r.mimetype,base64:c.toString("base64"),buffer:t?c:null}}catch(s){throw this.logger.error("line 3026"),this.logger.error(s),new m(s.toString())}}async fetchPrivacySettings(){let e=await this.client.fetchPrivacySettings();return{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}async updatePrivacySettings(e){try{return await this.client.updateReadReceiptsPrivacy(e.readreceipts),await this.client.updateProfilePicturePrivacy(e.profile),await this.client.updateStatusPrivacy(e.status),await this.client.updateOnlinePrivacy(e.online),await this.client.updateLastSeenPrivacy(e.last),await this.client.updateGroupsAddPrivacy(e.groupadd),this.reloadConnection(),{update:"success",data:{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}}catch(t){throw this.logger.error("line 3068"),new N("Error updating privacy settings",t.toString())}}async fetchBusinessProfile(e){try{let t=e?this.createJid(e):this.instance.wuid,s=await this.client.getBusinessProfile(t);return s?{isBusiness:!0,...s}:{isBusiness:!1,message:"Not is business profile",...(await this.whatsappNumber({numbers:[t]}))?.shift()}}catch(t){throw this.logger.error("line 3094"),new N("Error updating profile name",t.toString())}}async updateProfileName(e){try{return await this.client.updateProfileName(e),{update:"success"}}catch(t){throw this.logger.error("line 3105"),new N("Error updating profile name",t.toString())}}async updateProfileStatus(e){try{return await this.client.updateProfileStatus(e),{update:"success"}}catch(t){throw this.logger.error("line 3116"),new N("Error updating profile status",t.toString())}}async updateProfilePicture(e){try{let t;if((0,ne.isURL)(e)){let s=new Date().getTime(),o=`${e}?timestamp=${s}`,n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:ce({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await De.default.get(o,n)).data}else if((0,ne.isBase64)(e))t=Buffer.from(e,"base64");else throw new m('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(this.instance.wuid,t),this.reloadConnection(),{update:"success"}}catch(t){throw this.logger.error("line 3158"),new N("Error updating profile picture",t.toString())}}async removeProfilePicture(){try{return await this.client.removeProfilePicture(this.instance.wuid),this.reloadConnection(),{update:"success"}}catch(e){throw this.logger.error("line 3171"),new N("Error removing profile picture",e.toString())}}async blockUser(e){try{let{number:t}=e,s=(await this.whatsappNumber({numbers:[t]}))?.shift();if(!s.exists&&!(0,A.isJidGroup)(s.jid)&&!s.jid.includes("@broadcast"))throw new m(s);let o=s.jid;return await this.client.updateBlockStatus(o,e.status),{block:"success"}}catch(t){throw this.logger.error("line 3192"),new N("Error blocking user",t.toString())}}async formatUpdateMessage(e){try{let t=await this.getMessage(e.key,!0);return t?.messageType==="conversation"||t?.messageType==="extendedTextMessage"?{text:e.text}:t?.messageType==="imageMessage"?{image:t?.message?.imageMessage,caption:e.text}:t?.messageType==="videoMessage"?{video:t?.message?.videoMessage,caption:e.text}:null}catch(t){throw this.logger.error("line 3223"),this.logger.error(t),new m(t.toString())}}async updateMessage(e){let t=this.createJid(e.number),s=await this.formatUpdateMessage(e);if(!s)throw this.logger.error("Message not compatible"),new m("Message not compatible");try{return await this.client.sendMessage(t,{...s,edit:e.key})}catch(o){throw this.logger.error("line 3245"),this.logger.error(o),new m(o.toString())}}async fetchLabels(){return(await this.prismaRepository.label.findMany({where:{instanceId:this.instanceId}})).map(t=>({color:t.color,name:t.name,id:t.labelId,predefinedId:t.predefinedId}))}async handleLabel(e){let t=await this.whatsappNumber({numbers:[e.number]});if(t.length===0)throw new _("Number not found");let s=t[0];if(!s.exists)throw new _("Number is not on WhatsApp");try{if(e.action==="add")return await this.client.addChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,add:!0};if(e.action==="remove")return await this.client.removeChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,remove:!0}}catch(o){throw this.logger.error("line 3288"),new m(`Unable to ${e.action} label to chat`,o.toString())}}async updateGroupMetadataCache(e){try{let t=await this.client.groupMetadata(e),s=this.configService.get("CACHE");return(s?.REDIS?.ENABLED&&s?.REDIS?.URI!==""||s?.LOCAL?.ENABLED)&&(this.logger.verbose(`Updating cache for group: ${e}`),await Ln.set(e,{timestamp:Date.now(),data:t})),t}catch(t){return this.logger.error("line 3310"),this.logger.error(t),null}}async getGroupMetadataCache(e){if(!(0,A.isJidGroup)(e))return null;let t=S.get("CACHE");if(t?.REDIS?.ENABLED&&t?.REDIS?.URI!==""||t?.LOCAL?.ENABLED){if(await Ln?.has(e)){console.log(`Cache request for group: ${e}`);let s=await Ln.get(e);return Date.now()-s.timestamp>36e5&&await this.updateGroupMetadataCache(e),s.data}return console.log(`Cache request for group: ${e} - not found`),await this.updateGroupMetadataCache(e)}return await this.findGroup({groupJid:e},"inner")}async createGroup(e){try{let t=(await this.whatsappNumber({numbers:e.participants})).filter(n=>n.exists).map(n=>n.jid),{id:s}=await this.client.groupCreate(e.subject,t);return e?.description&&await this.client.groupUpdateDescription(s,e.description),e?.promoteParticipants&&await this.updateGParticipant({groupJid:s,action:"promote",participants:t}),await this.client.groupMetadata(s)}catch(t){throw this.logger.error("line 3363"),this.logger.error(t),new N("Error creating group",t.toString())}}async updateGroupPicture(e){try{let t;if((0,ne.isURL)(e.image)){let s=new Date().getTime(),o=`${e.image}?timestamp=${s}`,n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:ce({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await De.default.get(o,n)).data}else if((0,ne.isBase64)(e.image))t=Buffer.from(e.image,"base64");else throw new m('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(e.groupJid,t),{update:"success"}}catch(t){throw this.logger.error("line 3403"),new N("Error update group picture",t.toString())}}async updateGroupSubject(e){try{return await this.client.groupUpdateSubject(e.groupJid,e.subject),{update:"success"}}catch(t){throw this.logger.error("line 3414"),new N("Error updating group subject",t.toString())}}async updateGroupDescription(e){try{return await this.client.groupUpdateDescription(e.groupJid,e.description),{update:"success"}}catch(t){throw this.logger.error("line 3425"),new N("Error updating group description",t.toString())}}async findGroup(e,t="out"){try{let s=await this.client.groupMetadata(e.groupJid);if(!s)return this.logger.error("Group not found"),null;let o=await this.profilePicture(s.id);return{id:s.id,subject:s.subject,subjectOwner:s.subjectOwner,subjectTime:s.subjectTime,pictureUrl:o.profilePictureUrl,size:s.participants.length,creation:s.creation,owner:s.owner,desc:s.desc,descId:s.descId,restrict:s.restrict,announce:s.announce,participants:s.participants}}catch(s){if(t==="inner")return;throw this.logger.error("line 3460"),new _("Error fetching group",s.toString())}}async fetchAllGroups(e){let t=Object.values(await this?.client?.groupFetchAllParticipating()),s=[];for(let o of t){let n=await this.profilePicture(o.id),r={id:o.id,subject:o.subject,subjectOwner:o.subjectOwner,subjectTime:o.subjectTime,pictureUrl:n?.profilePictureUrl,size:o.participants.length,creation:o.creation,owner:o.owner,desc:o.desc,descId:o.descId,restrict:o.restrict,announce:o.announce};e.getParticipants=="true"&&(r.participants=o.participants),s=[...s,r]}return s}async inviteCode(e){try{let t=await this.client.groupInviteCode(e.groupJid);return{inviteUrl:`https://chat.whatsapp.com/${t}`,inviteCode:t}}catch(t){throw this.logger.error("line 3502"),new _("No invite code",t.toString())}}async inviteInfo(e){try{return await this.client.groupGetInviteInfo(e.inviteCode)}catch{throw this.logger.error("line 3511"),new _("No invite info",e.inviteCode)}}async sendInvite(e){try{let s=(await this.inviteCode({groupJid:e.groupJid})).inviteUrl,o=e.numbers.map(c=>this.createJid(c)),a={conversation:`${e.description??""}
234
235 ${s}`};for await(let c of o)await this.sendMessageWithTyping(c,a);return{send:!0,inviteUrl:s}}catch{throw this.logger.error("line 3537"),new _("No send invite")}}async acceptInviteCode(e){try{return{accepted:!0,groupJid:await this.client.groupAcceptInvite(e.inviteCode)}}catch(t){throw this.logger.error("line 3547"),new _("Accept invite error",t.toString())}}async revokeInviteCode(e){try{return{revoked:!0,inviteCode:await this.client.groupRevokeInvite(e.groupJid)}}catch(t){throw this.logger.error("line 3557"),new _("Revoke error",t.toString())}}async findParticipants(e){try{let t=(await this.client.groupMetadata(e.groupJid)).participants,s=await this.prismaRepository.contact.findMany({where:{instanceId:this.instanceId,remoteJid:{in:t.map(r=>r.id)}}}),o=t.map(r=>{let a=s.find(c=>c.remoteJid===r.id);return{...r,name:r.name??a?.pushName,imgUrl:r.imgUrl??a?.profilePicUrl}}),n=o.filter(r=>r.id.includes("@s.whatsapp"));return n&&await $e(n.map(r=>({remoteJid:r.id}))),{participants:o}}catch(t){throw console.error(t),this.logger.error("line 3583"),new _("No participants",t.toString())}}async updateGParticipant(e){try{let t=e.participants.map(o=>this.createJid(o));return{updateParticipants:await this.client.groupParticipantsUpdate(e.groupJid,t,e.action)}}catch(t){throw this.logger.error("line 3598"),new m("Error updating participants",t.toString())}}async updateGSetting(e){try{return{updateSetting:await this.client.groupSettingUpdate(e.groupJid,e.action)}}catch(t){throw this.logger.error("line 3608"),new m("Error updating setting",t.toString())}}async toggleEphemeral(e){try{return await this.client.groupToggleEphemeral(e.groupJid,e.expiration),{success:!0}}catch(t){throw this.logger.error("line 3618"),new m("Error updating setting",t.toString())}}async leaveGroup(e){try{return await this.client.groupLeave(e.groupJid),{groupJid:e.groupJid,leave:!0}}catch(t){throw this.logger.error("line 3628"),new m("Unable to leave the group",t.toString())}}async templateMessage(){throw new Error("Method not available in the Baileys service")}prepareMessage(e){let t=e?.message[(0,A.getContentType)(e.message)],s={key:e.key,pushName:e.pushName,message:{...e.message},contextInfo:t?.contextInfo,messageType:(0,A.getContentType)(e.message)||"unknown",messageTimestamp:e.messageTimestamp,instanceId:this.instanceId,source:(0,A.getDevice)(e.key.id)};return s.message.extendedTextMessage&&(s.messageType="conversation",s.message.conversation=s.message.extendedTextMessage.text,delete s.message.extendedTextMessage),s}};var Ne=class{constructor(i,e){this.prisma=i,this.monitor=e}set prisma(i){this.prismaRepository=i}get prisma(){return this.prismaRepository}set monitor(i){this.waMonitor=i}get monitor(){return this.waMonitor}init(i,e){if(!i.token&&i.integration===D.WHATSAPP_BUSINESS)throw new m("token is required");return i.integration===D.WHATSAPP_BUSINESS?new os(e.configService,e.eventEmitter,e.prismaRepository,e.cache,e.chatwootCache,e.baileysCache,e.providerFiles):i.integration===D.EVOLUTION?new is(e.configService,e.eventEmitter,e.prismaRepository,e.cache,e.chatwootCache,e.baileysCache,e.providerFiles):i.integration===D.WHATSAPP_BAILEYS?new Ts(e.configService,e.eventEmitter,e.prismaRepository,e.cache,e.chatwootCache,e.baileysCache,e.providerFiles):null}};var Cs=class extends Ne{constructor(e,t){super(e,t);this.logger=new I("EvolutionController")}async receiveWebhook(e){let t=e.numberId;if(!t){this.logger.error("WebhookService -> receiveWebhookEvolution -> numberId not found");return}let s=await this.prismaRepository.instance.findFirst({where:{number:t}});if(!s){this.logger.error("WebhookService -> receiveWebhook -> instance not found");return}return await this.waMonitor.waInstances[s.name].connectToWhatsapp(e),{status:"success"}}};var pr=C(require("axios"));var vs=class extends Ne{constructor(e,t){super(e,t);this.logger=new I("MetaController")}async receiveWebhook(e){if(e.object==="whatsapp_business_account"){if(e.entry[0]?.changes[0]?.field==="message_template_status_update"){let t=await this.prismaRepository.template.findFirst({where:{templateId:`${e.entry[0].changes[0].value.message_template_id}`}});if(!t){console.log("template not found");return}let{webhookUrl:s}=t;await pr.default.post(s,e.entry[0].changes[0].value,{headers:{"Content-Type":"application/json"}});return}e.entry?.forEach(async t=>{let s=t.changes[0].value.metadata.phone_number_id;if(!s)return this.logger.error("WebhookService -> receiveWebhookMeta -> numberId not found"),{status:"success"};let o=await this.prismaRepository.instance.findFirst({where:{number:s}});return o?(await this.waMonitor.waInstances[o.name].connectToWhatsapp(e),{status:"success"}):(this.logger.error("WebhookService -> receiveWebhookMeta -> instance not found"),{status:"success"})})}return{status:"success"}}};function lr(p){return p.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function ur(p,i){let e=i.split(" ").reduce((s,o)=>{let[n,...r]=o.split(":"),a=r.join(":");return s[n]||(s[n]=[]),s[n].push(a),s},{}),t=lr(p);return Object.entries(e).every(([s,o])=>o.some(n=>n.split(",").every(a=>{let c=lr(a);switch(s.toLowerCase()){case"contains":return t.includes(c);case"notcontains":return!t.includes(c);case"startswith":return t.startsWith(c);case"endswith":return t.endsWith(c);case"exact":return t===c;default:return!1}})))}var dr=async(p,i,e,t)=>{let s=await p.findFirst({where:{enabled:!0,triggerType:"all",instanceId:t}});if(s)return s;let o=await p.findMany({where:{enabled:!0,triggerType:"advanced",instanceId:t}});for(let f of o)if(ur(e,f.triggerValue))return f;let n=await p.findFirst({where:{enabled:!0,triggerType:"keyword",triggerOperator:"equals",triggerValue:e,instanceId:t}});if(n)return n;let r=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"regex",instanceId:t}}),a=null;for(let f of r)if(new RegExp(f.triggerValue).test(e)){a=f;break}if(a)return a;let c=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"startsWith",instanceId:t}}),u=null;for(let f of c)if(e.startsWith(f.triggerValue)){u=f;break}if(u)return u;let d=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"endsWith",instanceId:t}}),l=null;for(let f of d)if(e.endsWith(f.triggerValue)){l=f;break}if(l)return l;let g=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"contains",instanceId:t}}),h=null;for(let f of g)if(e.includes(f.triggerValue)){h=f;break}if(h)return h;let y=await i.findFirst({where:{instanceId:t}});if(y?.openaiIdFallback){let f=await p.findFirst({where:{id:y.openaiIdFallback}});if(f)return f}return null};var K=class{constructor(i,e){this.logger=new I("ChatbotController");this.prisma=i,this.monitor=e}set prisma(i){this.prismaRepository=i}get prisma(){return this.prismaRepository}set monitor(i){this.waMonitor=i}get monitor(){return this.waMonitor}async emit({instance:i,remoteJid:e,msg:t,pushName:s,isIntegration:o=!1}){let n={instance:i,remoteJid:e,msg:t,pushName:s,isIntegration:o};await z.emit(n),await Y.emit(n),await $.emit(n),await Q.emit(n),await X.emit(n)}processDebounce(i,e,t,s,o){i[t]?(i[t].message+=`
→ 236 ${e}`,this.logger.log("message debounced: "+i[t].message),clearTimeout(i[t].timeoutId)):i[t]={message:e,timeoutId:null},i[t].timeoutId=setTimeout(()=>{let n=i[t].message;this.logger.log("Debounce complete. Processing message: "+n),delete i[t],o(n)},s*1e3)}checkIgnoreJids(i,e){if(i&&i.length>0){let t=!1,s=!1;return i.includes("@g.us")&&(t=!0),i.includes("@s.whatsapp.net")&&(s=!0),t&&e.endsWith("@g.us")?(this.logger.warn("Ignoring message from group: "+e),!0):s&&e.endsWith("@s.whatsapp.net")?(this.logger.warn("Ignoring message from contact: "+e),!0):i.includes(e)?(this.logger.warn("Ignoring message from jid: "+e),!0):!1}return!1}async getSession(i,e){let t=await this.prismaRepository.integrationSession.findFirst(
Foreign key constraint failed on the field: `OpenaiSetting_openaiCredsId_fkey (index)`
at Ln.handleRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7753)
at Ln.handleAndLogRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7061)
at Ln.request (/evolution/node_modules/@prisma/client/runtime/library.js:121:6745)
at async l (/evolution/node_modules/@prisma/client/runtime/library.js:130:9633)
at async ks.deleteCreds (/evolution/dist/main.js:236:45512)
at async gi.dataValidate (/evolution/dist/main.js:236:98590)
at async /evolution/dist/main.js:236:135501 {
code: 'P2003',
clientVersion: '5.19.1',
{
modelName: 'OpenaiCreds',
field_name: 'OpenaiSetting_openaiCredsId_fkey (index)'
}
}
@DavidsonGomes estou incluindo mais um bug nessa ISSUE, versão 2.1.1:
Não é possível incluir a mesma credencial em instâncias distintas, API retorna erro 500 Internal Server Error.
No log, eu entendi que é exatamente isso, ele não deixa incluir uma mesma credencial em sessões diferentes. Segue log abaixo:
[Evolution API] v2.1.1 170 - Thu Oct 10 2024 13:32:37 ERROR [OpenaiController] [object]
PrismaClientKnownRequestError:
Invalid this.prismaRepository.integrationSession.findFirst() invocation in
/evolution/dist/main.js:236:44736
233 END:VCARD,n};return e.contact.length===1?t.contactMessage={displayName:e.contact[0].fullName,vcard:s(e.contact[0])}:t.contactsArrayMessage={displayName:${e.contact.length} contacts,contacts:e.contact.map(o=>({displayName:o.fullName,vcard:s(o)}))},await this.sendMessageWithTyping(e.number,{...t},{})}async reactionMessage(e){return await this.sendMessageWithTyping(e.key.remoteJid,{reactionMessage:{key:e.key,text:e.reaction}})}async whatsappNumber(e){let t={groups:[],broadcast:[],users:[]};e.numbers.forEach(l=>{let g=this.createJid(l);(0,A.isJidGroup)(g)?t.groups.push({number:l,jid:g}):g==="status@broadcast"?t.broadcast.push({number:l,jid:g}):t.users.push({number:l,jid:g})});let s=[];s.push(...t.broadcast.map(({jid:l,number:g})=>new tt(l,!1,g)));let o=await Promise.all(t.groups.map(async({jid:l,number:g})=>{let h=await this.findGroup({groupJid:l},"inner");return h||new tt(l,!1,g),new tt(h.id,!!h?.id,g,h?.subject)}));s.push(...o);let n=await this.prismaRepository.contact.findMany({where:{instanceId:this.instanceId,remoteJid:{in:t.users.map(({jid:l})=>l)}}}),r=t.users.map(({jid:l})=>l.replace("+","")),a=await Ko(r),c=r.filter(l=>!a.some(g=>g.jidOptions.includes(l))),u=await this.client.onWhatsApp(...c),d=await Promise.all(t.users.map(async l=>{let g=null,h=a.find(f=>f.jidOptions.includes(l.jid.replace("+","")));if(h)return{exists:!0,jid:h.remoteJid,name:n.find(f=>f.remoteJid===h.remoteJid)?.pushName,number:l.number};if(l.number.startsWith("55")){let f=l.number.slice(4,5)==="9"&&l.number.length===13?l.number:${l.number.slice(0,4)}9${l.number.slice(4)},w=l.number.length===12?l.number:l.number.slice(0,4)+l.number.slice(5);g=u.find(M=>M.jid===${f}@s.whatsapp.net||M.jid===${w}@s.whatsapp.net)}if(!g&&(l.number.startsWith("52")||l.number.startsWith("54"))){let f="";l.number.startsWith("52")&&(f="1"),l.number.startsWith("54")&&(f="9");let w=l.number.slice(2,3)===f&&l.number.length===13?l.number:${l.number.slice(0,2)}${f}${l.number.slice(2)},M=l.number.length===12?l.number:l.number.slice(0,2)+l.number.slice(3);g=u.find(b=>b.jid===${w}@s.whatsapp.net||b.jid===${M}@s.whatsapp.net)}g||(g=u.find(f=>f.jid===l.jid));let y=g?.jid||l.jid;return{exists:!!g?.exists,jid:y,name:n.find(f=>f.remoteJid===y)?.pushName,number:l.number}}));return await $e(d.filter(l=>l.exists).map(l=>({remoteJid:l.jid}))),s.push(...d),s}async markMessageAsRead(e){try{let t=[];return e.readMessages.forEach(s=>{((0,A.isJidGroup)(s.remoteJid)||(0,A.isJidUser)(s.remoteJid))&&t.push({remoteJid:s.remoteJid,fromMe:s.fromMe,id:s.id})}),await this.client.readMessages(t),{message:"Read messages",read:"success"}}catch(t){throw this.logger.error("line 2818"),new N("Read messages fail",t.toString())}}async getLastMessage(e){let t={key:{remoteJid:e},instanceId:this.instance.id},s=await this.prismaRepository.message.findMany({where:t,orderBy:{messageTimestamp:"desc"},take:1});if(s.length===0)throw new ("Messages not found");let o=s.pop();for(let n of s)n.messageTimestamp>=o.messageTimestamp&&(o=n);return o}async archiveChat(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new ("Last message not found");return await this.client.chatModify({archive:e.archive,lastMessages:[t]},this.createJid(s)),{chatId:s,archived:!0}}catch(t){throw this.logger.error("line 2884"),new N({archived:!1,message:["An error occurred while archiving the chat. Open a calling.",t.toString()]})}}async markChatUnread(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new ("Last message not found");return await this.client.chatModify({markRead:!1,lastMessages:[t]},this.createJid(s)),{chatId:s,markedChatUnread:!0}}catch(t){throw this.logger.error("line 2922"),new N({markedChatUnread:!1,message:["An error occurred while marked unread the chat. Open a calling.",t.toString()]})}}async deleteMessage(e){try{return await this.client.sendMessage(e.remoteJid,{delete:e})}catch(t){throw this.logger.error("line 2934"),new N("Error while deleting message for everyone",t?.toString())}}async getBase64FromMediaMessage(e,t=!1){try{let s=e?.message,o=e?.convertToMp4??!1,n=s?.message?s:await this.getMessage(s.key,!0);if(!n)throw"Message not found";for(let g of Oo)n.message[g]&&(n.message=n.message[g].message);let r,a;for(let g of Ro)if(r=n.message[g],r){a=g;break}if(!r)throw"The message is not of the media type";typeof r.mediaKey=="object"&&(n.message=JSON.parse(JSON.stringify(n.message)));let c=await(0,A.downloadMediaMessage)({key:n?.key,message:n?.message},"buffer",{},{logger:(0,it.default)({level:"error"}),reuploadRequest:this.client.updateMediaMessage}),u=(0,A.getContentType)(n.message),d=Tt.default.getExtension(r?.mimetype),l=r?.fileName||${n.key.id}.${d}||${(0,cr.v4)()}.${d};if(o&&u==="audioMessage"){let g=await this.processAudioMp4(c.toString("base64"));if(Buffer.isBuffer(g))return{mediaType:a,fileName:l,caption:r.caption,size:{fileLength:r.fileLength,height:r.height,width:r.width},mimetype:"audio/mp4",base64:g,buffer:t?g:null}}return{mediaType:a,fileName:l,caption:r.caption,size:{fileLength:r.fileLength,height:r.height,width:r.width},mimetype:r.mimetype,base64:c.toString("base64"),buffer:t?c:null}}catch(s){throw this.logger.error("line 3026"),this.logger.error(s),new m(s.toString())}}async fetchPrivacySettings(){let e=await this.client.fetchPrivacySettings();return{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}async updatePrivacySettings(e){try{return await this.client.updateReadReceiptsPrivacy(e.readreceipts),await this.client.updateProfilePicturePrivacy(e.profile),await this.client.updateStatusPrivacy(e.status),await this.client.updateOnlinePrivacy(e.online),await this.client.updateLastSeenPrivacy(e.last),await this.client.updateGroupsAddPrivacy(e.groupadd),this.reloadConnection(),{update:"success",data:{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}}catch(t){throw this.logger.error("line 3068"),new N("Error updating privacy settings",t.toString())}}async fetchBusinessProfile(e){try{let t=e?this.createJid(e):this.instance.wuid,s=await this.client.getBusinessProfile(t);return s?{isBusiness:!0,...s}:{isBusiness:!1,message:"Not is business profile",...(await this.whatsappNumber({numbers:[t]}))?.shift()}}catch(t){throw this.logger.error("line 3094"),new N("Error updating profile name",t.toString())}}async updateProfileName(e){try{return await this.client.updateProfileName(e),{update:"success"}}catch(t){throw this.logger.error("line 3105"),new N("Error updating profile name",t.toString())}}async updateProfileStatus(e){try{return await this.client.updateProfileStatus(e),{update:"success"}}catch(t){throw this.logger.error("line 3116"),new N("Error updating profile status",t.toString())}}async updateProfilePicture(e){try{let t;if((0,ne.isURL)(e)){let s=new Date().getTime(),o=${e}?timestamp=${s},n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:ce({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await De.default.get(o,n)).data}else if((0,ne.isBase64)(e))t=Buffer.from(e,"base64");else throw new m('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(this.instance.wuid,t),this.reloadConnection(),{update:"success"}}catch(t){throw this.logger.error("line 3158"),new N("Error updating profile picture",t.toString())}}async removeProfilePicture(){try{return await this.client.removeProfilePicture(this.instance.wuid),this.reloadConnection(),{update:"success"}}catch(e){throw this.logger.error("line 3171"),new N("Error removing profile picture",e.toString())}}async blockUser(e){try{let{number:t}=e,s=(await this.whatsappNumber({numbers:[t]}))?.shift();if(!s.exists&&!(0,A.isJidGroup)(s.jid)&&!s.jid.includes("@broadcast"))throw new m(s);let o=s.jid;return await this.client.updateBlockStatus(o,e.status),{block:"success"}}catch(t){throw this.logger.error("line 3192"),new N("Error blocking user",t.toString())}}async formatUpdateMessage(e){try{let t=await this.getMessage(e.key,!0);return t?.messageType==="conversation"||t?.messageType==="extendedTextMessage"?{text:e.text}:t?.messageType==="imageMessage"?{image:t?.message?.imageMessage,caption:e.text}:t?.messageType==="videoMessage"?{video:t?.message?.videoMessage,caption:e.text}:null}catch(t){throw this.logger.error("line 3223"),this.logger.error(t),new m(t.toString())}}async updateMessage(e){let t=this.createJid(e.number),s=await this.formatUpdateMessage(e);if(!s)throw this.logger.error("Message not compatible"),new m("Message not compatible");try{return await this.client.sendMessage(t,{...s,edit:e.key})}catch(o){throw this.logger.error("line 3245"),this.logger.error(o),new m(o.toString())}}async fetchLabels(){return(await this.prismaRepository.label.findMany({where:{instanceId:this.instanceId}})).map(t=>({color:t.color,name:t.name,id:t.labelId,predefinedId:t.predefinedId}))}async handleLabel(e){let t=await this.whatsappNumber({numbers:[e.number]});if(t.length===0)throw new ("Number not found");let s=t[0];if(!s.exists)throw new ("Number is not on WhatsApp");try{if(e.action==="add")return await this.client.addChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,add:!0};if(e.action==="remove")return await this.client.removeChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,remove:!0}}catch(o){throw this.logger.error("line 3288"),new m(Unable to ${e.action} label to chat,o.toString())}}async updateGroupMetadataCache(e){try{let t=await this.client.groupMetadata(e),s=this.configService.get("CACHE");return(s?.REDIS?.ENABLED&&s?.REDIS?.URI!==""||s?.LOCAL?.ENABLED)&&(this.logger.verbose(Updating cache for group: ${e}),await Ln.set(e,{timestamp:Date.now(),data:t})),t}catch(t){return this.logger.error("line 3310"),this.logger.error(t),null}}async getGroupMetadataCache(e){if(!(0,A.isJidGroup)(e))return null;let t=S.get("CACHE");if(t?.REDIS?.ENABLED&&t?.REDIS?.URI!==""||t?.LOCAL?.ENABLED){if(await Ln?.has(e)){console.log(Cache request for group: ${e});let s=await Ln.get(e);return Date.now()-s.timestamp>36e5&&await this.updateGroupMetadataCache(e),s.data}return console.log(Cache request for group: ${e} - not found),await this.updateGroupMetadataCache(e)}return await this.findGroup({groupJid:e},"inner")}async createGroup(e){try{let t=(await this.whatsappNumber({numbers:e.participants})).filter(n=>n.exists).map(n=>n.jid),{id:s}=await this.client.groupCreate(e.subject,t);return e?.description&&await this.client.groupUpdateDescription(s,e.description),e?.promoteParticipants&&await this.updateGParticipant({groupJid:s,action:"promote",participants:t}),await this.client.groupMetadata(s)}catch(t){throw this.logger.error("line 3363"),this.logger.error(t),new N("Error creating group",t.toString())}}async updateGroupPicture(e){try{let t;if((0,ne.isURL)(e.image)){let s=new Date().getTime(),o=${e.image}?timestamp=${s},n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:ce({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await De.default.get(o,n)).data}else if((0,ne.isBase64)(e.image))t=Buffer.from(e.image,"base64");else throw new m('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(e.groupJid,t),{update:"success"}}catch(t){throw this.logger.error("line 3403"),new N("Error update group picture",t.toString())}}async updateGroupSubject(e){try{return await this.client.groupUpdateSubject(e.groupJid,e.subject),{update:"success"}}catch(t){throw this.logger.error("line 3414"),new N("Error updating group subject",t.toString())}}async updateGroupDescription(e){try{return await this.client.groupUpdateDescription(e.groupJid,e.description),{update:"success"}}catch(t){throw this.logger.error("line 3425"),new N("Error updating group description",t.toString())}}async findGroup(e,t="out"){try{let s=await this.client.groupMetadata(e.groupJid);if(!s)return this.logger.error("Group not found"),null;let o=await this.profilePicture(s.id);return{id:s.id,subject:s.subject,subjectOwner:s.subjectOwner,subjectTime:s.subjectTime,pictureUrl:o.profilePictureUrl,size:s.participants.length,creation:s.creation,owner:s.owner,desc:s.desc,descId:s.descId,restrict:s.restrict,announce:s.announce,participants:s.participants}}catch(s){if(t==="inner")return;throw this.logger.error("line 3460"),new ("Error fetching group",s.toString())}}async fetchAllGroups(e){let t=Object.values(await this?.client?.groupFetchAllParticipating()),s=[];for(let o of t){let n=await this.profilePicture(o.id),r={id:o.id,subject:o.subject,subjectOwner:o.subjectOwner,subjectTime:o.subjectTime,pictureUrl:n?.profilePictureUrl,size:o.participants.length,creation:o.creation,owner:o.owner,desc:o.desc,descId:o.descId,restrict:o.restrict,announce:o.announce};e.getParticipants=="true"&&(r.participants=o.participants),s=[...s,r]}return s}async inviteCode(e){try{let t=await this.client.groupInviteCode(e.groupJid);return{inviteUrl:https://chat.whatsapp.com/${t},inviteCode:t}}catch(t){throw this.logger.error("line 3502"),new ("No invite code",t.toString())}}async inviteInfo(e){try{return await this.client.groupGetInviteInfo(e.inviteCode)}catch{throw this.logger.error("line 3511"),new ("No invite info",e.inviteCode)}}async sendInvite(e){try{let s=(await this.inviteCode({groupJid:e.groupJid})).inviteUrl,o=e.numbers.map(c=>this.createJid(c)),a={conversation:${e.description??""}
234
235 ${s}};for await(let c of o)await this.sendMessageWithTyping(c,a);return{send:!0,inviteUrl:s}}catch{throw this.logger.error("line 3537"),new ("No send invite")}}async acceptInviteCode(e){try{return{accepted:!0,groupJid:await this.client.groupAcceptInvite(e.inviteCode)}}catch(t){throw this.logger.error("line 3547"),new ("Accept invite error",t.toString())}}async revokeInviteCode(e){try{return{revoked:!0,inviteCode:await this.client.groupRevokeInvite(e.groupJid)}}catch(t){throw this.logger.error("line 3557"),new ("Revoke error",t.toString())}}async findParticipants(e){try{let t=(await this.client.groupMetadata(e.groupJid)).participants,s=await this.prismaRepository.contact.findMany({where:{instanceId:this.instanceId,remoteJid:{in:t.map(r=>r.id)}}}),o=t.map(r=>{let a=s.find(c=>c.remoteJid===r.id);return{...r,name:r.name??a?.pushName,imgUrl:r.imgUrl??a?.profilePicUrl}}),n=o.filter(r=>r.id.includes("@s.whatsapp"));return n&&await $e(n.map(r=>({remoteJid:r.id}))),{participants:o}}catch(t){throw console.error(t),this.logger.error("line 3583"),new ("No participants",t.toString())}}async updateGParticipant(e){try{let t=e.participants.map(o=>this.createJid(o));return{updateParticipants:await this.client.groupParticipantsUpdate(e.groupJid,t,e.action)}}catch(t){throw this.logger.error("line 3598"),new m("Error updating participants",t.toString())}}async updateGSetting(e){try{return{updateSetting:await this.client.groupSettingUpdate(e.groupJid,e.action)}}catch(t){throw this.logger.error("line 3608"),new m("Error updating setting",t.toString())}}async toggleEphemeral(e){try{return await this.client.groupToggleEphemeral(e.groupJid,e.expiration),{success:!0}}catch(t){throw this.logger.error("line 3618"),new m("Error updating setting",t.toString())}}async leaveGroup(e){try{return await this.client.groupLeave(e.groupJid),{groupJid:e.groupJid,leave:!0}}catch(t){throw this.logger.error("line 3628"),new m("Unable to leave the group",t.toString())}}async templateMessage(){throw new Error("Method not available in the Baileys service")}prepareMessage(e){let t=e?.message[(0,A.getContentType)(e.message)],s={key:e.key,pushName:e.pushName,message:{...e.message},contextInfo:t?.contextInfo,messageType:(0,A.getContentType)(e.message)||"unknown",messageTimestamp:e.messageTimestamp,instanceId:this.instanceId,source:(0,A.getDevice)(e.key.id)};return s.message.extendedTextMessage&&(s.messageType="conversation",s.message.conversation=s.message.extendedTextMessage.text,delete s.message.extendedTextMessage),s}};var Ne=class{constructor(i,e){this.prisma=i,this.monitor=e}set prisma(i){this.prismaRepository=i}get prisma(){return this.prismaRepository}set monitor(i){this.waMonitor=i}get monitor(){return this.waMonitor}init(i,e){if(!i.token&&i.integration===D.WHATSAPP_BUSINESS)throw new m("token is required");return i.integration===D.WHATSAPP_BUSINESS?new os(e.configService,e.eventEmitter,e.prismaRepository,e.cache,e.chatwootCache,e.baileysCache,e.providerFiles):i.integration===D.EVOLUTION?new is(e.configService,e.eventEmitter,e.prismaRepository,e.cache,e.chatwootCache,e.baileysCache,e.providerFiles):i.integration===D.WHATSAPP_BAILEYS?new Ts(e.configService,e.eventEmitter,e.prismaRepository,e.cache,e.chatwootCache,e.baileysCache,e.providerFiles):null}};var Cs=class extends Ne{constructor(e,t){super(e,t);this.logger=new I("EvolutionController")}async receiveWebhook(e){let t=e.numberId;if(!t){this.logger.error("WebhookService -> receiveWebhookEvolution -> numberId not found");return}let s=await this.prismaRepository.instance.findFirst({where:{number:t}});if(!s){this.logger.error("WebhookService -> receiveWebhook -> instance not found");return}return await this.waMonitor.waInstances[s.name].connectToWhatsapp(e),{status:"success"}}};var pr=C(require("axios"));var vs=class extends Ne{constructor(e,t){super(e,t);this.logger=new I("MetaController")}async receiveWebhook(e){if(e.object==="whatsapp_business_account"){if(e.entry[0]?.changes[0]?.field==="message_template_status_update"){let t=await this.prismaRepository.template.findFirst({where:{templateId:${e.entry[0].changes[0].value.message_template_id}}});if(!t){console.log("template not found");return}let{webhookUrl:s}=t;await pr.default.post(s,e.entry[0].changes[0].value,{headers:{"Content-Type":"application/json"}});return}e.entry?.forEach(async t=>{let s=t.changes[0].value.metadata.phone_number_id;if(!s)return this.logger.error("WebhookService -> receiveWebhookMeta -> numberId not found"),{status:"success"};let o=await this.prismaRepository.instance.findFirst({where:{number:s}});return o?(await this.waMonitor.waInstances[o.name].connectToWhatsapp(e),{status:"success"}):(this.logger.error("WebhookService -> receiveWebhookMeta -> instance not found"),{status:"success"})})}return{status:"success"}}};function lr(p){return p.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function ur(p,i){let e=i.split(" ").reduce((s,o)=>{let[n,...r]=o.split(":"),a=r.join(":");return s[n]||(s[n]=[]),s[n].push(a),s},{}),t=lr(p);return Object.entries(e).every(([s,o])=>o.some(n=>n.split(",").every(a=>{let c=lr(a);switch(s.toLowerCase()){case"contains":return t.includes(c);case"notcontains":return!t.includes(c);case"startswith":return t.startsWith(c);case"endswith":return t.endsWith(c);case"exact":return t===c;default:return!1}})))}var dr=async(p,i,e,t)=>{let s=await p.findFirst({where:{enabled:!0,triggerType:"all",instanceId:t}});if(s)return s;let o=await p.findMany({where:{enabled:!0,triggerType:"advanced",instanceId:t}});for(let f of o)if(ur(e,f.triggerValue))return f;let n=await p.findFirst({where:{enabled:!0,triggerType:"keyword",triggerOperator:"equals",triggerValue:e,instanceId:t}});if(n)return n;let r=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"regex",instanceId:t}}),a=null;for(let f of r)if(new RegExp(f.triggerValue).test(e)){a=f;break}if(a)return a;let c=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"startsWith",instanceId:t}}),u=null;for(let f of c)if(e.startsWith(f.triggerValue)){u=f;break}if(u)return u;let d=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"endsWith",instanceId:t}}),l=null;for(let f of d)if(e.endsWith(f.triggerValue)){l=f;break}if(l)return l;let g=await p.findMany({where:{enabled:!0,triggerType:"keyword",triggerOperator:"contains",instanceId:t}}),h=null;for(let f of g)if(e.includes(f.triggerValue)){h=f;break}if(h)return h;let y=await i.findFirst({where:{instanceId:t}});if(y?.openaiIdFallback){let f=await p.findFirst({where:{id:y.openaiIdFallback}});if(f)return f}return null};var K=class{constructor(i,e){this.logger=new I("ChatbotController");this.prisma=i,this.monitor=e}set prisma(i){this.prismaRepository=i}get prisma(){return this.prismaRepository}set monitor(i){this.waMonitor=i}get monitor(){return this.waMonitor}async emit({instance:i,remoteJid:e,msg:t,pushName:s,isIntegration:o=!1}){let n={instance:i,remoteJid:e,msg:t,pushName:s,isIntegration:o};await z.emit(n),await Y.emit(n),await $.emit(n),await Q.emit(n),await X.emit(n)}processDebounce(i,e,t,s,o){i[t]?(i[t].message+=
→ 236 ${e},this.logger.log("message debounced: "+i[t].message),clearTimeout(i[t].timeoutId)):i[t]={message:e,timeoutId:null},i[t].timeoutId=setTimeout(()=>{let n=i[t].message;this.logger.log("Debounce complete. Processing message: "+n),delete i[t],o(n)},s*1e3)}checkIgnoreJids(i,e){if(i&&i.length>0){let t=!1,s=!1;return i.includes("@g.us")&&(t=!0),i.includes("@s.whatsapp.net")&&(s=!0),t&&e.endsWith("@g.us")?(this.logger.warn("Ignoring message from group: "+e),!0):s&&e.endsWith("@s.whatsapp.net")?(this.logger.warn("Ignoring message from contact: "+e),!0):i.includes(e)?(this.logger.warn("Ignoring message from jid: "+e),!0):!1}return!1}async getSession(i,e){let t=await this.prismaRepository.integrationSession.findFirst(
Unique constraint failed on the fields: (apiKey)
at Ln.handleRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7753)
at Ln.handleAndLogRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7061)
at Ln.request (/evolution/node_modules/@prisma/client/runtime/library.js:121:6745)
at async l (/evolution/node_modules/@prisma/client/runtime/library.js:130:9633)
at async ks.createOpenaiCreds (/evolution/dist/main.js:236:44709)
at async gi.dataValidate (/evolution/dist/main.js:236:98590)
at async /evolution/dist/main.js:236:135141 {
code: 'P2002',
clientVersion: '5.19.1',
meta: { modelName: 'OpenaiCreds', target: [ 'apiKey' ] }
Up!
Welcome!
What did you do?
What did you expect?
Deletar credencial da OpenAi para inserir uma nova. Só é possível após exclusão da sessão.
What did you observe instead of what you expected?
Deletar credencial da OpenAi.
Screenshots/Videos
No response
Which version of the API are you using?
2.1.0
What is your environment?
Linux
Other environment specifications
No response
If applicable, paste the log output
No response
Additional Notes
Retorno da API: { "status": 500, "error": "Internal Server Error", "response": { "message": "Error deleting openai creds" } }
Erro nos logs: [Evolution API] v2.1.0 163 - Thu Aug 29 2024 10:31:36 ERROR [p] [object]
PrismaClientKnownRequestError: Invalid
this.prismaRepository.contact.findMany()
invocation in /evolution/dist/main.js:214:49547 211 item1.X-ABLabel:Celular 212 END:VCARD,n};return e.contact.length===1?t.contactMessage={displayName:e.contact[0].fullName,vcard:s(e.contact[0])}:t.contactsArrayMessage={displayName:
${e.contact.length} contacts,contacts:e.contact.map(o=>({displayName:o.fullName,vcard:s(o)}))},await this.sendMessageWithTyping(e.number,{...t},{})}async reactionMessage(e){return await this.sendMessageWithTyping(e.key.remoteJid,{reactionMessage:{key:e.key,text:e.reaction}})}async whatsappNumber(e){let t={groups:[],broadcast:[],users:[]};e.numbers.forEach(l=>{let u=this.createJid(l);(0,v.isJidGroup)(u)?t.groups.push({number:l,jid:u}):u==="status@broadcast"?t.broadcast.push({number:l,jid:u}):t.users.push({number:l,jid:u})});let s=[];s.push(...t.broadcast.map(({jid:l,number:u})=>new et(l,!1,u)));let o=await Promise.all(t.groups.map(async({jid:l,number:u})=>{let d=await this.findGroup({groupJid:l},"inner");return d||new et(l,!1,u),new et(d.id,!!d?.id,u,d?.subject)}));s.push(...o);let n=await this.prismaRepository.contact.findMany({where:{instanceId:this.instanceId,remoteJid:{in:t.users.map(({jid:l})=>l)}}}),r=t.users.map(({jid:l})=>l.replace("+","")),a=await this.client.onWhatsApp(...r),c=await Promise.all(t.users.map(async l=>{let u=null;if(l.number.startsWith("55")){let g=l.number.slice(4,5)==="9"&&l.number.length===13?l.number:
${l.number.slice(0,4)}9${l.number.slice(4)},m=l.number.length===12?l.number:l.number.slice(0,4)+l.number.slice(5);u=a.find(y=>y.jid===
${g}@s.whatsapp.net||y.jid===
${m}@s.whatsapp.net)}if(!u&&(l.number.startsWith("52")||l.number.startsWith("54"))){let g="";l.number.startsWith("52")&&(g="1"),l.number.startsWith("54")&&(g="9");let m=l.number.slice(2,3)===g&&l.number.length===13?l.number:
${l.number.slice(0,2)}${g}${l.number.slice(2)},y=l.number.length===12?l.number:l.number.slice(0,2)+l.number.slice(3);u=a.find(f=>f.jid===
${m}@s.whatsapp.net||f.jid===
${y}@s.whatsapp.net)}u||(u=a.find(g=>g.jid===l.jid));let d=u?.jid||l.jid;return{exists:!!u?.exists,jid:d,name:n.find(g=>g.remoteJid===d)?.pushName,number:l.number}}));return s.push(...c),s}async markMessageAsRead(e){try{let t=[];return e.readMessages.forEach(s=>{((0,v.isJidGroup)(s.remoteJid)||(0,v.isJidUser)(s.remoteJid))&&t.push({remoteJid:s.remoteJid,fromMe:s.fromMe,id:s.id})}),await this.client.readMessages(t),{message:"Read messages",read:"success"}}catch(t){throw this.logger.error("line 2818"),new k("Read messages fail",t.toString())}}async getLastMessage(e){let t={key:{remoteJid:e},instanceId:this.instance.id},s=await this.prismaRepository.message.findMany({where:t,orderBy:{messageTimestamp:"desc"},take:1});if(s.length===0)throw new P("Messages not found");let o=s.pop();for(let n of s)n.messageTimestamp>=o.messageTimestamp&&(o=n);return o}async archiveChat(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new P("Last message not found");return await this.client.chatModify({archive:e.archive,lastMessages:[t]},this.createJid(s)),{chatId:s,archived:!0}}catch(t){throw this.logger.error("line 2884"),new k({archived:!1,message:["An error occurred while archiving the chat. Open a calling.",t.toString()]})}}async markChatUnread(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new P("Last message not found");return await this.client.chatModify({markRead:!1,lastMessages:[t]},this.createJid(s)),{chatId:s,markedChatUnread:!0}}catch(t){throw this.logger.error("line 2922"),new k({markedChatUnread:!1,message:["An error occurred while marked unread the chat. Open a calling.",t.toString()]})}}async deleteMessage(e){try{return await this.client.sendMessage(e.remoteJid,{delete:e})}catch(t){throw this.logger.error("line 2934"),new k("Error while deleting message for everyone",t?.toString())}}async getBase64FromMediaMessage(e,t=!1){try{let s=e?.message,o=e?.convertToMp4??!1,n=s?.message?s:await this.getMessage(s.key,!0);if(!n)throw"Message not found";for(let g of To)n.message[g]&&(n.message=n.message[g].message);let r,a;for(let g of Mo)if(r=n.message[g],r){a=g;break}if(!r)throw"The message is not of the media type";typeof r.mediaKey=="object"&&(n.message=JSON.parse(JSON.stringify(n.message)));let c=await(0,v.downloadMediaMessage)({key:n?.key,message:n?.message},"buffer",{},{logger:(0,Mt.default)({level:"error"}),reuploadRequest:this.client.updateMediaMessage}),l=(0,v.getContentType)(n.message),u=It.default.getExtension(r?.mimetype),d=r?.fileName||
${n.key.id}.${u}||
${(0,er.v4)()}.${u};if(o&&l==="audioMessage"){let g=await this.processAudioMp4(c.toString("base64"));if(Buffer.isBuffer(g))return{mediaType:a,fileName:d,caption:r.caption,size:{fileLength:r.fileLength,height:r.height,width:r.width},mimetype:"audio/mp4",base64:g,buffer:t?g:null}}return{mediaType:a,fileName:d,caption:r.caption,size:{fileLength:r.fileLength,height:r.height,width:r.width},mimetype:r.mimetype,base64:c.toString("base64"),buffer:t?c:null}}catch(s){throw this.logger.error("line 3026"),this.logger.error(s),new h(s.toString())}}async fetchPrivacySettings(){let e=await this.client.fetchPrivacySettings();return{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}async updatePrivacySettings(e){try{return await this.client.updateReadReceiptsPrivacy(e.readreceipts),await this.client.updateProfilePicturePrivacy(e.profile),await this.client.updateStatusPrivacy(e.status),await this.client.updateOnlinePrivacy(e.online),await this.client.updateLastSeenPrivacy(e.last),await this.client.updateGroupsAddPrivacy(e.groupadd),this.reloadConnection(),{update:"success",data:{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}}catch(t){throw this.logger.error("line 3068"),new k("Error updating privacy settings",t.toString())}}async fetchBusinessProfile(e){try{let t=e?this.createJid(e):this.instance.wuid,s=await this.client.getBusinessProfile(t);return s?{isBusiness:!0,...s}:{isBusiness:!1,message:"Not is business profile",...(await this.whatsappNumber({numbers:[t]}))?.shift()}}catch(t){throw this.logger.error("line 3094"),new k("Error updating profile name",t.toString())}}async updateProfileName(e){try{return await this.client.updateProfileName(e),{update:"success"}}catch(t){throw this.logger.error("line 3105"),new k("Error updating profile name",t.toString())}}async updateProfileStatus(e){try{return await this.client.updateProfileStatus(e),{update:"success"}}catch(t){throw this.logger.error("line 3116"),new k("Error updating profile status",t.toString())}}async updateProfilePicture(e){try{let t;if((0,ne.isURL)(e)){let s=new Date().getTime(),o=
${e}?timestamp=${s},n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:ce({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await xe.default.get(o,n)).data}else if((0,ne.isBase64)(e))t=Buffer.from(e,"base64");else throw new h('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(this.instance.wuid,t),this.reloadConnection(),{update:"success"}}catch(t){throw this.logger.error("line 3158"),new k("Error updating profile picture",t.toString())}}async removeProfilePicture(){try{return await this.client.removeProfilePicture(this.instance.wuid),this.reloadConnection(),{update:"success"}}catch(e){throw this.logger.error("line 3171"),new k("Error removing profile picture",e.toString())}}async blockUser(e){try{let{number:t}=e,s=(await this.whatsappNumber({numbers:[t]}))?.shift();if(!s.exists&&!(0,v.isJidGroup)(s.jid)&&!s.jid.includes("@broadcast"))throw new h(s);let o=s.jid;return await this.client.updateBlockStatus(o,e.status),{block:"success"}}catch(t){throw this.logger.error("line 3192"),new k("Error blocking user",t.toString())}}async formatUpdateMessage(e){try{let t=await this.getMessage(e.key,!0);return t?.messageType==="conversation"||t?.messageType==="extendedTextMessage"?{text:e.text}:t?.messageType==="imageMessage"?{image:t?.message?.imageMessage,caption:e.text}:t?.messageType==="videoMessage"?{video:t?.message?.videoMessage,caption:e.text}:null}catch(t){throw this.logger.error("line 3223"),this.logger.error(t),new h(t.toString())}}async updateMessage(e){let t=this.createJid(e.number),s=await this.formatUpdateMessage(e);if(!s)throw this.logger.error("Message not compatible"),new h("Message not compatible");try{return await this.client.sendMessage(t,{...s,edit:e.key})}catch(o){throw this.logger.error("line 3245"),this.logger.error(o),new h(o.toString())}}async fetchLabels(){return(await this.prismaRepository.label.findMany({where:{instanceId:this.instanceId}})).map(t=>({color:t.color,name:t.name,id:t.labelId,predefinedId:t.predefinedId}))}async handleLabel(e){let t=await this.whatsappNumber({numbers:[e.number]});if(t.length===0)throw new P("Number not found");let s=t[0];if(!s.exists)throw new P("Number is not on WhatsApp");try{if(e.action==="add")return await this.client.addChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,add:!0};if(e.action==="remove")return await this.client.removeChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,remove:!0}}catch(o){throw this.logger.error("line 3288"),new h(
Unable to ${e.action} label to chat,o.toString())}}async updateGroupMetadataCache(e){try{let t=await this.client.groupMetadata(e),s=this.configService.get("CACHE");return(s?.REDIS?.ENABLED&&s?.REDIS?.URI!==""||s?.LOCAL?.ENABLED)&&(this.logger.verbose(
Updating cache for group: ${e}),await Pn.set(e,{timestamp:Date.now(),data:t})),t}catch(t){return this.logger.error("line 3310"),this.logger.error(t),null}}async getGroupMetadataCache(e){if(!(0,v.isJidGroup)(e))return null;let t=E.get("CACHE");if(t?.REDIS?.ENABLED&&t?.REDIS?.URI!==""||t?.LOCAL?.ENABLED){if(await Pn.has(e)){console.log(
Cache request for group: ${e});let s=await Pn.get(e);return Date.now()-s.timestamp>36e5&&await this.updateGroupMetadataCache(e),s.data}return console.log(
Cache request for group: ${e} - not found),await this.updateGroupMetadataCache(e)}return await this.findGroup({groupJid:e},"inner")}async createGroup(e){try{let t=(await this.whatsappNumber({numbers:e.participants})).filter(n=>n.exists).map(n=>n.jid),{id:s}=await this.client.groupCreate(e.subject,t);return e?.description&&await this.client.groupUpdateDescription(s,e.description),e?.promoteParticipants&&await this.updateGParticipant({groupJid:s,action:"promote",participants:t}),await this.client.groupMetadata(s)}catch(t){throw this.logger.error("line 3363"),this.logger.error(t),new k("Error creating group",t.toString())}}async updateGroupPicture(e){try{let t;if((0,ne.isURL)(e.image)){let s=new Date().getTime(),o=
${e.image}?timestamp=${s},n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:ce({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await xe.default.get(o,n)).data}else if((0,ne.isBase64)(e.image))t=Buffer.from(e.image,"base64");else throw new h('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(e.groupJid,t),{update:"success"}}catch(t){throw this.logger.error("line 3403"),new k("Error update group picture",t.toString())}}async updateGroupSubject(e){try{return await this.client.groupUpdateSubject(e.groupJid,e.subject),{update:"success"}}catch(t){throw this.logger.error("line 3414"),new k("Error updating group subject",t.toString())}}async updateGroupDescription(e){try{return await this.client.groupUpdateDescription(e.groupJid,e.description),{update:"success"}}catch(t){throw this.logger.error("line 3425"),new k("Error updating group description",t.toString())}}async findGroup(e,t="out"){try{let s=await this.client.groupMetadata(e.groupJid);if(!s)return this.logger.error("Group not found"),null;let o=await this.profilePicture(s.id);return{id:s.id,subject:s.subject,subjectOwner:s.subjectOwner,subjectTime:s.subjectTime,pictureUrl:o.profilePictureUrl,size:s.participants.length,creation:s.creation,owner:s.owner,desc:s.desc,descId:s.descId,restrict:s.restrict,announce:s.announce,participants:s.participants}}catch(s){if(t==="inner")return;throw this.logger.error("line 3460"),new P("Error fetching group",s.toString())}}async fetchAllGroups(e){let t=Object.values(await this?.client?.groupFetchAllParticipating()),s=[];for(let o of t){let n=await this.profilePicture(o.id),r={id:o.id,subject:o.subject,subjectOwner:o.subjectOwner,subjectTime:o.subjectTime,pictureUrl:n?.profilePictureUrl,size:o.participants.length,creation:o.creation,owner:o.owner,desc:o.desc,descId:o.descId,restrict:o.restrict,announce:o.announce};e.getParticipants=="true"&&(r.participants=o.participants),s=[...s,r]}return s}async inviteCode(e){try{let t=await this.client.groupInviteCode(e.groupJid);return{inviteUrl:
https://chat.whatsapp.com/${t}`,inviteCode:t}}catch(t){throw this.logger.error("line 3502"),new P("No invite code",t.toString())}}async inviteInfo(e){try{return await this.client.groupGetInviteInfo(e.inviteCode)}catch{throw this.logger.error("line 3511"),new P("No invite info",e.inviteCode)}}async sendInvite(e){try{let s=(await this.inviteCode({groupJid:e.groupJid})).inviteUrl,o=e.numbers.map(c=>this.createJid(c)),a={conversation:${e.description??""} 213 → 214 ${s}
};for await(let c of o)await this.sendMessageWithTyping(c,a);return{send:!0,inviteUrl:s}}catch{throw this.logger.error("line 3537"),new P("No send invite")}}async acceptInviteCode(e){try{return{accepted:!0,groupJid:await this.client.groupAcceptInvite(e.inviteCode)}}catch(t){throw this.logger.error("line 3547"),new P("Accept invite error",t.toString())}}async revokeInviteCode(e){try{return{revoked:!0,inviteCode:await this.client.groupRevokeInvite(e.groupJid)}}catch(t){throw this.logger.error("line 3557"),new P("Revoke error",t.toString())}}async findParticipants(e){try{let t=(await this.client.groupMetadata(e.groupJid)).participants,s=await this.prismaRepository.contact.findMany( Foreign key constraint failed on the field:OpenaiSetting_openaiCredsId_fkey (index)
at _n.handleRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7749) at _n.handleAndLogRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7057) at _n.request (/evolution/node_modules/@prisma/client/runtime/library.js:121:6741) at async l (/evolution/node_modules/@prisma/client/runtime/library.js:130:9355) at async p.deleteCreds (/evolution/dist/main.js:214:49514) at async gi.dataValidate (/evolution/dist/main.js:214:101852) at async /evolution/dist/main.js:214:138739 { code: 'P2003', clientVersion: '5.18.0', { modelName: 'OpenaiCreds', field_name: 'OpenaiSetting_openaiCredsId_fkey (index)' } }