0% found this document useful (0 votes)
25 views3 pages

Bot

This document is a JavaScript implementation of a WhatsApp bot using the 'whatsapp-web.js' library. The bot handles user interactions by sending welcome messages, requesting CPF information, and providing options for receiving invoices. It manages chat states and message queues to ensure smooth communication and avoid overlapping messages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views3 pages

Bot

This document is a JavaScript implementation of a WhatsApp bot using the 'whatsapp-web.js' library. The bot handles user interactions by sending welcome messages, requesting CPF information, and providing options for receiving invoices. It manages chat states and message queues to ensure smooth communication and avoid overlapping messages.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

const qrcode = require('qrcode-terminal');

const { Client } = require('whatsapp-web.js');


const client = new Client();
const DELAY_TIME = 5000;
const MESSAGE_COOLDOWN = 30000; // 30 seconds cooldown between welcome messages
const CHAT_STATES = {
INITIAL: 'INITIAL',
AWAITING_CPF: 'AWAITING_CPF',
AWAITING_OPTION: 'AWAITING_OPTION'
};
const userStates = new Map();
const messageQueue = new Map(); // Track messages in queue for each chat
const delay = ms => new Promise(res => setTimeout(res, ms));

async function sendMessageWithTyping(chat, message) {


try {
const chatId = chat.id._serialized;

// Check if there's already a message being sent to this chat


if (messageQueue.get(chatId)) {
return;
}

// Mark this chat as having a message in progress


messageQueue.set(chatId, true);

await chat.sendStateTyping();
await delay(DELAY_TIME);
await client.sendMessage(chat.id._serialized, message);

// Clear the message queue flag after sending


messageQueue.delete(chatId);
} catch (error) {
console.error('Erro ao enviar mensagem:', error);
// Make sure to clear the queue even if there's an error
messageQueue.delete(chat.id._serialized);
}
}

async function sendWelcomeSequence(chat) {


await sendMessageWithTyping(chat, getWelcomeMessage());
await delay(1000); // Small delay between messages
await sendMessageWithTyping(chat, getCPFRequestMessage());
}

function getFirstName(contact) {
return contact.pushname ? contact.pushname.split(" ")[0] : "Cliente";
}

function getWelcomeMessage() {
return "*Seja Bem Vindo(a) ao Canal de Atendimento da Desktop*";
}

function getCPFRequestMessage() {
return "Por favor, Digite o seu CPF:";
}

function getFaturaOptionsMessage() {
return "Como deseja receber sua fatura?\n\n1 - Pix (Aprovação imediata)\n2 -
Código do Boleto\n3 - Boleto em PDF";
}

function isValidCPFFormat(cpf) {
const numericCPF = cpf.replace(/\D/g, '');
const formatRegex = /^\d{11}$|^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
return formatRegex.test(cpf);
}

client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});

client.on('ready', () => {
console.log('Tudo certo! WhatsApp conectado.');
});

client.initialize();

client.on('message', async msg => {


try {
const chat = await msg.getChat();
const chatId = chat.id._serialized;
const contact = await msg.getContact();
const firstName = getFirstName(contact);

// First interaction or greeting message


if (!userStates.has(chatId) || msg.body.toLowerCase().match(/^(menu|oi|olá|
ola|bom dia|boa tarde|boa noite|Solicitar|via)$/)) {
// Only send welcome sequence if no message is currently being sent
if (!messageQueue.get(chatId)) {
await sendWelcomeSequence(chat);
userStates.set(chatId, { state: CHAT_STATES.AWAITING_CPF });
}
return;
}

let currentState = userStates.get(chatId);

switch (currentState.state) {
case CHAT_STATES.AWAITING_CPF:
if (isValidCPFFormat(msg.body)) {
currentState = {
state: CHAT_STATES.AWAITING_OPTION,
cpf: msg.body
};
userStates.set(chatId, currentState);
await sendMessageWithTyping(chat, getFaturaOptionsMessage());
} else {
await sendMessageWithTyping(chat, "Por favor, digite seu CPF em
um dos seguintes formatos:\n00000000000 ou 000.000.000-00");
}
break;

case CHAT_STATES.AWAITING_OPTION:
if (msg.body === "1" || msg.body === "2" || msg.body === "3") {
currentState = { state: CHAT_STATES.CPF, cpf:
currentState.cpf };
userStates.set(chatId, currentState);
await sendMessageWithTyping(chat, "Ok! Aguarde enquanto puxo
sua fatura no banco de dados..");
} else {
await sendMessageWithTyping(chat, "Por favor, escolha uma opção
válida:\n\n1 - Pix (Aprovação imediata)\n2 - Código do Boleto\n3 - Boleto em PDF");
}
break;
}
} catch (error) {
console.error('Erro no processamento da mensagem:', error);
// Make sure to clear the message queue if there's an error
messageQueue.delete(chat.id._serialized);
}
});

You might also like