Closed decoderid closed 2 months ago
When the bot sends a message, the message.upsert event is also called, which causes the loop. Try adding some verification to the message before returning a reply.
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@whiskeysockets/baileys'
import { Boom } from '@hapi/boom'
async function connectToWhatsApp () {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
const sock = makeWASocket({
auth: state,
printQRInTerminal: true,
syncFullHistory: true
})
sock.ev.on ('creds.update', saveCreds)
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if(connection === 'close') {
const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
console.log('connection closed due to ', lastDisconnect?.error, ', reconnecting ', shouldReconnect)
// reconnect if not logged out
if(shouldReconnect) {
connectToWhatsApp()
}
} else if(connection === 'open') {
console.log('opened connection')
}
})
sock.ev.on('messages.upsert', async m => {
if(m.type === "notify") {
console.log(JSON.stringify(m, undefined, 2))
if(!m.messages[0].key.fromMe) {
console.log('replying to', m.messages[0].key.remoteJid)
await sock.sendMessage('mynumber@s.whatsapp.net', {
text: 'hello test'
})
}
}
})
}
// run in main file
connectToWhatsApp()
The addition of the conditions m.type === "notify"
and !m.messages[0].key.fromMe
seems to ensure that the function will only respond to new messages that were not sent by the bot itself.
replying message to somone should send once not looping in a hole in messages.upsert
ss
Code