create a script that will post messages in the google chat space and tag people in nodejs
- User
create a script that will post messages in the google chat space and tag people in nodejs
Assistant
create a script that will post messages in the google chat space and tag people in nodejs
Here's a step-by-step guide and script to post messages in Google Chat using a webhook and tag users in Node.js:
Google Chat Webhook URL:
webhookUrl (you'll need it later).Node.js Environment:
axios package (for HTTP requests):
npm install axios
post-google-chat.js)const axios = require('axios');
// Configuration
const webhookUrl = 'YOUR_WEBHOOK_URL'; // Replace with your Google Chat webhook URL
const message = 'Hello team! This is a test message. @user1@example.com @user2@example.com';
// Format the message with mentions
const formattedMessage = {
text: message,
mentions: [
{
userId: 'users/user1@example.com', // Format: "users/{email}"
mentionText: '@user1@example.com',
},
{
userId: 'users/user2@example.com',
mentionText: '@user2@example.com',
},
],
};
// Send the message to Google Chat
async function postToGoogleChat() {
try {
await axios.post(webhookUrl, formattedMessage);
console.log('Message sent successfully!');
} catch (error) {
console.error('Error sending message:', error.message);
}
}
// Execute the function
postToGoogleChat();
Webhook Setup:
The script uses the Google Chat webhook URL to send messages programmatically.
Message Formatting:
mentions array specifies which users to tag. Each entry includes:
userId: The user’s Google Workspace email in the format users/{email} (e.g., users/john.doe@example.com).mentionText: The exact text to display in the message (e.g., @john.doe@example.com).Sending the Message:
The script sends a POST request with the formatted message to the Google Chat webhook.
Replace placeholders in the script:
YOUR_WEBHOOK_URL → Your Google Chat webhook URL.@user1@example.com → Replace with the email addresses of users you want to tag.Run the script:
node post-google-chat.js
mentions entries for tagging multiple users.catch block).Let me know if you need further adjustments! 😊