icon100

COMUNIDADE ZDG

TRELLO

ACESSE AGORA O PASSO A PASSO DETALHADO NA ÁREA DE MEMBROS DA COMUNIDADE ZDG.

INSCREVA-SE NO YOUTUBE

INSCREVA-SE NO TELEGRAM

icon100

Comunidade ZDG © 2020 | Praça Getúlio Vargas, 176, Alfenas – MG, CEP 37.130-073 | Tel: (35) 9 8875-4197 | E-mail: [email protected]Política de Privacidade | Termos de Uso
Art. 49 do Código de Defesa do Consumidor | GARANTIA TOTAL DE 7 DIAS | Este produto não garante a obtenção de resultados. Qualquer referência ao desempenho de uma estratégia não deve ser interpretada como uma garantia de resultados.

COMUNIDADE ZDG

TRELLO

LINKS

PASSO A PASSO

BOTZDG + TRELLO


1- INSTALAR GIT, NODE, CRIAR CONTA NO TRELLO (POWER UP)
2- INSTALAR A API
a. criar pasta e arquivos
b. npm install
c. configurar variaveis do trello (APP)
d. node botzdg_trello.js

PACKAGE.JSON

				
					{"name":"bot-zdg","version":"1.0.0","description":"bot-zdg: based on Whatsapp API","main":"app.js","scripts":{"start":"node .\botzdg_trello.js","start:dev":"nodemon app.js","test":"echo \"Error: no test specified\" && exit 1"},"keywords":["whatsapp-api","node.js"],"author":"Pedro","license":"MIT","dependencies":{"axios":"^1.5.0","express":"^4.17.1","express-fileupload":"^1.2.0","express-validator":"^6.9.2","http":"0.0.1-security","qrcode":"^1.4.4","qrcode-terminal":"^0.12.0","socket.io":"2.3.0","whatsapp-web.js":"https:\/\/github.com\/Julzk\/whatsapp-web.js\/tarball\/jkr_hotfix_7"},"devDependencies":{"nodemon":"^2.0.19"}}
				
			

INDEX.HTML

				
					<!DOCTYPE html>
<html>
<head>
	<title>WPP API by Pedrinho da NASA</title>
</head>
<body>

	<div id="app">
		<h1>WPP API</h1>
		<h3>Entre agora para comunidade ZDG: <a href="https://comunidaedzdg.com.br/">clique aqui</a></h3>
		<p>ZDG MOD</p>
		<img decoding="async" src="" alt="QR Code" id="qrcode">
		<h3>Logs:</h3>
		<ul class="logs"></ul>
	</div>

	<script type="rocketlazyloadscript" data-minify="1" src="https://comunidadezdg.com.br/wp-content/cache/min/1/ajax/libs/jquery/3.5.1/jquery.min.js?ver=1739334587" crossorigin="anonymous" defer></script>
	<script type="rocketlazyloadscript" data-minify="1" src="https://comunidadezdg.com.br/wp-content/cache/min/1/ajax/libs/socket.io/2.3.0/socket.io.js?ver=1739334587" crossorigin="anonymous" defer></script>
	<script type="rocketlazyloadscript">window.addEventListener('DOMContentLoaded', function() {
		$(document).ready(function() {
			var socket = io();

			socket.on('message', function(msg) {
				$('.logs').append($('<li>').text(msg));
			});

			socket.on('qr', function(src) {
				$('#qrcode').attr('src', src);
				$('#qrcode').show();
			});

			socket.on('ready', function(data) {
				$('#qrcode').hide();
			});

			socket.on('authenticated', function(data) {
				$('#qrcode').hide();
			});
		});
	});</script>
<script>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</script></body>
</html>

				
			

botzdg_trello.js

				
					const { Client, LocalAuth } = require('whatsapp-web.js');
const express = require('express');
const socketIO = require('socket.io');
const qrcode = require('qrcode');
const http = require('http');
const fileUpload = require('express-fileupload');
const port = 8000;
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
const fetch = require('node-fetch');

// TRELLO
const APIKey = '76dcf6f7a6e1aed951bec77a49d69796';
const APIToken = 'ATTA45dd59b413ed00c4cf3099adb6314ea9da8f67e3edf9247cb5d1cb7f7ac0cfbcDF7B0FC8';
const id = 'pfA5Spxc'

async function trelloGetList(){
  fetch(`https://api.trello.com/1/boards/${id}/lists?key=${APIKey}&token=${APIToken}`, {
    method: 'GET'
  })
    .then(response => {
      console.log(
        `Response: ${response.status} ${response.statusText}`
      );
      return response.json();
    })
    .then(data => {
      data.forEach(item => {
        console.log(`ID: ${item.id}, Name: ${item.name}`);
      });
    })
    .catch(err => console.error(err));
}

async function trelloCreateCard(list, name, desc){
  fetch(`https://api.trello.com/1/cards?idList=${list}&key=${APIKey}&token=${APIToken}&name=${name}&desc=${desc}`, {
    method: 'POST',
    headers: {
      'Accept': 'application/json'
    }
  })
    .then(response => {
      console.log(
        `Response: ${response.status} ${response.statusText}`
      );
      return response.text();
    })
    .then(text => console.log(text))
    .catch(err => console.error(err));
}

async function trelloUpdateCard(card, list, name){
  fetch(`https://api.trello.com/1/cards/${card}?key=${APIKey}&token=${APIToken}&idList=${list}&name=${name}`, {
    method: 'PUT',
    headers: {
      'Accept': 'application/json'
    }
  })
    .then(response => {
      console.log(
        `Response: ${response.status} ${response.statusText}`
      );
      return response.json();
    })
    .then(text => console.log(text))
    .catch(err => console.error(err));
}

async function trelloGetCard(item) {
  function checkDesc(cards) {
    for (const card of cards) {
      if (card.desc.includes(item)) {
        return card.id;
      }
    }
    return false;
  }
  try {
    const response = await fetch(`https://api.trello.com/1/boards/${id}/cards?key=${APIKey}&token=${APIToken}`, {
      method: 'GET'
    });
    const data = await response.json();
    const hasDescription = checkDesc(data);
    return hasDescription;
  } catch (err) {
    console.error(err);
    return false;
  }
}

trelloGetList();

app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));
app.use(fileUpload({
  debug: true
}));
app.use("/", express.static(__dirname + "/"))
app.get('/', (req, res) => {
  res.sendFile('index.html', {
    root: __dirname
  });
});

const client = new Client({
  authStrategy: new LocalAuth({ clientId: 'email' }),
  puppeteer: { headless: true,
    executablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-accelerated-2d-canvas',
      '--no-first-run',
      '--no-zygote',
      '--single-process', // <- this one doesn't works in Windows
      '--disable-gpu'
    ] }
});

client.initialize();

io.on('connection', function(socket) {
  socket.emit('message', '© BOT-ZDG - Iniciado');
  socket.emit('qr', './icon.svg');

client.on('qr', (qr) => {
    console.log('QR RECEIVED', qr);
    qrcode.toDataURL(qr, (err, url) => {
      socket.emit('qr', url);
      socket.emit('message', '© BOT-ZDG QRCode recebido, aponte a câmera  seu celular!');
    });
});

client.on('ready', async () => {
    socket.emit('ready', '© BOT-ZDG Dispositivo pronto!');
    socket.emit('message', '© BOT-ZDG Dispositivo pronto!');
    socket.emit('qr', './check.svg')	
    console.log('© BOT-ZDG Dispositivo pronto');
});

client.on('authenticated', () => {
    socket.emit('authenticated', '© BOT-ZDG Autenticado!');
    socket.emit('message', '© BOT-ZDG Autenticado!');
    console.log('© BOT-ZDG Autenticado');
});

client.on('auth_failure', function() {
    socket.emit('message', '© BOT-ZDG Falha na autenticação, reiniciando...');
    console.error('© BOT-ZDG Falha na autenticação');
});

client.on('change_state', state => {
  console.log('© BOT-ZDG Status de conexão: ', state );
});

client.on('disconnected', (reason) => {
  socket.emit('message', '© BOT-ZDG Cliente desconectado!');
  console.log('© BOT-ZDG Cliente desconectado', reason);
  client.initialize();
});
});

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

  const list0 = '65088638b9368e77f5987bc7' // Cliente Prospectado
  const list1 = '65088638b9368e77f5987bc8' // Orçamento Enviado
  const list2 = '65088638b9368e77f5987bc9' // Trabalho Concluído

  const idCard = await trelloGetCard(msg.from.replace(/\D/g, ''));

  if (msg.body !== null && msg.body !== '0' && msg.body !== '1' && msg.body !== '2'){
    client.sendMessage(msg.from, 'Escolha uma opção: \n0- Cliente\n1- Orçamento\n2- Concluído')
  }
  if (msg.body !== null && msg.body === '0'){
    client.sendMessage(msg.from, 'Card criado para a lista: Cliente Prospectado')
    if(idCard){
      await trelloUpdateCard(idCard, list0, 'Cliente Prospectado - ' + msg.from.replace(/\D/g, ''))
    }
    else{
      await trelloCreateCard(list0, 'Cliente Prospectado - ' + msg.from.replace(/\D/g, ''), 'https://wa.me/' + msg.from.replace(/\D/g, ''))
    }
  }
  if (msg.body !== null && msg.body === '1'){
    client.sendMessage(msg.from, 'Card criado para a lista: Orçamento Enviado')
    if(idCard){
      await trelloUpdateCard(idCard, list1, 'Orçamento Enviado - ' + msg.from.replace(/\D/g, ''))
    }
    else{
      await trelloCreateCard(list1, 'Orçamento Enviado - ' + msg.from.replace(/\D/g, ''), 'https://wa.me/' + msg.from.replace(/\D/g, ''))
    }
  }
  if (msg.body !== null && msg.body === '2'){
    client.sendMessage(msg.from, 'Card criado para a lista: Trabalho Concluído')
    if(idCard){
      await trelloUpdateCard(idCard, list2, 'Trabalho Concluído - ' + msg.from.replace(/\D/g, ''))
    }
    else{
      await trelloCreateCard(list2, 'Trabalho Concluído - ' + msg.from.replace(/\D/g, ''), 'https://wa.me/' + msg.from.replace(/\D/g, ''))
    }
  }
});

console.log("\nA Comunidade ZDG é a oportunidade perfeita para você aprender a criar soluções incríveis usando as APIs, sem precisar de experiência prévia com programação. Com conteúdo exclusivo e atualizado, você terá tudo o que precisa para criar robôs, sistemas de atendimento e automações do zero. O curso é projetado para iniciantes e avançados, e oferece um aprendizado prático e passo a passo para que você possa criar soluções incríveis.")
console.log("\nIncreva-se agora acessando link: comunidadezdg.com.br\n")
   
server.listen(port, function() {
  console.log('App running on *: ' + port);
});