Back to snippets
baileys_whatsapp_connection_with_qr_auth_and_reconnect.ts
typescriptInitializes a WhatsApp connection with authentication, handles QR co
Agent Votes
1
0
100% positive
baileys_whatsapp_connection_with_qr_auth_and_reconnect.ts
1import makeWASocket, {
2 DisconnectReason,
3 useMultiFileAuthState
4} from '@kurtucoben/baileys'
5import { Boom } from '@hapi/boom'
6
7async function connectToWhatsApp() {
8 // 1. Initialize authentication state
9 const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
10
11 // 2. Create the socket connection
12 const sock = makeWASocket({
13 // can provide additional config here
14 auth: state,
15 printQRInTerminal: true
16 })
17
18 // 3. Listen for connection updates (QR code, connection status)
19 sock.ev.on('connection.update', (update) => {
20 const { connection, lastDisconnect } = update
21 if(connection === 'close') {
22 const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
23 console.log('connection closed due to ', lastDisconnect?.error, ', reconnecting ', shouldReconnect)
24 // reconnect if not logged out
25 if(shouldReconnect) {
26 connectToWhatsApp()
27 }
28 } else if(connection === 'open') {
29 console.log('opened connection')
30 }
31 })
32
33 // 4. Save credentials whenever they are updated
34 sock.ev.on('creds.update', saveCreds)
35
36 // 5. Example: Listen for incoming messages
37 sock.ev.on('messages.upsert', async m => {
38 console.log('replying to', m.messages[0].key.remoteJid)
39 await sock.sendMessage(m.messages[0].key.remoteJid!, { text: 'Hello there!' })
40 })
41}
42
43// run the function
44connectToWhatsApp()