top of page
Writer's pictureIGEL Community

Automating Slack User Count to Display on AWTRIX Clock via MQTT

Written by Sebastien Perusat


Hello, fellow tech and Slack enthusiasts!

I've been working on a fun and geeky project that combines the power of Slack, shell scripting, and the awesomeness of the AWTRIX clock. I wanted a way to keep track of the active users in our Slack workspace and display this count live on my AWTRIX clock using MQTT. Why? Because every member of the IGEL Community is so important that I want to see every new one right on my clock! This is a Awtrix Blueforcer firmware on Ulanzi TC001.


Here’s a step-by-step breakdown of how I did it:



The Script: Counting Active Slack Users and writing it to a CCU

First, let’s take a look at the script that makes this magic happen:


#!/bin/sh
# Slack API Script with Comprehensive Features
# This script handles counting active Slack users and sending the data to a third party system, Homematic IP CCU in my case.
# Variables
SLACK_TOKEN="xoxb-xxxxxxxxxxx-xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxx" # Your Slack API token
LOG_FILE="/var/log/slack-api.log"
CCU_USER="api_user" # Your CCU user
CCU_PASSWORD="your_password" # Your CCU password
CCU_ENDPOINT="http://your_ccu_endpoint" # Your CCU endpoint
SLACKUSERCOUNT_VARIABLE="yourCCUvariable "

# Log file with date
LOG_DATE=$(date +%Y-%m-%d)
LOG_FILE="/var/log/slack-api-$LOG_DATE.log"

# Function to log messages
log_message() {
    echo "$(date): $1" >> "$LOG_FILE"
}

# Function to count active Slack users and update CCU
count_and_update_slack_users() {
    local cursor=""
    local total_active_users=0
    while :
    do
        response=$(curl -s -H "Authorization: Bearer $SLACK_TOKEN"
"https://slack.com/api/users.list?limit=1000&cursor=$cursor")
        [ $? -ne 0 ] && return 1
        active_user_count=$(echo $response | jq '[.members[] | select(.deleted == false)] | length')
        total_active_users=$((total_active_users + active_user_count))
        cursor=$(echo $response | jq -r '.response_metadata.next_cursor')
        if [ -z "$cursor" ]; then
            break
        fi
    done

    log_message "Total active Slack users: $total_active_users"
    echo "$total_active_users"

    local url="$CCU_ENDPOINT?Antwort=dom.GetObject(\"$SLACKUSERCOUNT_VARIABLE\").State(\"$total_active_users\")"
    response=$(curl -k --user "$CCU_USER:$CCU_PASSWORD" "$url")
    if [ -z "$response" ]; then
        log_message "Error updating CCU with Slack user count"
        return 1
    fi
    log_message "Updated CCU with Slack user count: $total_active_users"
    # Publish to MQTT for AWTRIX
    local mqtt_broker="your_mqtt_broker_address" # Replace with your MQTT broker address
    local mqtt_topic="awtrix/customapp"
    local mqtt_message="{\"icon\":10977,\"text\":\"Active Users: $total_active_users\"}"
    mosquitto_pub -h "$mqtt_broker" -t "$mqtt_topic" -m "$mqtt_message"
    log_message "Published to MQTT: $mqtt_message"
}

# Main execution
main() {
    log_message "Starting API script."
    update_last_run_date
    log_message "End of run - Counter values: Daily Requests: 
DAILY_REQUESTS
   # Process script arguments for further actions
    case "$1" in
        count_active_slack_users)
            count_and_update_slack_users
            ;;
        *)
            echo "Unknown command: $1"
            return 1
            ;;
    esac

    log_message "API script execution completed."
}

# Start the script with provided arguments
main "$@"

Breaking Down the Script

Logging Function

First, we have a simple logging function to keep track of all the actions performed by the script:


log_message() {
    echo "$(date): $1" >> "$LOG_FILE"
}

Counting Active Slack Users

This function connects to the Slack API, counts the number of active (non-deleted) users, and updates our control unit (CCU) with the user count. As the result of the Slack API covers multiple answers and is built in Blocks of 1000 users, we needed to build a cursor and add them mathematically.


count_and_update_slack_users() {
    local cursor=""
    local total_active_users=0
    while :
    do
        response=$(curl -s -H "Authorization: Bearer $SLACK_TOKEN"
"https://slack.com/api/users.list?limit=1000&cursor=$cursor")
        [ $? -ne 0 ] && return 1
        active_user_count=$(echo $response | jq '[.members[] | select(.deleted == false)] | length')
        total_active_users=$((total_active_users + active_user_count))
        cursor=$(echo $response | jq -r '.response_metadata.next_cursor')
        if [ -z "$cursor" ]; then
            break
        fi
    done

    log_message "Total active Slack users: $total_active_users"
    echo "$total_active_users"

    # Publish to MQTT for AWTRIX
    local mqtt_broker="your_mqtt_broker_address" # Replace with your MQTT broker address
    local mqtt_topic="awtrix/customapp"
    local mqtt_message="{\"icon\":10977,\"text\":\"Active Users: $total_active_users\"}"
    mosquitto_pub -h "$mqtt_broker" -t "$mqtt_topic" -m "$mqtt_message"
    log_message "Published to MQTT: $mqtt_message"
}

Why This is Awesome


  1. Seamless API Integration: The script uses the Slack API to fetch real-time data on active users.

  2. Automation: This eliminates manual counting and updating processes, saving time and reducing errors.

  3. Visual Delight: The best part? Watching the user count update live on my AWTRIX clock! Because every IGEL Community member is so important, I want to see every new one on my clock.


How to Get Started

  1. Get Your Slack API Token: You'll need an API token from your Slack workspace.

  2. Set Up Your Environment: Ensure you have curl, mosquitto_pub and jq installed on your system.

  3. Customize the Script: Replace the placeholders with your actual values.

  4. Run the Script: Execute the script to start counting active users and updating your CCU and AWTRIX clock!



Final Thoughts


This project was a fantastic way to blend work with a bit of fun tech play. If you're into automation, APIs, or just cool tech hacks, let's connect and chat about the endless possibilities!


Stay geeky, my friends!



Disclaimer


The content of this post is provided without any warranty or support by IGEL Technology. This information is derived from the IGEL Community, and not IGEL Technology. IGEL Technology will not provide any packages, instructions, or support for processes, scripts, or other content contained in this post. Use at your own risk!


Hope it works well, please let me know if you have some questions or comments!


Comments


bottom of page