evolution-api icon indicating copy to clipboard operation
evolution-api copied to clipboard

startSession is ignored in the Evolution API's start command for Typebot in version 2.1.0

Open admdanielspalma opened this issue 1 year ago • 9 comments

Welcome!

  • [X] Yes, I have searched for similar issues on GitHub and found none.

What did you do?

I configured the startSession parameter as true when starting a session with the typebot via the Evolution API, expecting a new session to be automatically initiated when calling the bot.

What did you expect?

I expected a new session with the bot to automatically start when the startSession parameter is set to true.

What did you observe instead of what you expected?

The bot session is not initiated, even when the startSession parameter is set to true. The command seems to be completely ignored, and the expected behavior does not occur.

Screenshots/Videos

No response

Which version of the API are you using?

2.1.0

What is your environment?

Linux

Other environment specifications

Ubuntu server / docker / portainer

If applicable, paste the log output

No response

Additional Notes

The issue has been present since version 1.8.x or older.

admdanielspalma avatar Sep 14 '24 02:09 admdanielspalma

Posso confirmar o mesmo problema aqui. Quando faço a chamada para o endpoint setando "startSession": true, o fluxo do typebot é iniciado e as mensagens iniciais são enviadas, mas a seção do typebot não é aberta/registrada no evolution. Então quando a mensagem é respondida, o fluxo do typebot é reiniciado, enviando novamente as mensagens iniciais.

RodPace avatar Sep 14 '24 12:09 RodPace

Posso confirmar o mesmo problema aqui. Quando faço a chamada para o endpoint setando "startSession": true, o fluxo do typebot é iniciado e as mensagens iniciais são enviadas, mas a seção do typebot não é aberta/registrada no evolution. Então quando a mensagem é respondida, o fluxo do typebot é reiniciado, enviando novamente as mensagens iniciais.

Na verdade simplesmente não acontece nada, né? Se tá reiniciando é porque tem um outro gatilho, pra iniciar a partir de keyword por exemplo. Mas nesse caso, quando inicia a partir de keyword, funciona corretamente (inicia a sessão e tudo corre normal).

admdanielspalma avatar Sep 14 '24 15:09 admdanielspalma

Vamos lá Daniel, deixe eu tentar expicar em mais detalhes.

Url da documentação a qual me refiro: https://doc.evolution-api.com/v2/pt/integrations/typebot, item 4. "Inicialização Ativa de um Bot". Especificamente o parâmetro startSession: Define se a sessão deve ser iniciada com o bot (true ou false).

Lendo a documentação o que se espera é que quando você chama o endpoint {{baseUrl}}/typebot/start/{{instance}} com o parâmetro "startSession": true é que seja iniciado o fluxo e que a seção do typebot seja setado na Evolution. Conseguimos ver a seção do typebot na evolution indo no manager em Integrações>typebot>"fluxo cadastrado">sessions.

O que acontece. Quando chamo esse endpoint o fluxo é iniciado e a mensagem é enviada para o usuário final através do jid fornecido, entretanto a sessão do typebot não é registrada na Evolution. Quando configuramos o parâmetro "startSession":true estamos informando a Evolution que queremos que a seção seja registrada na Evolution assim, quando cliente responde, o fluxo segue do ponto onde parou e não inicie novamente.

Vamos a um exemplo? Imagine um fluxo onde no typebot eu envio a seguinte mensagem "Recebemos seu cadastro, por favor, informe seu CPF". Qual será o comportamento do cliente? Será obviamente digitar o CPF. Quando o cliente informa o CPF o fluxo deveria seguir para as próximas etapas. Mas não é isso que acontece.

Quando o cliente informa o CPF, uma nova seção do typebot é iniciada, iniciando o fluxo novamente e, dessa vez, registrando a sessão na Evolution. Então para o cliente fica assim:

  • Mensagem: Recebemos seu cadastro, por favor, informe seu CPF
  • Cliente digita o CPF
  • Mensagem: Recebemos seu cadastro, por favor, informe seu CPF
  • Cliente digita novamente o CPF
  • Mensagem: CPF encontrado, como podemos ajudar

O que espero que aconteça:

  • Mensagem: Recebemos seu cadastro, por favor, informe seu CPF
  • Cliente digita novamente o CPF
  • Mensagem: CPF encontrado, como podemos ajudar

Para mim parece ser uma correção fácil porque a rotina de registro da sessão do typebot na evolution já está escrita, tanto que ela é ativada e executada corretamente quando o fluxo é iniciada por uma mensagem do cliente. Então, para corrigir o inicio ativo do typebot, seria somente chamar a mesma função quando o endpoint de start typebot for chamado.

RodPace avatar Sep 18 '24 18:09 RodPace

Sim, RodPace, obrigado por detalhar.

O que acontece é que, quando o cliente interage, nada acontece porque a sessão não está aberta.

O fato do seu fluxo estar reiniciando se deve ao fato que tu deve ter um gatilho de início de fluxo na mensagem do cliente.

O que eu estava dizendo é que esse reinicio não se refere ao problema diretamente, mas é apenas uma consequencia dele. Se tu desabilitar esse gatilho da primeira mensagem, o que vai acontecer é nada. Vai rodar o começo do fluxo e na primeira interação com o cliente vai parar e não vai acontecer mais nada mesmo que ele responda.

Dito isso, dito esse detalhe, estamos na mesma página. Obrigado por reforçar aqui o pedido. Abraço!

admdanielspalma avatar Sep 21 '24 17:09 admdanielspalma

Testei na 2.1.1 agora (do dia 22/set/24).

Agora, se está startSession = false segue como tava, normal... mas startSession=true retorna um erro (antes só ignorava, ficava como false)

Log: { "status": 500, "error": "Internal Server Error", "response": { "message":"\nInvalid this.prismaRepository.integrationSession.findFirst() invocation in\n/evolution/dist/main.js:236:69319\n\n 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??""}\n 234 \n 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(/[\̀-\ͯ]/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+=\n→ 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({\n where: {\n url_typebot_instanceId: {\n ~~~~~~~~~~~~~~~~~~~~~~\n url: \"https://chat.eagleflow.com.br\",\n typebot: \"teste2\",\n instanceId: \"19d3f2ba-5e33-4077-868b-84c86916cfe7\"\n },\n ? id?: String,\n ? AND?: TypebotWhereInput | TypebotWhereInput[],\n ? OR?: TypebotWhereInput[],\n ? NOT?: TypebotWhereInput | TypebotWhereInput[],\n ? enabled?: BoolFilter | Boolean,\n ? description?: StringNullableFilter | String | Null,\n ? url?: StringFilter | String,\n ? typebot?: StringFilter | String,\n ? expire?: IntNullableFilter | Int | Null,\n ? keywordFinish?: StringNullableFilter | String | Null,\n ? delayMessage?: IntNullableFilter | Int | Null,\n ? unknownMessage?: StringNullableFilter | String | Null,\n ? listeningFromMe?: BoolNullableFilter | Boolean | Null,\n ? stopBotFromMe?: BoolNullableFilter | Boolean | Null,\n ? keepOpen?: BoolNullableFilter | Boolean | Null,\n ? debounceTime?: IntNullableFilter | Int | Null,\n ? createdAt?: DateTimeNullableFilter | DateTime | Null,\n ? updatedAt?: DateTimeNullableFilter | DateTime | Null,\n ? ignoreJids?: JsonNullableFilter,\n ? triggerType?: EnumTriggerTypeNullableFilter | TriggerType | Null,\n ? triggerOperator?: EnumTriggerOperatorNullableFilter | TriggerOperator | Null,\n ? triggerValue?: StringNullableFilter | String | Null,\n ? instanceId?: StringFilter | String,\n ? Instance?: InstanceRelationFilter | InstanceWhereInput,\n ? TypebotSetting?: TypebotSettingListRelationFilter\n },\n update: {\n enabled: true\n },\n create: {\n enabled: true,\n url: \"https://chat.eagleflow.com.br\",\n typebot: \"teste2\",\n expire: 10,\n triggerType: \"none\",\n keywordFinish: \"Parar bot\",\n delayMessage: 1000,\n unknownMessage: \"Desculpe, não entendi\",\n listeningFromMe: false,\n stopBotFromMe: true,\n keepOpen: false,\n instanceId: \"19d3f2ba-5e33-4077-868b-84c86916cfe7\"\n }\n })\n\nUnknown argument url_typebot_instanceId`. Available options are marked with ?." } }

admdanielspalma avatar Sep 28 '24 13:09 admdanielspalma

Com false funciona

Com true dá erro:

{ "url": "https://chat.eagleflow.com.br", "typebot": "teste", "remoteJid": "{{remoteJid}}", "startSession": true }

image

admdanielspalma avatar Sep 30 '24 18:09 admdanielspalma

Estou com o mesmo problema aqui. O fluxo inicia, porém, não captura a resposta do usuário e não registra nenhuma sessão. Testei na versão 2.1.0 e 2.1.1, ambas não abrem a sessão e o fluxo do TypeBot é reiniciado. Não tinha encontrado essa Issue e abri essa: #939

markinhok2 avatar Oct 02 '24 14:10 markinhok2

Estou enfrentando o mesmo problema

robisonfb avatar Oct 02 '24 15:10 robisonfb

Pessoal, foi consertado, porém parcialmente... não sei se devo informar um novo bug. O problema agora é que só inicia sessão com o JID exato. Porém, se botar só o telefone por exemplo, sem @, ele inicia o fluxo... só não abre sessão. Acho que se ele inicia o fluxo deveria iniciar sessão, não acham?

admdanielspalma avatar Oct 07 '24 16:10 admdanielspalma

acredito que o ideal é informar o Jid pois é como se fosse o ID que o evolution entende

dpaes avatar Nov 28 '24 16:11 dpaes

estou na versão 2.2.0 e está com esse erro, conseguiu solucionar de algum modo?

VitorParceria avatar Jan 07 '25 14:01 VitorParceria

Estou com a versão 2.2.3 e está com o mesmo erro. Alguém conseguiu uma solução?

leofelipet avatar Feb 21 '25 19:02 leofelipet