Baileys
Baileys copied to clipboard
message not showing when send to new number first time[BUG]
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched
please help me
I have the same problem.
me too
anyone get issue?
here too
Update the app, it solved for me.
Update the app, it solved for me.
What version are you using ?
It's been more than a week, I am getting this issue and have no fix yet.
Update the app, it solved for me.
You mean the sender or receiver? who needs to update the app to avoid this issue?
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched
please help me
you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
let messages = []
function deleteMessage(messageID) {
delete messages[messageID]
}
function saveMessage(messageID, txt) {
messages[messageID] = txt
}
function getMessage(messageID) {
return messages[messageID]
}
function clearMessages() {
messages = []
}
setInterval(clearMessages, 120000)
export default {
getMessage,
saveMessage,
deleteMessage
}
then at making socket :
const retryMessageHandler = async message => {
console.log("retry for send message !!!!!")
let text = temporaryStore.getMessage(message.id)
temporaryStore.deleteMessage(message.id)
return {
conversation: text
}
}
sock = makeWASocket({
browser: config.getAgent(process.env.AGENT_NUMBER),
version,
logger,
printQRInTerminal: true,
auth: state,
msgRetryCounterMap,
// implement to handle retries
getMessage: retryMessageHandler // at this line we use retryMessageHandler
})
and finally after sending a message , save it at temporaryStore
let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me you should implement getMessage on making socket
- fetch a message from your store
- implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Thank you so much, I am gonna implement this now.
Update the app, it solved for me.
You mean the sender or receiver? who needs to update the app to avoid this issue?
On my case updating receiver app device is works.
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me
you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Bro thanks to try help us, is possible use this solution for send media url and buttons ?
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me
you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
I tested this solution with some numbers and at first it worked for me. I created a more generic function to support sending other messages and not just texts. I tested it with about 10 numbers and it seems to have solved the problem at hand, this may not be the best solution but if anyone else can test it to validate its effectiveness it would be great.
function saveMessage(messageID, message: Record<string, unknown>): void {
messages[messageID] = message;
}
const response = await sock?.sendMessage(
jid,
buttonMessage
);
temporaryStore.saveMessage(response?.key?.id, {
buttonsMessage: response?.message?.buttonsMessage,
});
retryMessageHandler = async (
message
): Promise<proto.IMessage | undefined> => {
const messageContent = temporaryStore.getMessage(message.id);
console.log("retry for send message !!!!!", messageContent);
temporaryStore.deleteMessage(message.id);
return messageContent;
};
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me
you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined> example : implement a store at temporaryStore file (I created this file myself)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Bro thanks to try help us, is possible use this solution for send media url and buttons ?
yes just save the whole message structure instead of message text at temporaryStore and return that at the retryMessageHandler
@adiwajshing please help to solve this issue
You all can use
import { proto } from "@adiwajshing/baileys";
export class MessageRetryHandler {
public messagesMap: Record<string, proto.IMessage>;
constructor() {
this.messagesMap = {};
}
addMessage = async (message: proto.IWebMessageInfo) => {
const id = message.key.id ?? "";
console.log(this);
this.messagesMap[id] = this.cleanMessage(message);
return message;
};
getMessage = (msgKey: string): proto.IMessage => {
return this.messagesMap[msgKey];
};
removeMessage = (msgKey: string) => {
delete this.messagesMap[msgKey];
};
getMessageKeys = (): string[] => {
return Object.keys(this.messagesMap);
};
cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => {
const msg = message.message ?? {};
return msg;
};
messageRetryHandler = async (message: proto.IMessageKey) => {
const msg = this.getMessage(message.id ?? "");
// Remove msg from map
this.removeMessage(message.id ?? "");
return msg;
};
}
Then implement it as
const handler = new MessageRetryHandler();
const socketConfig: Partial<SocketConfig> = {
printQRInTerminal: false,
logger: PinoLogger({
level: "silent",
}),
getMessage: handler.messageRetryHandler,
};
And when sending messages,
const sentMessage = await socket.sendMessage(id, {
text: text,
})
.then(handler.addMessage);
This will handle all types of messages automatically, just remember to add the .then(handler.addMessage);
after the message.
@Manjit2003 thanks man...
messages show on phone but still show pending on desktop login
@Manjit2003
That's the WhatsApp Web bug. Is it usually working on the phone now?
yes but whatsapp web still showing waiting for message....we use other company api its working well please look also into this
Okay, i will check it
@Manjit2003 @Denver1997 I am not able to use this code in the example.ts file. I am not sure where exactly i need to add this code. Can you please add this code in the example.ts and paste the full code here.
@picblog229 Here you go,
import { MessageRetryHandler } from "./retryHandler";
import { Boom } from "@hapi/boom";
import { useSingleFileAuthState } from "./authState";
import makeWASocket, {
AnyMessageContent,
DisconnectReason,
fetchLatestBaileysVersion,
makeInMemoryStore,
} from "@adiwajshing/baileys";
import pino from "pino";
const logger = pino();
logger.level = "trace";
const useStore = !process.argv.includes("--no-store");
const doReplies = !process.argv.includes("--no-reply");
// external map to store retry counts of messages when decryption/encryption fails
// keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts
const msgRetryCounterMap: MessageRetryMap = {};
const handler = new MessageRetryHandler();
// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = useStore ? makeInMemoryStore({ logger }) : undefined;
store?.readFromFile("./baileys_store_multi.json");
// save every 10s
setInterval(() => {
store?.writeToFile("./baileys_store_multi.json");
}, 10_000);
const { state, saveState } = useSingleFileAuthState("./auth_info_multi.json");
// start a connection
const startSock = async () => {
// fetch latest version of WA Web
const { version, isLatest } = await fetchLatestBaileysVersion();
console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);
const sock = makeWASocket({
version,
logger,
printQRInTerminal: true,
auth: state,
msgRetryCounterMap,
// implement to handle retries
getMessage: handler.messageRetryHandler,
});
store?.bind(sock.ev);
const sendMessageWTyping = async (msg: AnyMessageContent, jid: string) => {
await sock.presenceSubscribe(jid);
await delay(500);
await sock.sendPresenceUpdate("composing", jid);
await delay(2000);
await sock.sendPresenceUpdate("paused", jid);
await sock.sendMessage(jid, msg).then(handler.addMessage);
};
sock.ev.on("call", (item) => console.log("recv call event", item));
sock.ev.on("chats.set", (item) =>
console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`)
);
sock.ev.on("messages.set", (item) =>
console.log(
`recv ${item.messages.length} messages (is latest: ${item.isLatest})`
)
);
sock.ev.on("contacts.set", (item) =>
console.log(`recv ${item.contacts.length} contacts`)
);
sock.ev.on("messages.upsert", async (m) => {
console.log(JSON.stringify(m, undefined, 2));
const msg = m.messages[0];
if (!msg.key.fromMe && m.type === "notify" && doReplies) {
console.log("replying to", m.messages[0].key.remoteJid);
await sock!.sendReadReceipt(msg.key.remoteJid, msg.key.participant, [
msg.key.id,
]);
await sendMessageWTyping({ text: "Hello there!" }, msg.key.remoteJid);
}
});
sock.ev.on("messages.update", (m) => console.log(m));
sock.ev.on("message-receipt.update", (m) => console.log(m));
sock.ev.on("presence.update", (m) => console.log(m));
sock.ev.on("chats.update", (m) => console.log(m));
sock.ev.on("contacts.upsert", (m) => console.log(m));
sock.ev.on("connection.update", (update) => {
const { connection, lastDisconnect } = update;
if (connection === "close") {
// reconnect if not logged out
if (
(lastDisconnect?.error as Boom)?.output?.statusCode !==
DisconnectReason.loggedOut
) {
startSock();
} else {
console.log("Connection closed. You are logged out.");
}
}
console.log("connection update", update);
});
// listen for when the auth credentials is updated
sock.ev.on("creds.update", saveState);
return sock;
};
startSock();
This doesn't work, does anyone have any idea why? I tried @Manjit2003 code and I get the same message Waiting for this message....
messages show on phone but still show pending on desktop login
@Manjit2003
Reinstall desktop whatsapp app
@picblog229 Here you go,
import { MessageRetryHandler } from "./retryHandler"; import { Boom } from "@hapi/boom"; import { useSingleFileAuthState } from "./authState"; import makeWASocket, { AnyMessageContent, DisconnectReason, fetchLatestBaileysVersion, makeInMemoryStore, } from "@adiwajshing/baileys"; import pino from "pino"; const logger = pino(); logger.level = "trace"; const useStore = !process.argv.includes("--no-store"); const doReplies = !process.argv.includes("--no-reply"); // external map to store retry counts of messages when decryption/encryption fails // keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts const msgRetryCounterMap: MessageRetryMap = {}; const handler = new MessageRetryHandler(); // the store maintains the data of the WA connection in memory // can be written out to a file & read from it const store = useStore ? makeInMemoryStore({ logger }) : undefined; store?.readFromFile("./baileys_store_multi.json"); // save every 10s setInterval(() => { store?.writeToFile("./baileys_store_multi.json"); }, 10_000); const { state, saveState } = useSingleFileAuthState("./auth_info_multi.json"); // start a connection const startSock = async () => { // fetch latest version of WA Web const { version, isLatest } = await fetchLatestBaileysVersion(); console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`); const sock = makeWASocket({ version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: handler.messageRetryHandler, }); store?.bind(sock.ev); const sendMessageWTyping = async (msg: AnyMessageContent, jid: string) => { await sock.presenceSubscribe(jid); await delay(500); await sock.sendPresenceUpdate("composing", jid); await delay(2000); await sock.sendPresenceUpdate("paused", jid); await sock.sendMessage(jid, msg).then(handler.addMessage); }; sock.ev.on("call", (item) => console.log("recv call event", item)); sock.ev.on("chats.set", (item) => console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`) ); sock.ev.on("messages.set", (item) => console.log( `recv ${item.messages.length} messages (is latest: ${item.isLatest})` ) ); sock.ev.on("contacts.set", (item) => console.log(`recv ${item.contacts.length} contacts`) ); sock.ev.on("messages.upsert", async (m) => { console.log(JSON.stringify(m, undefined, 2)); const msg = m.messages[0]; if (!msg.key.fromMe && m.type === "notify" && doReplies) { console.log("replying to", m.messages[0].key.remoteJid); await sock!.sendReadReceipt(msg.key.remoteJid, msg.key.participant, [ msg.key.id, ]); await sendMessageWTyping({ text: "Hello there!" }, msg.key.remoteJid); } }); sock.ev.on("messages.update", (m) => console.log(m)); sock.ev.on("message-receipt.update", (m) => console.log(m)); sock.ev.on("presence.update", (m) => console.log(m)); sock.ev.on("chats.update", (m) => console.log(m)); sock.ev.on("contacts.upsert", (m) => console.log(m)); sock.ev.on("connection.update", (update) => { const { connection, lastDisconnect } = update; if (connection === "close") { // reconnect if not logged out if ( (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut ) { startSock(); } else { console.log("Connection closed. You are logged out."); } } console.log("connection update", update); }); // listen for when the auth credentials is updated sock.ev.on("creds.update", saveState); return sock; }; startSock();
Using this example code the problem appeared: "waiting for this message. this may take a while".
Analyzing the logs this appears several times:
{
"level": 30,
"time": 1653081636518,
"pid": 11,
"hostname": "7141cc37f605",
"attrs": {
"from": "[email protected]",
"type": "retry",
"id": "BAE52F42979AB40B",
"participant": "[email protected]",
"t": "1653081626"
},
"key": {
"remoteJid": "[email protected]",
"id": "",
"fromMe": true,
"participant": "[email protected]"
},
"msg": "will not send message again, as sent too many times"
}
To improve error identification, I added this code snippet in function getMessage
:
const sock = makeWASocket({
version,
logger,
printQRInTerminal: true,
auth: state,
msgRetryCounterMap,
// implement to handle retries
getMessage: async (key) => {
const msg = await handler.messageRetryHandler(key);
console.log(`Get message ${JSON.stringify(key)} for resend, ${msg ? 'found' : 'not_found'}`);
return msg;
}
});
Resulting in
"Get message {"remoteJid":"[email protected]","id":"BAE52F42979AB40B","fromMe":true,"participant":"[email protected]"} for resend, found"
What would that error ("will not send message again, as sent too many times") be? is it possible to solve?
@Manjit2003 thanks for posting the code. But I am still getting following compile error:. Can you please have a look.
TSError: ⨯ Unable to compile TypeScript: Example/example.ts:55:41 - error TS2345: Argument of type '(message: proto.IWebMessageInfo) => Promise<proto.IWebMessageInfo>' is not assignable to parameter of type '(value: WebMessageInfo) => IWebMessageInfo | PromiseLike<IWebMessageInfo>'. Types of parameters 'message' and 'value' are incompatible. Type 'WebMessageInfo' is not assignable to type 'IWebMessageInfo'. Types of property 'messageStubType' are incompatible. Type 'import("/home/emr2043/asp_w/w/WAProto/index").proto.WebMessageInfo.WebMessageInfoStubType' is not assignable to type 'import("/home/emr2043/asp_w/w/node_modules/@adiwajshing/baileys/WAProto/index").proto.WebMessageInfo.WebMessageInfoStubType'. Property 'COMMUNITY_UNLINK_PARENT_GROUP' is missing in type 'import("/home/emr2043/asp_w/w/node_modules/@adiwajshing/baileys/WAProto/index").proto.WebMessageInfo.WebMessageInfoStubType'.
55 await sock.sendMessage(jid, msg).then(handler.addMessage);
@picblog229 can you please send me the code....
@LeonardoBein try debugging with this code snippet,
const sock = makeWASocket({
version,
logger,
printQRInTerminal: true,
auth: state,
msgRetryCounterMap,
// implement to handle retries
getMessage: async (key) => {
const msg = await handler.getMessage(message.id ?? "");
console.log(`Get message ${JSON.stringify(key)} for resend, ${msg ? 'found' : 'not_found'}`);
}
});
@picblog229 Here you go,
import { MessageRetryHandler } from "./retryHandler"; import { Boom } from "@hapi/boom"; import { useSingleFileAuthState } from "./authState"; import makeWASocket, { AnyMessageContent, DisconnectReason, fetchLatestBaileysVersion, makeInMemoryStore, } from "@adiwajshing/baileys"; import pino from "pino"; const logger = pino(); logger.level = "trace"; const useStore = !process.argv.includes("--no-store"); const doReplies = !process.argv.includes("--no-reply"); // external map to store retry counts of messages when decryption/encryption fails // keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts const msgRetryCounterMap: MessageRetryMap = {}; const handler = new MessageRetryHandler(); // the store maintains the data of the WA connection in memory // can be written out to a file & read from it const store = useStore ? makeInMemoryStore({ logger }) : undefined; store?.readFromFile("./baileys_store_multi.json"); // save every 10s setInterval(() => { store?.writeToFile("./baileys_store_multi.json"); }, 10_000); const { state, saveState } = useSingleFileAuthState("./auth_info_multi.json"); // start a connection const startSock = async () => { // fetch latest version of WA Web const { version, isLatest } = await fetchLatestBaileysVersion(); console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`); const sock = makeWASocket({ version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: handler.messageRetryHandler, }); store?.bind(sock.ev); const sendMessageWTyping = async (msg: AnyMessageContent, jid: string) => { await sock.presenceSubscribe(jid); await delay(500); await sock.sendPresenceUpdate("composing", jid); await delay(2000); await sock.sendPresenceUpdate("paused", jid); await sock.sendMessage(jid, msg).then(handler.addMessage); }; sock.ev.on("call", (item) => console.log("recv call event", item)); sock.ev.on("chats.set", (item) => console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`) ); sock.ev.on("messages.set", (item) => console.log( `recv ${item.messages.length} messages (is latest: ${item.isLatest})` ) ); sock.ev.on("contacts.set", (item) => console.log(`recv ${item.contacts.length} contacts`) ); sock.ev.on("messages.upsert", async (m) => { console.log(JSON.stringify(m, undefined, 2)); const msg = m.messages[0]; if (!msg.key.fromMe && m.type === "notify" && doReplies) { console.log("replying to", m.messages[0].key.remoteJid); await sock!.sendReadReceipt(msg.key.remoteJid, msg.key.participant, [ msg.key.id, ]); await sendMessageWTyping({ text: "Hello there!" }, msg.key.remoteJid); } }); sock.ev.on("messages.update", (m) => console.log(m)); sock.ev.on("message-receipt.update", (m) => console.log(m)); sock.ev.on("presence.update", (m) => console.log(m)); sock.ev.on("chats.update", (m) => console.log(m)); sock.ev.on("contacts.upsert", (m) => console.log(m)); sock.ev.on("connection.update", (update) => { const { connection, lastDisconnect } = update; if (connection === "close") { // reconnect if not logged out if ( (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut ) { startSock(); } else { console.log("Connection closed. You are logged out."); } } console.log("connection update", update); }); // listen for when the auth credentials is updated sock.ev.on("creds.update", saveState); return sock; }; startSock();
this work for me, but generate large files, how can delete?, i trying add setinterval every 6 hours but this delete and recreate same size file
store:function(h){
if(!stores[h]){
stores[h] = makeInMemoryStore({ logger });
stores[h].readFromFile( __dirname + '/sessions/' + h + '_store.json');
setInterval(() => {
stores[h].writeToFile( __dirname + '/sessions/' + h + '_store.json')
}, 10000)
setInterval(()=>{
if (fs.existsSync(__dirname + '/sessions/' + h + '_store.json')) {
fs.unlinkSync(__dirname + '/sessions/' + h + '_store.json')
}
}, 1000*60*60*6)
return stores[h];
}else{
return stores[h];
}
}
@LeonardoBein try debugging with this code snippet,
const sock = makeWASocket({ version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: async (key) => { const msg = await handler.getMessage(message.id ?? ""); console.log(`Get message ${JSON.stringify(key)} for resend, ${msg ? 'found' : 'not_found'}`); } });
Did not solve. Continue with the same error.
@adiwajshing please also look into this bug... waiting for solution from last 20-25days
Updated to latest version and i add the message memory store and it works for me.
Updated to latest version and i add the message memory store and it works for me.
Can you show a example for us? I did all of sugestions and nothing works for me
You all can use
import { proto } from "@adiwajshing/baileys"; export class MessageRetryHandler { public messagesMap: Record<string, proto.IMessage>; constructor() { this.messagesMap = {}; } addMessage = async (message: proto.IWebMessageInfo) => { const id = message.key.id ?? ""; console.log(this); this.messagesMap[id] = this.cleanMessage(message); return message; }; getMessage = (msgKey: string): proto.IMessage => { return this.messagesMap[msgKey]; }; removeMessage = (msgKey: string) => { delete this.messagesMap[msgKey]; }; getMessageKeys = (): string[] => { return Object.keys(this.messagesMap); }; cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => { const msg = message.message ?? {}; return msg; }; messageRetryHandler = async (message: proto.IMessageKey) => { const msg = this.getMessage(message.id ?? ""); // Remove msg from map this.removeMessage(message.id ?? ""); return msg; }; }
Then implement it as
const handler = new MessageRetryHandler(); const socketConfig: Partial<SocketConfig> = { printQRInTerminal: false, logger: PinoLogger({ level: "silent", }), getMessage: handler.messageRetryHandler, };
And when sending messages,
const sentMessage = await socket.sendMessage(id, { text: text, }) .then(handler.addMessage);
This will handle all types of messages automatically, just remember to add the
.then(handler.addMessage);
after the message.
This solution is working, but not always. Some messages are retried 5 times without success and then it gives up.
Waiting for this message. This may take a while. Learn more. click on learn more. you will find you need send message to sync with other instance (Whatsapp web and mobile), it's because end to end encryption. Add Message Store to have sync data. this what i think so.
You all can use
import { proto } from "@adiwajshing/baileys"; export class MessageRetryHandler { public messagesMap: Record<string, proto.IMessage>; constructor() { this.messagesMap = {}; } addMessage = async (message: proto.IWebMessageInfo) => { const id = message.key.id ?? ""; console.log(this); this.messagesMap[id] = this.cleanMessage(message); return message; }; getMessage = (msgKey: string): proto.IMessage => { return this.messagesMap[msgKey]; }; removeMessage = (msgKey: string) => { delete this.messagesMap[msgKey]; }; getMessageKeys = (): string[] => { return Object.keys(this.messagesMap); }; cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => { const msg = message.message ?? {}; return msg; }; messageRetryHandler = async (message: proto.IMessageKey) => { const msg = this.getMessage(message.id ?? ""); // Remove msg from map this.removeMessage(message.id ?? ""); return msg; }; }
Then implement it as
const handler = new MessageRetryHandler(); const socketConfig: Partial<SocketConfig> = { printQRInTerminal: false, logger: PinoLogger({ level: "silent", }), getMessage: handler.messageRetryHandler, };
And when sending messages,
const sentMessage = await socket.sendMessage(id, { text: text, }) .then(handler.addMessage);
This will handle all types of messages automatically, just remember to add the
.then(handler.addMessage);
after the message.This solution is working, but not always. Some messages are retried 5 times without success and then it gives up.
Did you found a fix for this? I am having this same issue.
You all can use
import { proto } from "@adiwajshing/baileys"; export class MessageRetryHandler { public messagesMap: Record<string, proto.IMessage>; constructor() { this.messagesMap = {}; } addMessage = async (message: proto.IWebMessageInfo) => { const id = message.key.id ?? ""; console.log(this); this.messagesMap[id] = this.cleanMessage(message); return message; }; getMessage = (msgKey: string): proto.IMessage => { return this.messagesMap[msgKey]; }; removeMessage = (msgKey: string) => { delete this.messagesMap[msgKey]; }; getMessageKeys = (): string[] => { return Object.keys(this.messagesMap); }; cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => { const msg = message.message ?? {}; return msg; }; messageRetryHandler = async (message: proto.IMessageKey) => { const msg = this.getMessage(message.id ?? ""); // Remove msg from map this.removeMessage(message.id ?? ""); return msg; }; }
Then implement it as
const handler = new MessageRetryHandler(); const socketConfig: Partial<SocketConfig> = { printQRInTerminal: false, logger: PinoLogger({ level: "silent", }), getMessage: handler.messageRetryHandler, };
And when sending messages,
const sentMessage = await socket.sendMessage(id, { text: text, }) .then(handler.addMessage);
This will handle all types of messages automatically, just remember to add the
.then(handler.addMessage);
after the message.This solution is working, but not always. Some messages are retried 5 times without success and then it gives up.
Did you found a fix for this? I am having this same issue.
Not really a fix, but I send a new message after 5 failed retries.
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me you should implement getMessage on making socket
- fetch a message from your store
- implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Thank you so much, I am gonna implement this now.
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me
you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Sorry
This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days
any solution :(?
we must create new file?
@adiwajshing I've two related finds.
- retryCount for sendMessageAgain is calculated per message, but often we need to resend same message to different devices.
- I've added dynamic delay between assertSessions and relayMessage in sendMessageAgain and the number of "waiting" messages become significantly reduced. Can I send patch to you for that?
@adiwajshing У меня есть две связанные находки.
- retryCount для sendMessageAgain рассчитывается для каждого сообщения, но часто нам нужно повторно отправлять одно и то же сообщение на разные устройства.
- Я добавил динамическую задержку между assertSessions и relayMessage в sendMessageAgain, и количество "ожидающих" сообщений значительно сократилось.Могу ли я отправить вам патч для этого?
Hi, please show this solution in the comments
patch in attachment messages-recv.txt
In general, do you have any thoughts about what this problem is related to?
Also examples of getMessage above are not correct. They delete saved message after first get, but we can do up to 5 attempts to resend message.
In general, do you have any thoughts about what this problem is related to?
No :(
In general, do you have any thoughts about what this problem is related to?
No :(
We are also guessing
It's strange that on version 4.1.0, before the fixes about a month ago, everything works correctly
исправление во вложении messages-recv.txt
Мне не помогло: ( Кто-нибудь помог? also no
Does anyone have a working solution? Even if it's not very good. Very necessary
not working
I saw a fix in the bible, but it didn't help for me. Are there those who work for?
I saw a fix in the bible, but it didn't help for me. Are there those who work for?
Statistic becomes better with this getMessage method and new baileys fixes. But about 20% of messages are still not delivered https://discord.com/channels/725839806084546610/891299313932722247/975018675306373140
I also have this problem
Please help us @adiwajshing I have the same problem.
me too..
This problem persists.
Please help us @adiwajshing I have the same problem.
I have same problem, please help.
any solution!? problem already exists
i have the same problem...
A temporary solution add an delay in getMessage For some reason baileys calls this function before the callback that saves the message
Thanks @mrhb6006 , and @Manjit2003
any update ?
Hi I have same problem And I get this error only on new chat and for first message !!!
Some one give us a fix for this issue, receivers are not able to see the message content
I can pay for any available solution :)
Please use baileys version 4.1.0 till the issue is not resolved.
same issue here. Does the delay in getMessage has any effect?
any update ?
When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched please help me
you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>
example : implement a store at temporaryStore file (I created this file myself)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
can you help me fixing the issue ? I am looking to some one who can fix it in my app
Please use baileys version 4.1.0 till the issue is not resolved.
Has anyone tried it with that version?
Yes, but no difference.. Tried also latest commit but no luck.
Statistic becomes better with this getMessage method and new baileys fixes. But about 20% of messages are still not delivered https://discord.com/channels/725839806084546610/891299313932722247/975018675306373140
retry sending with getMessage not always works for me, sometimes message still waiting
same issue
Statistic becomes better with this getMessage method and new baileys fixes. But about 20% of messages are still not delivered https://discord.com/channels/725839806084546610/891299313932722247/975018675306373140
retry sending with getMessage not always works for me, sometimes message still waiting
same issue. is there anything we can do to resend the message even after attemp failed? it's hard to reproduce the failed after 5 attemp retries issue as it only occasionally happen
same issue
As I explained before, this method works for me and solved the problem
https://github.com/adiwajshing/Baileys/issues/1631#issuecomment-1129573412
Read this comment and the comments below it carefully
As I explained before, this method works for me and solved the problem
Read this comment and the comments below it carefully
Hi Brother, can you help me fix the issue in my script, I am ready to have a deal
thanks
As I explained before, this method works for me and solved the problem #1631 (comment) Read this comment and the comments below it carefully
Hi Brother, can you help me fix the issue in my script, I am ready to have a deal
thanks
@MuhammadKarzoun We already implemented this in our script with the store function, but it consumes more Ram and did not work
Using Baileys 4.1.0 with store is helps. Latest version have the problem unsolved. Observing 300+ instances of Baileys.
Using Baileys 4.1.0 with store is helps. Latest version have the problem unsolved. Observing 300+ instances of Baileys.
which kind of store? multifile session or single file? any msghdlr? plz give us an example code tnx!
Still relevant
Very relevant.
By store i mean messages store + message handler from above. Session is stored in remote database.
getMessage: async (key): Promise<proto.IMessage | undefined> => {
Logger.print({ retry_message: key });
const { id } = key;
if (id) {
const found = Storage.getSent(id);
if (found) {
Logger.print({ retry_found: key });
return found;
} else Logger.print({ retry_no_found: key });
}
}
same issue
This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days
+1
Still relevant
This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days
Quando eu envio uma mensagem para um novo número, a primeira mensagem não aparece ...Mostrar apenas "Aguardando esta mensagem. Isso pode demorar um pouco" captura de tela anexada , por favor me ajude
você deve implementar getMessage ao fazer soquete * buscar uma mensagem de sua loja * implementar isso para que as mensagens com falha no envio (resolve o problema "esta mensagem pode demorar um pouco") possam ser repetidas getMessage: (chave: proto.IMessageKey) => Promessa<proto.IMessage | undefined> exemplo: implemente uma loja no arquivo temporárioStore (eu mesmo criei este arquivo)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Mano, obrigado por tentar nos ajudar, é possível usar esta solução para enviar url de mídia e botões?
sim , apenas salve toda a estrutura da mensagem em vez do texto da mensagem no temporárioStore e retorne isso no retryMessageHandler
Também pensei nisso! Deve resolver para cada tipo de mensagem já que a estrutura é salva completamente e não só o texto
Quando eu envio uma mensagem para um novo número, a primeira mensagem não aparece ...Mostrar apenas "Aguardando esta mensagem. Isso pode demorar um pouco" captura de tela anexada , por favor me ajude
você deve implementar getMessage ao fazer soquete * buscar uma mensagem de sua loja * implementar isso para que as mensagens com falha no envio (resolve o problema "esta mensagem pode demorar um pouco") possam ser repetidas getMessage: (chave: proto.IMessageKey) => Promessa<proto.IMessage | undefined> exemplo: implemente uma loja no arquivo temporárioStore (eu mesmo criei este arquivo)
let messages = [] function deleteMessage(messageID) { delete messages[messageID] } function saveMessage(messageID, txt) { messages[messageID] = txt } function getMessage(messageID) { return messages[messageID] } function clearMessages() { messages = [] } setInterval(clearMessages, 120000) export default { getMessage, saveMessage, deleteMessage } then at making socket : const retryMessageHandler = async message => { console.log("retry for send message !!!!!") let text = temporaryStore.getMessage(message.id) temporaryStore.deleteMessage(message.id) return { conversation: text } } sock = makeWASocket({ browser: config.getAgent(process.env.AGENT_NUMBER), version, logger, printQRInTerminal: true, auth: state, msgRetryCounterMap, // implement to handle retries getMessage: retryMessageHandler // at this line we use retryMessageHandler }) and finally after sending a message , save it at temporaryStore let whatsappRes = await sock.sendMessage(jid, {text: text}) temporaryStore.saveMessage(whatsappRes.key.id, text)
Mano, obrigado por tentar nos ajudar, é possível usar esta solução para enviar url de mídia e botões?
sim , apenas salve toda a estrutura da mensagem em vez do texto da mensagem no temporárioStore e retorne isso no retryMessageHandler
Também pensei nisso! Deve resolver para cada tipo de mensagem já que a estrutura é salva completamente e não só o texto
This solution in some chats not work for template buttons, buttons and media.
Still relevant
This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days
Still relevant
I would send a default message, before sending the right message. But it would be nice to know when this error happens, to simply resend the message again
+1
So that this does not happen, I only have to connect the account with baileys, if I open another session with whatsapp web the next day it starts to generate that problem