Receive GitLab Comments on WhatsApp Using Webhooks

Effective communication is essential for successful project management, especially when dealing with multiple clients and complex projects. This tutorial will show you how to use GitLab webhooks to centralize communication and improve response times by integrating with WhatsApp.
Introduction
In this tutorial, we will walk through the steps to set up a system that listens for GitLab webhook events and sends notifications to WhatsApp using Node.js and the whatsapp-web.js
library. This system can help you keep track of important GitLab activities and ensure timely responses.
Prerequisites
To follow along with this tutorial, you will need:
- A GitLab account
- Node.js and npm installed
- A WhatsApp account
- Basic knowledge of JavaScript
Project Setup
First, create a new directory for your project and initialize a new Node.js application:
mkdir whatsapp-gitlab-integration
cd whatsapp-gitlab-integration
npm init -y
Next, install the required dependencies:
npm install whatsapp-web.js qrcode-terminal express body-parser puppeteer ai @ai-sdk/openai
Project Code
Create a new file named index.js
and add the following code:
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const express = require('express');
const bodyParser = require('body-parser');
const puppeteer = require('puppeteer');
const { generateText } = require('ai');
const { openai } = require('@ai-sdk/openai');
const HANDLE = 'marrouchi';
const PHONE_NUMBER = '21624309128@c.us';
// Personalize the contacts and companies arrays with your own information
const contacts = [
{ phoneNumber: PHONE_NUMBER, name: 'Anis Marrouchi', company: 'NOQTA', role: 'Founder' }
// Add more contacts as needed
];
const companies = [
{
name: 'NOQTA',
description: 'NOQTA is a web agency AI centered, based in Tunisia. We provide web & mobile development, AI & Automation, Cybersecurity, Consulting, IT Maintenance & support.',
projects: [
`Let's us build your next project together.`,
],
latestInteraction: ''
}
];
const app = express();
app.use(bodyParser.json());
const client = new Client({
authStrategy: new LocalAuth(),
puppeteer: {
executablePath: puppeteer.executablePath(),
args: ['--no-sandbox', '--disable-setuid-sandbox'],
timeout: 60000 // Increase timeout to 60 seconds
}
});
client.on('qr', (qr) => {
console.log('QR event received, generating QR code...');
qrcode.generate(qr, { small: true });
console.log('QR code generated, scan it using WhatsApp');
});
client.on('ready', () => {
console.log('WhatsApp client is ready!');
});
client.on('message', async (msg) => {
console.log('Message received:', msg.body);
const contact = contacts.find(contact => contact.phoneNumber === msg.from);
if (contact) {
const company = companies.find(company => company.name === contact.company);
const description = company ? company.description : '';
const projects = company ? company.projects.join(', ') : '';
const latestInteraction = company ? company.latestInteraction : '';
try {
// Generate a response using Vercel AI SDK
const { text } = await generateText({
model: openai('gpt-4o'), // Use the appropriate model from Vercel AI
system: `You are an AI assistant for a web agency, and your role is to reply to client messages in a professional manner. You provide clear, concise, and helpful responses based on the client's message and the company's context. if the client is my wife, you should reply with a lovely message. Always use the language of the sender.`,
prompt: `Company: ${contact.company}\nDescription: ${description}\nProjects: ${projects}\nLatest Interaction: ${latestInteraction}\nMessage: ${msg.body}`
});
// Send the generated response back to the user
msg.reply(text);
} catch (error) {
console.error('Error generating response:', error);
msg.reply('Sorry, I encountered an error while generating a response.');
}
} else {
console.log('Contact not found in the contacts array.');
}
});
client.initialize();
// Endpoint to handle GitLab webhooks
app.post('/webhook', (req, res) => {
const mentionEvent = req.body;
const mentionText = mentionEvent.object_attributes.note;
// Extract the mentioned user and message details
const mentionedUser = mentionEvent.user.name;
// If the mentionText contains the handle of the user, then send a message to the phone number
// Include the URL of the issue or merge request in the message
if (mentionText.includes(HANDLE)) {
const message = `You were mentioned in a GitLab note: "${mentionText}" \n ${mentionEvent.object_attributes.url}`;
// Send message via WhatsApp
client.sendMessage(PHONE_NUMBER, message)
.then(response => {
console.log('Message sent:', response);
res.status(200).send('Message sent successfully');
})
.catch(err => {
console.error('Failed to send message:', err);
res.status(500).send('Failed to send message');
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Exposing a Local Server Using ngrok
To test the webhook locally, you can use ngrok to expose your local server to the internet. Follow these steps:
-
Install ngrok:
npm install -g ngrok
-
Start your local server:
node index.js
-
Expose your local server:
ngrok http 3000
-
Get the public URL: ngrok will provide a public URL that you can use to configure the GitLab webhook. The URL will look something like this:
https://<random-string>.ngrok.io
-
Configure GitLab Webhook:
- Go to your GitLab project.
- Navigate to Settings > Webhooks.
- Add the ngrok URL as the webhook URL.
- Select the events you want to trigger the webhook (e.g., comments, issues).
Running a Publicly Accessible Server with PM2
For a production setup, you can use PM2 to run your server continuously and manage it efficiently. Here’s how to do it:
-
Install PM2:
npm install -g pm2
-
Start the server with PM2:
pm2 start index.js --name whatsapp-gitlab-integration
-
Monitor the server:
pm2 monit
-
Set up PM2 to restart on server reboot:
pm2 startup pm2 save
-
Configure GitLab Webhook:
- Use your server's public URL to configure the webhook in GitLab.
- Go to your GitLab project.
- Navigate to Settings > Webhooks.
- Add the server URL as the webhook URL.
- Select the events you want to trigger the webhook (e.g., comments, issues).
Conclusion
By integrating GitLab webhooks with WhatsApp, you can streamline communication and ensure that important updates and mentions are never missed. This setup allows for real-time notifications and responses, improving the overall efficiency and responsiveness of your project management workflow.
For more details, you can find the full project on GitHub: GitHub Repository
Discuss Your Project with Us
We're here to help with your web development needs. Schedule a call to discuss your project and how we can assist you.
Let's find the best solutions for your needs.