Engineering

How to Automate Sending Slack Messages using Node.js

Automate Sending Slack Messages using Node.js

TL;DR

This blog explains two methods to automate sending Slack messages using Node.js, with example on fetching daily currency exchange rates.

Method #1: Using Node.js and ExchangeRatesAPI:

  1. Understand ExchangeRatesAPI and obtain an API key.
  2. Set up Slack webhook to receive notifications.
  3. Implement a Node.js script to fetch exchange rates and send Slack messages.

Method #2: Connect any API on Locale.ai for Slack alerts:

  1. Use Locale's API Connector to connect data sources through API.
  2. Create alerts in Locale and configure schedules for alert runs.
  3. Set up recipients and customize Slack messages.

Automating Slack messages with Node.js requires technical skills and may face scalability and maintenance challenges. However Locale.ai ‘s no-code platform offers a simpler solution to automate Slack messages from any API. It also offers dynamic notifications based on query results. This streamlines communication within teams without extensive development efforts.

In the modern workplace, regular updates and notifications are essential for keeping teams aligned and informed. One efficient way to achieve this is by automating Slack messages that carry important data from various APIs. This not only enhances productivity but also ensures that everyone is on the same page with the latest information.

In this blog, we'll demonstrate this concept using a practical example: sending automated Slack messages with daily currency exchange rates from the ExchangeRatesAPI. While we focus on currency data, this method can be adapted to various other APIs, making it a versatile solution for different business needs.

  1. Method #1: Using Node.js and ExchangeRatesAPI for Slack Notifications
  2. Method #2: Connect API on Locale and send Slack alert

Method #1: Using Node.js and ExchangeRatesAPI for Slack Notifications

Step 1: Understanding ExchangeRatesAPI

ExchangeRatesAPI provides real-time exchange rate data for over 200 currencies. It's a straightforward and accessible tool, ideal for our demonstration of fetching the USD to INR (US Dollar to Indian Rupee) exchange rate. The API is free for basic usage, which includes up to 1,000 monthly requests. To get started, sign up for their official website and obtain your API key.

Step 2: Setting Up a Slack Webhook

To automate Slack messages, the first step is to set up a Slack webhook:

  1. Go to your Slack workspace's App Directory.
  2. Search for and select Incoming WebHooks.
  3. Click Add to Slack to create a new webhook.
  4. Choose the channel to which you want the notifications to be posted.
  5. Click the Add Incoming WebHooks integration button.
  6. Copy the webhook URL provided — you'll use this in your Python script to send notifications to Slack.
Setup Slack Incoming Webhooks

Step 3: Implementing the Node.js Script

With your API key and Slack webhook URL, you can now create a Node.js script to send daily currency updates:


const axios = require('axios');

// Replace with your ExchangeRatesAPI key and Slack Webhook URL
const EXCHANGERATES_API_KEY = 'your_exchangerates_api_key';
const SLACK_WEBHOOK_URL = 'your_slack_webhook_url';

async function fetchExchangeRate() {
  try {
    const response = await axios.get(`http://api.exchangeratesapi.io/v1/latest?access_key=${EXCHANGERATES_API_KEY}&symbols=INR&base=USD`);
    return response.data.rates.INR;
  } catch (error) {
    console.error('Error fetching exchange rate:', error);
  }
}

async function sendSlackMessage(exchangeRate) {
  const message = `Today's USD to INR Exchange Rate: ${exchangeRate}`;
  try {
    await axios.post(SLACK_WEBHOOK_URL, { text: message });
    console.log('Exchange rate update sent to Slack');
  } catch (error) {
    console.error('Error sending message to Slack:', error);
  }
}

async function main() {
  const exchangeRate = await fetchExchangeRate();
  if (exchangeRate) {
    await sendSlackMessage(exchangeRate);
  }
}

main();

This script fetches the latest USD to INR exchange rate from ExchangeRatesAPI and sends it as a Slack message.

Drawbacks

While effective, this method has its challenges:

  • Technical Expertise Required: Setting up and maintaining the script requires knowledge of Node.js
  • Complex Error Handling: Robust error handling is essential to manage potential API failures or network issues, adding complexity to the script.
  • Limited Scalability: The script may need significant modifications for more complex requirements or higher data volumes, affecting scalability.

Method #2: Connect API on Locale and send Slack alert

Locale is a no-code platform which significantly simplifies the process sending Slack alert from any API. With just a few clicks, you can automate the Slack alerts using SQL queries.

Step 1: Login to Locale, go to Org Setting and select API Connector to connect your data source through API.

API Connector for Data Sources - Locale

Step 2: Go to Alerts → Create New Alerts. Choose your database → Click on Setup data to be monitored. Add your API endpoint, write your query and then click on Run Query. Once, it fetches the correct data, click on Done.

API Database Connection setup on Locale platform

Step 4: Now Setup your schedule based on your requirement, this would automatically run the query based on the frequency you set. Click on Run the query at frequency and choose your schedule

Scheduling alert runs in Locale by setting alert frequency

Step 5: With Locale, you can also customize the Slack message to get a better idea. To configure the Slack message, click on Configure Incidents and enter your message in the Incident Title.

Configure incidents on Locale to provide better context to the users receiving alerts

Step 6: Final Step, set up whom or on which channel the Slack alert should be sent. Go to the Setup Notification section and click on Add Notification then select Send Slack Message. Select whether you want the Slack message to be sent to a channel or a user. You can also preview and send test notifications.

Configuring Slack alerts to define whom to send alerts on Locale
You can also dynamically send Slack messages to the users based on query results. To set up this, Select Send message to Slack User → Select Dynamic, then choose the field.

Save the alert. It will automatically run itself on the pre-set schedule and trigger a Slack notification.

Conclusion

Automating Slack messages with no-code platform like Locale offers valuable solutions for streamlining communication within teams. It’s no-code platform simplifies the entire process, allowing users to effortlessly connect APIs, automate Slack alerts, and customize notifications with just a few clicks. It provides users a hassle-free environment empowering users to automate Slack messages effortlessly, streamlining communication without the need for extensive development efforts. It also allows sending Slack messages dynamically to different users, help delivering important details only to those it’s neccessary and decluttering the noise.

Excited to get started? It takes less than 10 minutes to get all things set up: Try for free

Receive Latest InsideOps Updates

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.