-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectToWhatsApp.js
91 lines (73 loc) · 3.44 KB
/
connectToWhatsApp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const fs = require('fs/promises');
const path = require('path');
const { default: makeWASocket, useMultiFileAuthState, DisconnectReason } = require('baileys');
// Path for local storage on Fly.io
const sessionPath = path.join(__dirname, '/data', 'auth_info_baileys');
let sock; // Declare sock at a higher scope to manage the connection
async function connectToWhatsApp() {
if (sock) {
return sock; // Return existing socket if already connected
}
const { state: authState, saveCreds } = await useMultiFileAuthState(sessionPath);
sock = makeWASocket({
auth: authState,
printQRInTerminal: true, // Print QR code in terminal for authentication
syncFullHistory: false,
});
sock.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
console.log('Connection closed due to:', lastDisconnect?.error, ', reconnecting:', shouldReconnect);
if (!shouldReconnect) {
try {
await fs.rm(sessionPath, { recursive: true, force: true });
console.log("Old session files wiped successfully.");
} catch (err) {
console.error("Error wiping old files:", err);
}
try {
await fs.mkdir(sessionPath, { recursive: true });
console.log("New auth file directory created successfully.");
} catch (err) {
console.error("Error creating new auth file directory:", err);
}
}
sock = null; // Reset sock to allow reconnection
setTimeout(connectToWhatsApp, 5000);
}
else if (connection === 'open') {
console.log('Successfully opened connection');
}
});
sock.ev.on('creds.update', saveCreds); // Save credentials to local storage automatically
// Delay sending the first message by 30 seconds
setTimeout(async () => {
const jid = '96565022680@s.whatsapp.net'; // Replace with a valid recipient JID
try {
await sock.presenceSubscribe(jid);
await delay(500);
await sock.sendPresenceUpdate('composing', jid);
await delay(2000);
await sock.sendPresenceUpdate('paused', jid);
await sock.sendMessage(jid, { text: 'Booted Successfully' });
console.log('First message sent successfully after delay');
} catch (error) {
console.error('Failed to send the first message:', error);
}
}, 30000); // 30-second delay
sock.ev.on('messages.upsert', async (chatUpdate) => {
const message = chatUpdate.messages[0];
if (!message.key.fromMe && message.message && message.message.conversation) {
const text = message.message.conversation;
if (text === '!ping') {
const replyMessage = { text: 'pong' };
await sock.sendMessage(message.key.remoteJid, replyMessage);
console.log(`Sent reply: pong to ${message.key.remoteJid}`);
}
}
});
return sock; // Return the socket object
}
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
module.exports = connectToWhatsApp; // Export the function