Home Backend Development Python Tutorial Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

Dec 11, 2024 am 04:47 AM

I recently built a system to automate Slack notifications with graphs that visualize the session counts for the last 7 days. This was achieved using a combination of Cloud Run functions for data processing and graph generation, and Cloud Scheduler for scheduling the execution.

Implementation Overview

Cloud Run Function

The Cloud Run function queries BigQuery to fetch session data, uses Matplotlib to create a line chart, and then sends the chart to Slack via the Slack API. The following steps outline the setup process.

Here is the code for main.py. Before running, you need to set the SLACK_API_TOKEN and SLACK_CHANNEL_ID as environment variables. You can leave them empty for now, as we will set them up later.

import os
import matplotlib.pyplot as plt
from google.cloud import bigquery
from datetime import datetime, timedelta
import io
import pytz
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

def create_weekly_total_sessions_chart(_):
    SLACK_TOKEN = os.environ.get('SLACK_API_TOKEN')
    SLACK_CHANNEL_ID = os.environ.get('SLACK_CHANNEL_ID')

    client = bigquery.Client()

    # Calculate the date range for the last 7 days
    jst = pytz.timezone('Asia/Tokyo')
    today = datetime.now(jst)
    start_date = (today - timedelta(days=7)).strftime('%Y-%m-%d')
    end_date = (today - timedelta(days=1)).strftime('%Y-%m-%d')

    query = f"""
        SELECT 
            DATE(created_at) AS date,
            COUNT(DISTINCT session_id) AS unique_sessions
        FROM `<project>.<dataset>.summary_all`
        WHERE created_at BETWEEN '{start_date} 00:00:00' AND '{end_date} 23:59:59'
        GROUP BY date
        ORDER BY date;
    """

    query_job = client.query(query)
    results = query_job.result()

    # Prepare data for the graph
    dates = []
    session_counts = []
    for row in results:
        dates.append(row['date'].strftime('%Y-%m-%d'))
        session_counts.append(row['unique_sessions'])

    # Generate the graph
    plt.figure()
    plt.plot(dates, session_counts, marker='o')
    plt.title('Unique Session Counts (Last 7 Days)')
    plt.xlabel('Date')
    plt.ylabel('Unique Sessions')
    plt.xticks(rotation=45)
    plt.tight_layout()

    # Save the graph as an image
    image_binary = io.BytesIO()
    plt.savefig(image_binary, format='png')
    image_binary.seek(0)

    # Send the graph to Slack
    client = WebClient(token=SLACK_TOKEN)
    try:
        response = client.files_upload_v2(
            channel=SLACK_CHANNEL_ID,
            file_uploads=[{
                "file": image_binary,
                "filename": "unique_sessions.png",
                "title": "Unique Session Counts (Last 7 Days)"
            }],
            initial_comment="Here are the session counts for the last 7 days!"
        )
    except SlackApiError as e:
        return f"Error uploading file: {e.response['error']}"

    return "Success"
Copy after login

Dependencies

Create a requirements.txt file and include the following dependencies:

functions-framework==3.*
google-cloud-bigquery
matplotlib
slack_sdk
pytz
Copy after login

Granting Access to the Cloud Run Function

To allow Cloud Scheduler or other services to invoke your Cloud Run function, you need to assign the roles/run.invoker role to the appropriate entity. Use the following command to do this:

gcloud functions add-invoker-policy-binding create-weekly-total-sessions-chart \
      --region="asia-northeast1" \
      --member="MEMBER_NAME"
Copy after login

Replace MEMBER_NAME with one of the following:

  • A service account for Cloud Scheduler: serviceAccount:scheduler-account@example.iam.gserviceaccount.com
  • For public access (not recommended): allUsers

Setting Up Cloud Scheduler

Use Cloud Scheduler to automate the function’s execution every Monday at 10:00 AM (JST). Here’s an example configuration:

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

Slack API Configuration

To enable your Cloud Run function to send Slack notifications, follow these steps:

  1. Go to Slack API and create a new app.
  2. Assign the following Bot Token Scopes under OAuth & Permissions:
    • channels:read
    • chat:write
    • files:write

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

  1. Install the app to your Slack workspace and copy the Bot User OAuth Token.

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

  1. Add the app to the Slack channel where you want to post notifications.

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

  1. Copy the channel ID and paste it, along with the Bot Token, into the SLACK_CHANNEL_ID and SLACK_API_TOKEN environment variables for your Cloud Run function.

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

Final Result

Once everything is set up, your Slack channel will receive a weekly notification with a graph like this:

Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler

The above is the detailed content of Automate Slack Notifications with Graphs Using Cloud Run Functions and Cloud Scheduler. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

See all articles