example: revamp example and add options for unit tests

This commit is contained in:
Rajeh Taher
2026-01-18 17:53:09 +02:00
parent c4c22c9628
commit 5b5ac85443
+15 -22
View File
@@ -42,6 +42,10 @@ const question = (text: string) => new Promise<string>((resolve) => rl.question(
// start a connection
const startSock = async() => {
const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info')
// NOTE: For unit testing purposes only
if (process.env.ADV_SECRET_KEY) {
state.creds.advSecretKey = process.env.ADV_SECRET_KEY
}
// fetch latest version of WA Web
const { version, isLatest } = await fetchLatestBaileysVersion()
console.log(`using WA v${version.join('.')}, isLatest: ${isLatest}`)
@@ -64,27 +68,6 @@ const startSock = async() => {
getMessage
})
// Pairing code for Web clients
if (usePairingCode && !sock.authState.creds.registered) {
// todo move to QR event
const phoneNumber = await question('Please enter your phone number:\n')
const code = await sock.requestPairingCode(phoneNumber)
console.log(`Pairing code: ${code}`)
}
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)
}
// the process function lets you process all events that just occurred
// efficiently in a batch
sock.ev.process(
@@ -94,7 +77,7 @@ const startSock = async() => {
// maybe it closed, or we received all offline message or connection opened
if(events['connection.update']) {
const update = events['connection.update']
const { connection, lastDisconnect } = update
const { connection, lastDisconnect, qr } = update
if(connection === 'close') {
// reconnect if not logged out
if((lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
@@ -103,6 +86,16 @@ const startSock = async() => {
console.log('Connection closed. You are logged out.')
}
}
if (qr) {
// Pairing code for Web clients
if (usePairingCode && !sock.authState.creds.registered) {
const phoneNumber = await question('Please enter your phone number:\n')
const code = await sock.requestPairingCode(phoneNumber)
console.log(`Pairing code: ${code}`)
}
}
console.log('connection update', update)
}