搜索
首页后端开发Python教程使用 Cloud Run Functions 和 Cloud Scheduler 通过图形自动发送 Slack 通知

我最近构建了一个系统来自动执行 Slack 通知,并通过图表可视化过去 7 天的会话计数。这是通过结合用于数据处理和图形生成的 Cloud Run 函数以及用于调度执行的 Cloud Scheduler 来实现的。

实施概述

云运行功能

Cloud Run 函数查询 BigQuery 以获取会话数据,使用 Matplotlib 创建折线图,然后通过 Slack API 将图表发送到 Slack。以下步骤概述了设置过程。

这是 main.py 的代码。运行之前,您需要将 SLACK_API_TOKEN 和 SLACK_CHANNEL_ID 设置为环境变量。您暂时可以将它们留空,因为我们稍后会设置它们。

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"
</dataset></project>

依赖关系

创建一个requirements.txt 文件并包含以下依赖项:

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

授予对 Cloud Run 功能的访问权限

要允许Cloud Scheduler或其他服务调用您的Cloud Run功能,您需要将roles/run.invoker角色分配给适当的实体。使用以下命令来执行此操作:

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

将 MEMBER_NAME 替换为以下内容之一:

  • Cloud Scheduler 的服务帐户: serviceAccount:scheduler-account@example.iam.gserviceaccount.com
  • 对于公众访问(不推荐): 所有用户

设置云调度程序

使用 Cloud Scheduler 在每周一上午 10:00 (JST) 自动执行该函数。这是一个示例配置:

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

Slack API 配置

要使您的 Cloud Run 功能能够发送 Slack 通知,请按照以下步骤操作:

  1. 转到 Slack API 并创建一个新应用程序。
  2. OAuth 和权限 下分配以下机器人令牌范围:
    • 频道:阅读
    • 聊天:写
    • 文件:写入

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

  1. 将应用程序安装到您的 Slack 工作区并复制 机器人用户 OAuth 令牌

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

  1. 将应用添加到您要发布通知的 Slack 频道。

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

  1. 复制通道 ID 并将其与 Bot 令牌一起粘贴到 Cloud Run 函数的 SLACK_CHANNEL_ID 和 SLACK_API_TOKEN 环境变量中。

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

最终结果

一切设置完毕后,您的 Slack 频道将收到每周通知,其中包含如下图表:

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

以上是使用 Cloud Run Functions 和 Cloud Scheduler 通过图形自动发送 Slack 通知的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何将元素附加到Python列表中?您如何将元素附加到Python列表中?May 04, 2025 am 12:17 AM

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

您如何创建Python列表?举一个例子。您如何创建Python列表?举一个例子。May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

讨论有效存储和数值数据的处理至关重要的实际用例。讨论有效存储和数值数据的处理至关重要的实际用例。May 04, 2025 am 12:11 AM

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。 1)在金融中,使用内存映射文件和NumPy库可显着提升数据处理速度。 2)科研领域,HDF5文件优化数据存储和检索。 3)医疗中,数据库优化技术如索引和分区提高数据查询性能。 4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显着提升系统性能和可扩展性。

您如何创建Python数组?举一个例子。您如何创建Python数组?举一个例子。May 04, 2025 am 12:10 AM

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

使用Shebang系列指定Python解释器有哪些替代方法?使用Shebang系列指定Python解释器有哪些替代方法?May 04, 2025 am 12:07 AM

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具