File size: 2,907 Bytes
80a3011
 
 
 
 
 
 
 
e5ac680
80a3011
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { makeWASocket, useMultiFileAuthState, DisconnectReason } from '@whiskeysockets/baileys';
import { Boom } from '@hapi/boom';
import pino from 'pino';

// --- MAIN CONFIGURATION ---
// This is the proxy address using your custom domain and reserved port.
const PROXY_ADDRESS = 'ws://whatsapi.dpdns.org:30079';
// This is the phone number you will link the bot to.
const BOT_PHONE_NUMBER = '919709859065'; 
// This is the folder where your login session will be saved.
const AUTH_FOLDER = 'auth_info_baileys';

// --- CONNECTION LOGIC ---
async function connectToWhatsApp() {
  const { state, saveCreds } = await useMultiFileAuthState(AUTH_FOLDER);
  
  const sock = makeWASocket({
    logger: pino({ level: 'silent' }),
    printQRInTerminal: false,
    auth: state,
    socketConfig: {
      waWebSocketUrl: PROXY_ADDRESS
    }
  });

  // Use pairing code for login
  if (!sock.authState.creds.registered) {
    console.log(`No session found for ${BOT_PHONE_NUMBER}. Requesting pairing code...`);
    setTimeout(async () => {
      try {
        const code = await sock.requestPairingCode(BOT_PHONE_NUMBER);
        console.log(`\n====================================`);
        console.log(`   PAIRING CODE: ${code}`);
        console.log(`====================================\n`);
        console.log('Open WhatsApp on your phone > Linked Devices > Link with phone number');
      } catch(e) {
        console.error("Failed to request pairing code. Please restart the bot.", e);
      }
    }, 3000);
  }

  // Handle connection events
  sock.ev.on('connection.update', (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === 'close') {
      const shouldReconnect = (lastDisconnect.error instanceof Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
      console.log('Connection closed, reconnecting:', shouldReconnect);
      if (shouldReconnect) {
        connectToWhatsApp();
      }
    } else if (connection === 'open') {
      console.log('βœ… WhatsApp connection opened! Bot is online.');
    }
  });

  // Save credentials
  sock.ev.on('creds.update', saveCreds);

  // --- MESSAGE HANDLING LOGIC ---
  sock.ev.on('messages.upsert', async (event) => {
    try {
      const message = event.messages[0];
      if (!message || message.key.fromMe) return;

      const sender = message.key.remoteJid;
      const messageText = message.message?.conversation || message.message?.extendedTextMessage?.text || "";

      console.log(`Received message from ${sender}: "${messageText}"`);

      // Simple auto-reply logic
      if (messageText.toLowerCase() === 'hi') {
        await sock.sendMessage(sender, { text: 'Hello! 🌟 This is the bot.' }, { quoted: message });
        console.log(`Replied to ${sender}`);
      }
    } catch (error) {
      console.error('Error handling message:', error);
    }
  });
}

// Start the bot
connectToWhatsApp();