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

Erro ao enviar mensagem de texto

Open LuizLobao opened this issue 1 month ago • 10 comments

Welcome!

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

What did you do?

Ao tentar enviar uma mensagem de texto via API, ocorre o erro 500 - Internal Server Error. O log aponta uma exceção relacionada à invocação inválida de this.cache.delete() no arquivo main.js.

500 - {"status":500,"error":"Internal Server Error","response":{"message":"Invalid this.cache.delete() invocation in /evolution/dist/main.js:244:8153"}}

Trecho relevante: 241 ),i.url&&(n+=URL:${i.url} 242 ),i.wuid||(i.wuid=G(i.phoneNumber)),n+=item1.TEL;waid=${i.wuid}:${i.phoneNumber} 243 item1.X-ABLabel:Celular → 244 END:VCARD,n};return e.contact.length===1?t.contact={displayName:e.contact[0].fullName,vcard:o(e.contact[0])}:t.contactsArrayMessage={displayName:${e.contact.length} contacts,contacts:e.contact.map(i=>({displayName:i.fullName,vcard:o(i)}))},await this.sendMessageWithTyping(...) ... Unique constraint failed on the fields: (remoteJid)

What did you expect?

A mensagem de texto deve ser enviada com sucesso, sem gerar erro interno no serviço.

What did you observe instead of what you expected?

🧠 Possível causa

Aparentemente, há uma chamada inválida para this.cache.delete() — possivelmente tentando excluir uma chave inexistente ou usando um tipo incorreto de objeto de cache. O erro pode estar relacionado ao gerenciamento de remoteJid em mensagens enviadas com múltiplos contatos no payload.

Screenshots/Videos

No response

Which version of the API are you using?

"version":"2.3.6"

What is your environment?

Windows

Other environment specifications

Versão da lib / container: (informar exata, ex: v3.12.1)

Runtime: Node.js (versão exata)

SO / ambiente de execução: (ex: Docker / Ubuntu / Windows)

Banco ou cache usado: (ex: Redis, MemoryCache, etc.)

If applicable, paste the log output

Erro ao enviar mensagem de texto 500 - {"status":500,"error":"Internal Server Error","response":{"message":"\nInvalid this.cache.delete() invocation in\n/evolution/dist/main.js:244:8153\n\n 241 ),i.url&&(n+=URL:${i.url}\n 242 ),i.wuid||(i.wuid=G(i.phoneNumber)),n+=item1.TEL;waid=${i.wuid}:${i.phoneNumber}\n 243 item1.X-ABLabel:Celular\n→ 244 END:VCARD,n};return e.contact.length===1?t.contact={displayName:e.contact[0].fullName,vcard:o(e.contact[0])}:t.contactsArrayMessage={displayName:${e.contact.length} contacts,contacts:e.contact.map(i=>({displayName:i.fullName,vcard:o(i)}))},await this.sendMessageWithTyping(e.number,{contacts:e.contact.map(i=>({name:{formatted_name:i.fullName,first_name:i.fullName},phones:[{phone:i.phoneNumber}],urls:[{url:i.url}],emails:[{email:i.email}],org:{company:i.organization}})),message:t},{delay:e?.delay,presence:"composing",quoted:e?.quoted,linkPreview:e?.linkPreview,mentionsEveryOne:e?.mentionsEveryOne,mentioned:e?.mentioned})}async reactionMessage(e){return await this.sendMessageWithTyping(e.key.remoteJid,{reactionMessage:{key:e.key,text:e.reaction}})}async getBase64FromMediaMessage(e){try{let t=e.message,o=t.messageType.includes("Message")?t.messageType:t.messageType+"Message",i=t.message[o];return{mediaType:t.messageType,fileName:i?.fileName,caption:i?.caption,size:{fileLength:i?.fileLength,height:i?.fileLength,width:i?.width},mimetype:i?.mime_type,base64:t.message.base64}}catch(t){throw this.logger.error(t),new y(t.toString())}}async deleteMessage(){throw new y("Method not available on WhatsApp Business API")}async mediaSticker(){throw new y("Method not available on WhatsApp Business API")}async pollMessage(){throw new y("Method not available on WhatsApp Business API")}async statusMessage(){throw new y("Method not available on WhatsApp Business API")}async reloadConnection(){throw new y("Method not available on WhatsApp Business API")}async whatsappNumber(){throw new y("Method not available on WhatsApp Business API")}async markMessageAsRead(){throw new y("Method not available on WhatsApp Business API")}async archiveChat(){throw new y("Method not available on WhatsApp Business API")}async markChatUnread(){throw new y("Method not available on WhatsApp Business API")}async fetchProfile(){throw new y("Method not available on WhatsApp Business API")}async offerCall(){throw new y("Method not available on WhatsApp Business API")}async sendPresence(){throw new y("Method not available on WhatsApp Business API")}async setPresence(){throw new y("Method not available on WhatsApp Business API")}async fetchPrivacySettings(){throw new y("Method not available on WhatsApp Business API")}async updatePrivacySettings(){throw new y("Method not available on WhatsApp Business API")}async fetchBusinessProfile(){throw new y("Method not available on WhatsApp Business API")}async updateProfileName(){throw new y("Method not available on WhatsApp Business API")}async updateProfileStatus(){throw new y("Method not available on WhatsApp Business API")}async updateProfilePicture(){throw new y("Method not available on WhatsApp Business API")}async removeProfilePicture(){throw new y("Method not available on WhatsApp Business API")}async blockUser(){throw new y("Method not available on WhatsApp Business API")}async updateMessage(){throw new y("Method not available on WhatsApp Business API")}async createGroup(){throw new y("Method not available on WhatsApp Business API")}async updateGroupPicture(){throw new y("Method not available on WhatsApp Business API")}async updateGroupSubject(){throw new y("Method not available on WhatsApp Business API")}async updateGroupDescription(){throw new y("Method not available on WhatsApp Business API")}async findGroup(){throw new y("Method not available on WhatsApp Business API")}async fetchAllGroups(){throw new y("Method not available on WhatsApp Business API")}async inviteCode(){throw new y("Method not available on WhatsApp Business API")}async inviteInfo(){throw new y("Method not available on WhatsApp Business API")}async sendInvite(){throw new y("Method not available on WhatsApp Business API")}async acceptInviteCode(){throw new y("Method not available on WhatsApp Business API")}async revokeInviteCode(){throw new y("Method not available on WhatsApp Business API")}async findParticipants(){throw new y("Method not available on WhatsApp Business API")}async updateGParticipant(){throw new y("Method not available on WhatsApp Business API")}async updateGSetting(){throw new y("Method not available on WhatsApp Business API")}async toggleEphemeral(){throw new y("Method not available on WhatsApp Business API")}async leaveGroup(){throw new y("Method not available on WhatsApp Business API")}async fetchLabels(){throw new y("Method not available on WhatsApp Business API")}async handleLabel(){throw new y("Method not available on WhatsApp Business API")}async receiveMobileCode(){throw new y("Method not available on WhatsApp Business API")}async fakeCall(){throw new y("Method not available on WhatsApp Business API")}};var Ke=class{constructor(s,e,t,o,i){this.jid=s;this.exists=e;this.number=t;this.name=o;this.lid=i}},xs=class{},ks=class{},et=class{};var Ls=class{},Bs=class{},bt=class{};var Us=class{};var $s=class{},Ws=class{},Js=class{},Fs=class{};var Ln=class{},Gs=class extends Ln{},qs=class extends Gs{},Hs=class extends Gs{},Vs=class{};var Bn=require("baileys"),Le=class{constructor(s){this.cache=s;this.logger=new v("CacheService");s?this.logger.verbose(cacheservice created using cache engine: ${s.constructor?.name}):this.logger.verbose("cacheservice disabled")}async get(s){if(this.cache)return this.cache.get(s)}async hGet(s,e){if(!this.cache)return null;try{let t=await this.cache.hGet(s,e);return t?JSON.parse(t,Bn.BufferJSON.reviver):null}catch(t){return this.logger.error(t),null}}async set(s,e,t){this.cache&&this.cache.set(s,e,t)}async hSet(s,e,t){if(this.cache)try{let o=JSON.stringify(t,Bn.BufferJSON.replacer);await this.cache.hSet(s,e,o)}catch(o){this.logger.error(o)}}async has(s){if(this.cache)return this.cache.has(s)}async delete(s){if(this.cache)return this.cache.delete(\nUnique constraint failed on the fields: (remoteJid`)"}}

Additional Notes

No response

LuizLobao avatar Nov 06 '25 02:11 LuizLobao

Estou com o mesmo problema

RafaelCardozo02 avatar Nov 06 '25 12:11 RafaelCardozo02

Mesma coisa aqui

hiuryr avatar Nov 06 '25 13:11 hiuryr

+1

juliancesar avatar Nov 06 '25 14:11 juliancesar

Também estou com o mesmo problema. Estou usando o mysql e evolution-api via docker. A migração

/evolution/prisma/mysql-migrations/20250918183910_add_kafka_integration/migration.sql

desfaz as duas migrações anteriores, a

20250612155048_add_coluns_trypebot_tables

-- AlterTable
ALTER TABLE `Typebot` ADD COLUMN     `splitMessages` BOOLEAN DEFAULT false,
ADD COLUMN     `timePerChar` INTEGER DEFAULT 50;

-- AlterTable
ALTER TABLE `TypebotSetting` ADD COLUMN     `splitMessages` BOOLEAN DEFAULT false,
ADD COLUMN     `timePerChar` INTEGER DEFAULT 50;

e a 20250613143000_add_lid_column_to_is_onwhatsapp são feitas

-- AlterTable
ALTER TABLE `IsOnWhatsapp` ADD COLUMN     `lid` VARCHAR(100);

20250918183910_add_kafka_integration/migration.sql desfaz as duas migrações anteriores

-- AlterTable                                                                                                                                                                                 
ALTER TABLE `IsOnWhatsapp` DROP COLUMN `lid`,                                                                                                                                                 
    MODIFY `createdAt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,                                                                                                                          
    MODIFY `updatedAt` TIMESTAMP NOT NULL; 

-- AlterTable
ALTER TABLE `Typebot` DROP COLUMN `splitMessages`,
    DROP COLUMN `timePerChar`,
    MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    MODIFY `updatedAt` TIMESTAMP NULL;

-- AlterTable
ALTER TABLE `TypebotSetting` DROP COLUMN `splitMessages`,
    DROP COLUMN `timePerChar`,
    MODIFY `createdAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
    MODIFY `updatedAt` TIMESTAMP NOT NULL;

O campo lid não aparece no schema do mysql também

model IsOnWhatsapp {
  id         String   @id @default(cuid())
  remoteJid  String   @unique @db.VarChar(100)
  jidOptions String
  createdAt  DateTime @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp
  updatedAt  DateTime @updatedAt @db.Timestamp
}

Mas aparece no schema do postgres

model IsOnWhatsapp {
  id         String   @id @default(cuid())
  remoteJid  String   @unique @db.VarChar(100)
  jidOptions String
  lid        String?  @db.VarChar(100)
  createdAt  DateTime @default(now()) @db.Timestamp
  updatedAt  DateTime @updatedAt @db.Timestamp
}

Primeira vez que estou tentando usar a evolution-api, então não sei porquê isso, se é proposital ou algo que não deveria acontecer, acho que ir para o postgres resolva o problema.

lfelizari avatar Nov 06 '25 14:11 lfelizari

Trocando o banco para postgresql, funciona, a versão com mysql não. js não é bem minha praia, então não sei exatamente como arrumar a versão do mysql, mas acredito que tenha que criar uma nova migração para recuperar os campos que a migração 20250918183910_add_kafka_integration/migration.sql apagou e conferir os que foram alterados.

lfelizari avatar Nov 06 '25 17:11 lfelizari

Eu também estou com o mesmo problema, imagens e arquivos também não estão enviando. Alguma solução?

Emanuellefelix avatar Nov 06 '25 19:11 Emanuellefelix

Após analise do @lfelizari consegui chegar nessa solução (muito obrigado por isso, meu amigo)

Verifique se o campo lid existe no banco Entre no container do MySQL e execute:

docker exec -it evolution-mysql mysql -u root -p
USE evolution; -- ou o nome do seu banco
DESCRIBE IsOnWhatsapp;

Ou via algum gerenciador de banco de dados.

Se a coluna lid não aparecer, crie com:

ALTER TABLE `IsOnWhatsapp`
  ADD COLUMN `lid` VARCHAR(100) NULL AFTER `jidOptions`;

Corrigir o schema Prisma usado pelo MySQL Entre no container do Evolution API:

docker exec -it evolution_api bash

Acesse a pasta do Prisma - certifique de estar na pasta do evolution:

cd prisma/

Abra o arquivo de schema do MySQL:

vi mysql-schema.prisma

vai descendo até achar model IsOnWhatsapp Pressione i (modo de inserção)

Vá até logo abaixo de jidOptions String e adicione esta linha

  lid        String?  @db.VarChar(100)

Deve ficar assim:

model IsOnWhatsapp {
  id         String   @id @default(cuid())
  remoteJid  String   @unique @db.VarChar(100)
  jidOptions String
  lid        String?  @db.VarChar(100) // <--- adicione esta linha
  createdAt  DateTime @default(dbgenerated("CURRENT_TIMESTAMP")) @db.Timestamp
  updatedAt  DateTime @updatedAt @db.Timestamp
}

Pressione ESC para sair do modo de edição

Digite :wq e pressione ENTER para salvar e sair

Regenerar o Prisma Client

Volte uma pasta para ficar /evolution/ :

cd ..

Execute:

npx prisma generate --schema=./prisma/mysql-schema.prisma

Você deve ver uma mensagem como:

Prisma schema loaded from prisma/mysql-schema.prisma ✔ Generated Prisma Client (v6.17.1)

Reiniciar o serviço:

Reinicie o Evolution API para carregar o novo cliente Prisma:

docker compose restart evolution_api

mhanelia avatar Nov 06 '25 21:11 mhanelia

@mhanelia obrigado pela resposta clara e objetiva. Funcionou perfeitamente.

VilasBoas23 avatar Nov 20 '25 18:11 VilasBoas23

aqui eu uso o postgresql, versão do evo 2.3.6 tem esse campo, mas ainda sim esta com mesmo erro, alguém resolveu?

luispimenta avatar Nov 21 '25 21:11 luispimenta

Tem um merge realizado para um problema semelhante. A próxima versão deve corrigir alguns cenários principalmente para envio em grupos. https://github.com/EvolutionAPI/evolution-api/pull/2162

Lucasbrunoferreira avatar Nov 25 '25 14:11 Lucasbrunoferreira