Skip to content

Instantly share code, notes, and snippets.

@kuatroestrellas
Created April 23, 2023 08:16
Show Gist options
  • Save kuatroestrellas/5185647e43e682e8853c7fa12314a061 to your computer and use it in GitHub Desktop.
Save kuatroestrellas/5185647e43e682e8853c7fa12314a061 to your computer and use it in GitHub Desktop.
bot that redirects whatsapp messages to google chat (google workspace)
/**
* Bot que recibe mensajes de whatsapp en Google Chat
* web: https://kuatroestrellas.github.io/blog/
*
* requiere nodejs v12 o superior y las librerias qrcode-terminal, whatsapp-web.js y node-fetch
* npm i qrcode-terminal whatsapp-web.js node-fetch@2.6.1
**/
/**
* Sends asynchronous message into Google Chat
* @return{obj} response
*/
function webhook(testo) {
const fetch = require('node-fetch');
const webhookURL = 'YOUR-WEBHOOK-URL-GOOGLE-CHAT';
const data = JSON.stringify({
'text': testo,
});
let resp;
fetch(webhookURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: data,
}).then((response) => {
resp = response;
console.log(response);
});
return resp;
}
const qrcode = require('qrcode-terminal');
//Crea una sesión con whatsapp-web y la guarda localmente para autenticarse solo una vez por QR
const { Client, LocalAuth } = require('whatsapp-web.js');
const client = new Client({
authStrategy: new LocalAuth()
});
//Genera el código qr para conectarse a whatsapp-web
client.on('qr', qr => {
qrcode.generate(qr, {small: true});
});
//Si la conexión es exitosa muestra el mensaje de conexión exitosa
client.on('ready', () => {
console.log('Conexion exitosa nenes');
});
//Escucha los mensajes y los pasa a la funcion webhook
client.on('message', async message => {
console.log(message.body)
const contact = await message.getContact() //obtiene el numero del remitente
webhook(contact.id.user + ': ' + message.body) //enviar el mensaje recibido al webhook
});
//Inicializa el cliente whatsapp
client.initialize();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment