File size: 12,394 Bytes
ebccf84
 
 
 
 
 
 
7afc018
ebccf84
7afc018
 
e7a4a90
7afc018
6570f44
 
 
 
 
 
 
 
7afc018
 
 
 
 
6570f44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebccf84
 
 
 
 
 
 
 
 
 
 
e75a813
 
 
 
 
 
 
 
 
 
 
 
 
7afc018
 
 
 
e75a813
 
 
 
 
 
 
 
 
 
 
 
 
 
be0ac99
e75a813
 
7afc018
 
 
e75a813
be0ac99
7afc018
 
 
 
 
 
 
 
 
 
 
 
 
ebccf84
e75a813
ebccf84
e75a813
ebccf84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a4a90
ebccf84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
const { Client, LocalAuth } = require('whatsapp-web.js');
const xlsx = require('xlsx');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const fs = require('fs');
const path = require('path');
const qrcode = require('qrcode');
const CONFIG = require('./config');
const axios = require('axios');

async function getFreeProxy() {
    try {
        const response = await axios.get('https://www.proxy-list.download/api/v1/get?type=https');
        const proxyList = response.data.split('\n').filter(Boolean);
        
        for (let proxy of proxyList) {
            console.log("test => ", proxy);
            let isValid = await testProxy(proxy);
            if (isValid) return proxy;
        }
        
        return null;
    } catch (error) {
        console.error('Error fetching proxy:', error);
        return null;
    }
}

async function testProxy(proxy) {
    try {
        await axios.get('https://web.whatsapp.com/', {
            proxy: {
                host: proxy.split(':')[0],
                port: proxy.split(':')[1]
            },
            timeout: 5000
        });
        return true;
    } catch {
        return false;
    }
}

class WhatsAppAccountManager {
    constructor(accountId) {
        this.accountId = accountId;
        this.status = 'initializing';
        this.qrFile = path.join(CONFIG.SESSION_DIR, `qrcode_${accountId}.png`);
        this.sessionPath = path.join(CONFIG.SESSION_DIR, `session_${accountId}`);
        this.processDetails = [];
        if (!fs.existsSync(this.sessionPath)) {
            fs.mkdirSync(this.sessionPath, { recursive: true });
        }

        this.csvWriter = createCsvWriter({
            path: CONFIG.CSV_FILE,
            header: [
                { id: 'phone', title: 'PHONE' },
                { id: 'name', title: 'NAME' },
                { id: 'status', title: 'STATUS' },
                { id: 'error_code', title: 'ERROR_CODE' },
                { id: 'message', title: 'MESSAGE' },
                { id: 'is_invite_sent', title: 'INVITE_SENT' }
            ],
            append: true
        });

        (async () => {
            const proxy = await getFreeProxy();
            console.log(`[${this.accountId}] Using proxy:`, proxy);

            this.client = new Client({
                authStrategy: new LocalAuth({ clientId: accountId }),
    
                puppeteer: {
                    headless: true,
                    executablePath: '/usr/bin/google-chrome',
                    args: [
                        '--no-sandbox',
                        '--disable-setuid-sandbox',
                        `--user-data-dir=${this.sessionPath}`,
                        `--proxy-server=${proxy}`
                    ],
                }
            });
          
            this.setupHandlers();
            this.initializeClient();
           
        })();

       

        // this.client = new Client({
        //     authStrategy: new LocalAuth({ clientId: accountId }),

        //     puppeteer: {
        //         headless: true,
        //         executablePath: '/usr/bin/google-chrome',
        //         args: [
        //             '--no-sandbox',
        //             `--user-data-dir=${this.sessionPath}`,
        //             '--disable-setuid-sandbox'
        //         ],
        //     }
        // });

     

       
    }


    setupHandlers() {
        this.client.on('qr', async (qr) => {
            this.status = 'awaiting_qr';
            await qrcode.toFile(this.qrFile, qr, { scale: 2 });
            console.log(`[${this.accountId}] QR code generated`);
        });

        this.client.on('ready', () => {
            this.status = 'ready';
            console.log(`[${this.accountId}] Client ready`);
            this.processBatch();
        });

        this.client.on('disconnected', () => {
            this.status = 'disconnected';
            console.log(`[${this.accountId}] Client disconnected`);
        });
    }

    initializeClient() {
        this.client.initialize().catch(err => {
            console.error(`[${this.accountId}] Initialization error:`, err);
            this.status = 'error';
        });
    }

    loadSharedState() {
        try {
            return JSON.parse(fs.readFileSync(CONFIG.STATE_FILE));
        } catch {
            return {
                lastProcessed: 0,
                currentGroup: null,
                groupCounter: 1,
                activeGroups: []
            };
        }
    }

    saveSharedState(state) {
        fs.writeFileSync(CONFIG.STATE_FILE, JSON.stringify(state, null, 2));
    }

    readNumbers(lastProcessed) {
        try {
            const workbook = xlsx.readFile(CONFIG.EXCEL_FILE);
            const sheet = workbook.Sheets[workbook.SheetNames[0]];
            const rows = xlsx.utils.sheet_to_json(sheet);
            
            return rows
                .slice(lastProcessed, lastProcessed + CONFIG.DAILY_BATCH_SIZE)
                .map(row => ({
                    phone: `967${row['phone number']}@c.us`,
                    name: row['name']
                }));
        } catch (error) {
            console.error('Error reading numbers:', error);
            return [];
        }
    }


    async processBatch() {
        if (this.status !== 'running') return;

        try {
            const state = this.loadSharedState();
            const numbers = this.readNumbers(state.lastProcessed);
            
            if (numbers.length === 0) {
                console.log(`[${this.accountId}] No numbers to process`);
                return;
            }

            let groupId = state.currentGroup;
            if (!groupId || !await this.verifyGroup(groupId)) {
                groupId = await this.createGroup(state);
            }

            await this.processNumbers(groupId, numbers, state);
            
            this.saveSharedState(state);

            console.log(`[${this.accountId}] Processed ${numbers.length} numbers`);
        } catch (error) {
            console.error(`[${this.accountId}] Batch processing error:`, error);
        }
    }

    async verifyGroup(groupId) {
        try {
            const group = await this.client.getChatById(groupId);
            return group.participants.length < CONFIG.MAX_GROUP_SIZE;
        } catch {
            return false;
        }
    }

    async createGroup(state) {
        try {
            const   numberAdded = [
            '730442027@c.us', //1
            '730446721@c.us', //2
            '730426743@c.us',//3
            '730416694@c.us',//4
            '730436848@c.us',//5

        '736704949@c.us',//mohammed old

        '782726213@c.us',//6
        '737536699@c.us',//7
    
    
    
        '967739817442@c.us', //unclue
        '967780341777@c.us' //mohammed alhas
        ]

            
            const groupName = `${CONFIG.BASE_GROUP_NAME} ${state.groupCounter++}`;
            const creation = await this.client.createGroup(groupName, numberAdded);

            const group = await this.client.getChatById(creation.gid._serialized);
            await group.promoteParticipants([
                '730442027@c.us', 
                '730446721@c.us',
                '730426743@c.us',
                '730416694@c.us',
                '730436848@c.us',
                '782726213@c.us',
                '737536699@c.us',]);
            await group.setMessagesAdminsOnly(true);
            await group.setInfoAdminsOnly(true);

            state.currentGroup = creation.gid._serialized;
            state.activeGroups.push(creation.gid._serialized);
            return creation.gid._serialized;
        } catch (error) {
            console.error('Group creation failed:', error);
            throw error;
        }
    }

    async processNumbers(groupId, numbers, state) {
        try {
            const group = await this.client.getChatById(groupId);
            
            for (const { phone, name } of numbers) {
                const record = {
                    phone,
                    name,
                    status: 'PENDING',
                    error_code: '',
                    message: '',
                    is_invite_sent: false
                };

                try {
                    const contactId = await this.client.getNumberId(phone);
                    if (!contactId) {
                        record.status = 'INVALID';
                        record.message = 'Number not registered';
                        await this.csvWriter.writeRecords([record]);
                        continue;
                    }

                    const result = await group.addParticipants([phone], { autoSendInviteV4: false });
                    const participantResult = result[phone];

                    record.status = participantResult.code === 200 ? 'ADDED' : 'FAILED';
                    record.error_code = participantResult.code;
                    record.message = participantResult.message;
                    record.is_invite_sent = participantResult.isInviteV4Sent;

                    if (participantResult.code === 403 && !participantResult.isInviteV4Sent) {
                        await group.sendInvite(phone);
                        record.is_invite_sent = true;
                    }
                    this.processDetails.push(record);
                    await this.csvWriter.writeRecords([record]);
                    state.lastProcessed++;
                } catch (error) {
                    record.status = 'ERROR';
                    record.message = error.message;
                    this.processDetails.push(record);
                    await this.csvWriter.writeRecords([record]);
                }
            }
        } catch (error) {
            console.error('Number processing error:', error);
        }
    }


    async addNumberToGroup(phone, groupName) {
        try {
            if (!phone.endsWith('@c.us')) {
                phone = phone.replace(/\D/g, ''); // Remove non-numeric characters
                if (!phone.startsWith('967')) {
                    phone = `967${phone}`; // Add Yemen country code if missing
                }
                phone = `${phone}@c.us`; // Append @c.us suffix
            }
    
            console.log(`Formatted phone number: ${phone}`);
    
            // Get all chats and find the group
            const chats = await this.client.getChats();
            const group = chats.find(chat => chat.isGroup && chat.name === groupName);
    
            if (!group) {
                console.error(`Group '${groupName}' not found.`);
                return { success: false, message: "Group not found" };
            }
    
            const record = {
                phone,
                status: 'PENDING',
                error_code: '',
                message: '',
                is_invite_sent: false
            };
    
            // Check if number is valid
            const contactId = await this.client.getNumberId(phone);
            if (!contactId) {
                record.status = 'INVALID';
                record.message = 'Number not registered';
                await this.csvWriter.writeRecords([record]);
                return { success: false, message: "Number not registered" };
            }
    
            // Add participant
            const result = await group.addParticipants([phone], { autoSendInviteV4: false });
            const participantResult = result[phone];
    
            record.status = participantResult.code === 200 ? 'ADDED' : 'FAILED';
            record.error_code = participantResult.code;
            record.message = participantResult.message;
            record.is_invite_sent = participantResult.isInviteV4Sent;
    
            // Handle invitation if needed
            if (participantResult.code === 403 && !participantResult.isInviteV4Sent) {
                await group.sendInvite(phone);
                record.is_invite_sent = true;
            }
    
            await this.csvWriter.writeRecords([record]);
    
            return { success: participantResult.code === 200, message: participantResult.message };
    
        } catch (error) {
            console.error('Error adding number to group:', error);
            return { success: false, message: error.message };
        }
    }
    
}
module.exports = WhatsAppAccountManager;