understanding commited on
Commit
b012c49
Β·
verified Β·
1 Parent(s): 4898cd3

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +35 -87
index.js CHANGED
@@ -1,97 +1,45 @@
1
- const makeWASocket = require('@whiskeysockets/baileys').default;
2
- const {
3
- DisconnectReason,
4
- useMultiFileAuthState,
5
- fetchLatestBaileysVersion
6
- } = require('@whiskeysockets/baileys');
7
- const fs = require('fs');
8
- const path = require('path');
9
- const Pino = require('pino');
10
 
11
- const logger = Pino({ level: 'info' });
12
-
13
- const store = {};
14
-
15
- const getMessage = key => {
16
- const { id } = key;
17
- if (store[id]) return store[id].message;
18
- };
19
-
20
- async function connectWhatsApp() {
21
- try {
22
- const { state, saveCreds } = await useMultiFileAuthState('auth');
23
- const { version } = await fetchLatestBaileysVersion();
24
-
25
- const sock = makeWASocket({
26
- auth: state,
27
- version: version,
28
- getMessage,
29
- printQRInTerminal: false // Disable QR code
30
- });
31
-
32
- // Request pairing code if not registered
33
- if (!sock.authState.creds.registered) {
34
- const phoneNumber = '+919709769655'; // Replace with your WhatsApp number
35
- try {
36
- const code = await sock.requestPairingCode(phoneNumber);
37
- console.log(`Pairing Code: ${code}`);
38
- console.log('Enter this code in WhatsApp under Linked Devices > Pair a New Device.');
39
- } catch (error) {
40
- console.error('Error requesting pairing code:', error);
41
- }
42
- }
43
 
 
44
  sock.ev.on('connection.update', async (update) => {
45
- const { connection, lastDisconnect } = update;
46
- if (connection === 'close') {
47
- if (lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut) {
48
- logger.info('Connection lost. Reconnecting...');
49
- await connectWhatsApp();
50
- } else {
51
- logger.info('Disconnected because you logged out.');
52
  }
53
- } else if (connection === 'open') {
54
- logger.info('Connection established.');
55
- }
56
  });
57
 
58
- sock.ev.on('creds.update', async () => {
59
- try {
60
- await saveCreds();
61
- logger.info('Credentials updated.');
62
- } catch (error) {
63
- logger.error('Failed to save credentials:', error);
64
- }
65
- });
66
-
67
- sock.ev.on('messages.upsert', async (events) => {
68
- const { messages } = events;
69
- messages.forEach(message => {
70
- const maskedNumber = maskPhoneNumber(message.key.remoteJid);
71
- logger.info(`Message from ${maskedNumber}:`, message);
72
- });
73
- });
74
-
75
- } catch (error) {
76
- logger.error('Failed to connect to WhatsApp:', error);
77
- }
78
- }
79
 
80
- function maskPhoneNumber(phoneNumber) {
81
- if (!phoneNumber) return phoneNumber;
82
- const parts = phoneNumber.split('@');
83
- if (parts.length === 2) {
84
- const [number, domain] = parts;
85
- const maskedNumber = number.slice(0, 3) + '*****' + number.slice(-3);
86
- return `${maskedNumber}@${domain}`;
87
- }
88
- return phoneNumber;
89
- }
90
 
91
- // Ensure the auth directory exists
92
- const authDir = path.join(__dirname, 'auth');
93
- if (!fs.existsSync(authDir)) {
94
- fs.mkdirSync(authDir, { recursive: true });
95
  }
96
 
97
- connectWhatsApp();
 
 
 
1
+ // index.js
2
+ import { makeWASocket, useMultiFileAuthState, DisconnectReason } from 'baileys';
3
+ import { handleMessage } from './bot/autoreply.js';
 
 
 
 
 
 
4
 
5
+ async function connectToWhatsApp() {
6
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
7
+ const sock = makeWASocket({ auth: state, printQRInTerminal: false });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ // Connection updates
10
  sock.ev.on('connection.update', async (update) => {
11
+ const { connection, lastDisconnect } = update;
12
+ if (connection === 'close') {
13
+ const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
14
+ if (shouldReconnect) connectToWhatsApp();
15
+ } else if (connection === 'open') {
16
+ console.log('WhatsApp connected!');
 
17
  }
 
 
 
18
  });
19
 
20
+ // Request pairing code if not registered
21
+ setTimeout(async () => {
22
+ if (!state.creds?.registered) {
23
+ try {
24
+ const number = '916234859346'; // Your WhatsApp number
25
+ console.log(`πŸ”„ Requesting pairing code for ${number}`);
26
+ const code = await sock.requestPairingCode(number);
27
+ console.log(`πŸ‘ Pairing Code: ${code}`);
28
+ console.log('1. Go to WhatsApp on your phone: Settings > Linked Devices > Add Device');
29
+ console.log('2. Enter the code above into the app to pair.');
30
+ } catch (error) {
31
+ console.error('Error requesting pairing code:', error);
32
+ }
33
+ }
34
+ }, 5000);
 
 
 
 
 
 
35
 
36
+ // Handle incoming messages
37
+ sock.ev.on('messages.upsert', (event) => handleMessage(event, sock));
38
+ sock.ev.on('creds.update', saveCreds);
 
 
 
 
 
 
 
39
 
40
+ return sock;
 
 
 
41
  }
42
 
43
+ connectToWhatsApp()
44
+ .then(() => console.log('Bot is running...'))
45
+ .catch(console.error);