UNPKG

choco-bot

Version:

Whatsapp-bot

346 lines (302 loc) • 11 kB
const qrcode = require('qrcode-terminal'); const brain = require('./brain.js'); const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js'); const fs = require('fs'); const {archiveChat} = require('./commands/archive'); const {unarchiveChat} = require('./commands/unarchive'); const {takeover} = require('./commands/takeover'); const {reminder} = require('./commands/reminder'); const {createlist} = require('./commands/createlist'); const {addtolist} = require('./commands/addtolist'); const {dwp} = require('./commands/dwp'); const {invitetogroup} = require('./commands/invitetogroup'); const {currency_converter} = require('./commands/currency_converter'); const {screenshotweb} = require('./commands/screenshotweb'); const {dictionary} = require('./commands/dictionary'); const {processCommand} = require('./lib/processor'); const {restartGideon} = require('./lib/restart'); const {echoGroupMetadata} = require('./commands/groupdata.js') const {switchOffGideon} = require('./lib/switchOffGideon'); const {mergelist} = require('./commands/mergelist.js'); const lists = require('./lists.json'); const path = require('path'); const { getlist } = require('./commands/getlist.js'); const { getGroups } = require('choco-bot/commands/getgroups.js'); const { addToListById } = require('choco-bot/commands/addtolistbyid.js'); const { deleteList } = require('choco-bot/commands/deletelist.js'); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; let reminders = []; let gideonisActive = true; const logo = ` šŸ¤–šŸ¤–šŸ¤–šŸ¤–šŸ¤–šŸ¤–šŸ¤–šŸ¤– ` const chopper = ` ▬▬▬..ā—™..▬▬▬ ā–‚ā–„ā–„ā–„ā–“ā–„ā–„ā–‚ ā—¢ā—¤ā–ˆā–€ā–€ā–ˆā–ˆā–ˆā–ˆā–„ā–„ā–„ā–„ ◢◤ ā–ˆā–„ ā–ˆćƒ¼ ā–ˆā–ˆā–ˆā–€ā–€ā–€ā–€ā–€ā–€ā–€ā•¬ ā—„ā–ˆā–ˆā–ˆā–ˆā–ˆā—¤ ══╩══╩══ CHOCO BOT `; if (fs.existsSync('./reminders.json')) { const remindersData = fs.readFileSync('./reminders.json', 'utf-8'); reminders = JSON.parse(remindersData); } const client = new Client({ authStrategy: new LocalAuth() }); const apiKeys = ['npiAfgcFu114n7l8JXCBFOnjlWmyOl12']; let currentApiKeyIndex = 0; function switchApiKey() { currentApiKeyIndex = (currentApiKeyIndex + 1) % apiKeys.length; } client.on('qr', qr => { qrcode.generate(qr, { small: true }); }); client.on('ready', () => { console.log('CLIENT READY'); client.sendMessage('2348027329153@c.us', `CLIENT READY\n${chopper}`) client.sendMessage('2348027329153@c.us', `${logo}`) }); client.on('auth_failure', (msg) => { console.error('Authentication failed:', msg); }); client.on('disconnected', (reason) => { console.log('Client disconnected:', reason); }); function getRandomDelay() { return Math.floor(Math.random() * 10000); } async function sendMessageWithDelay(client, participantId, message, media) { await new Promise(resolve => setTimeout(resolve, getRandomDelay())); try { // Send the message await client.sendMessage(participantId, media, { caption: `${message}\n\n *CHOCO BOT V2*` }); } catch (error) { console.error(`Error sending message to ${participantId}: ${error}`); } } async function broadcast(remainingMessage, msg) { const chat = msg.getChat(); const mess = remainingMessage.trim(); const mess2 = mess.split(' '); const type = mess2[0]; if (type.toLowerCase() === "list") { const listName = mess2[1]; const messageParts = remainingMessage.split('/'); const bbb = messageParts[1]; if (messageParts.length < 2) { msg.reply("Usage: `broadcast (type) (listname if using list type) /message`"); } else { if (lists[listName]) { const participantsInList = lists[listName]; var count = 0; for (const participantId of participantsInList) { if (participantId !== client.info.me.user) { count++; await sendMessageWithDelay(client, '2348027329153@c.us', count); // Check if the message contains media (image or file) if (msg.hasMedia) { const media = await msg.downloadMedia(); await sendMessageWithDelay(client, participantId, bbb, media); } else { await sendMessageWithDelay(client, participantId, bbb); } } } msg.reply(`Broadcast sent to list "${listName}" participants.`); } else { msg.reply(`List "${listName}" does not exist.`); } } } else if (type.toLowerCase() === "group") { if (chat.isGroup) { const participants = chat.participants; for (const participant of participants) { const participantId = participant.id._serialized; if (participantId !== client.info.me.user) { await sendMessageWithDelay(client, participantId, remainingMessage.slice(4).trim(), null); } } msg.reply(`Broadcast sent to ${participants.length} participants.`); } else { msg.reply('Use in groups alone'); } } } function exportcontacts(remainingMessage, msg) { const format = remainingMessage.trim(); const chat = msg.getChat(); const chatname = chat.name + ' M'; let ran = 0; if (format === "vcf" || format === "csv") { const participants = chat.participants; if (!Array.isArray(participants)) { msg.reply("Participants data is not available."); return; } msg.reply("Alright *CHOCO LAID* processing command!"); let outputData = ''; for (let participant of participants) { ran += 1; const contact = client.getContactById(participant.id._serialized); const name = contact.pushname || chatname + ran; const phoneNumber = contact.id.user; if (format === "vcf") { // Create a vCard const vCard = `BEGIN:VCARD VERSION:3.0 FN:${name} TEL:${phoneNumber} END:VCARD\n`; outputData += vCard; } else if (format === "csv") { // Create a CSV entry outputData += `${name},${phoneNumber}\n`; } } const fileExtension = format === "vcf" ? 'vcf' : 'csv'; fs.writeFileSync(`contacts.${fileExtension}`, outputData, 'utf-8'); const media = MessageMedia.fromFilePath(`./contacts.${fileExtension}`); // Send the contact file chat.sendMessage(media, { caption: 'List of Contacts' }); fs.unlinkSync(`./contacts.${fileExtension}`); } else { msg.reply("Unknown format. Supported formats: vcf, csv."); } } client.on('message_create', async (msg) => { const chat = await msg.getChat(); const chatId = chat.id._serialized; const message = msg.body && typeof msg.body === 'string' ? msg.body.trim() : ''; const device = msg.deviceType; console.log(message) if (gideonisActive) { processCommand(message, (command, remainingMessage) => { console.log(`Executing command: ${command}`); switch (command) { case 'archivechat': archiveChat(msg); break; case 'unarchivechat': unarchiveChat(msg); break; case 'takeover': takeover(remainingMessage, msg); break; case 'broadcast': //broadcast(remainingMessage, msg); break; case 'createlist': createlist(remainingMessage, msg); break; case 'addtolist': addtolist(remainingMessage, msg); break; case 'reminder': reminder(remainingMessage, msg, client, reminders); break; case 'invitetogroup': invitetogroup(remainingMessage, msg); break; case 'exportcontacts': exportcontacts(remainingMessage, msg); break; case 'currency_converter': currency_converter(remainingMessage, msg); break; case 'screenshotweb': screenshotweb(remainingMessage, msg); break; case 'dictionary': dictionary(remainingMessage, msg); break; case 'dwp': dwp(remainingMessage, msg); break; case 'groupdata': echoGroupMetadata(msg); break; case 'mergelist': mergelist(remainingMessage, msg, lists); break; case 'getlist': getlist(remainingMessage, msg); break; case 'getgroups': getGroups(client, msg); break; } }); } if (message.toLocaleLowerCase().startsWith('atlbi')){ const args = message.split(' '); const id = args[1]; const listname = args[2]; addToListById(id, listname, msg); } if (message.toLocaleLowerCase().startsWith('delete list')){ const listname = message.slice(12); deleteList(listname, msg); } if (message.toLowerCase() === '.switchoff') { switchOffGideon(); msg.reply(`*Gideon is now switched off and not listening to commands.*`); } if (message.toLowerCase() === '.restart') { restartGideon(); msg.reply(`*Gideon is now restarting. He will be back online shortly.*`); } if (msg.from === '2348027329153@c.us'){ if (message.toLowerCase().startsWith('reply')){ if (msg.hasQuotedMsg){ const text = msg.getQuotedMessage(); const rep = message.slice(6); const phoneNumberRegex = /(\d{3}-\d{3}-\d{4}|\d{3}-\d{4})/g; const phoneNumbers = text.match(phoneNumberRegex); const phn = phoneNumbers + '@c.us'; client.sendMessage(`${phn}`, rep); }else{ msg.reply('Please reply a message'); } } } if (message.toLowerCase().startsWith('.broadcast')){ const cccc = message.slice(10); broadcast(cccc, msg); } if (message.toLocaleLowerCase().startsWith('.edit')){ if (msg.hasQuotedMsg) { const quotedMsg = await msg.getQuotedMessage(); const newm = message.slice(6); quotedMsg.edit(newm).then((res)=>{ console.log(res) }).catch(errro => { console.error('Erro ao deletar') }) msg.react('āœļø') } } }); client.on('message', message => { if (!message.from == '2348027329153@c.us'){ const fff = message.from.split('@') const f2 = fff[0] client.sendMessage('2348027329153@c.us', `*NEW MESSAGE*\n\n*From: ${f2}*\n*Message:*\n${message.body}`); } }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static('public')); app.post('/sendMessage', (req, res) => { const message = req.body.message; console.log(`Received message: ${message}`); res.send({ success: true }); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); client.initialize();