Slack に通知を送信する

このドキュメントでは、予算通知を Slack に送信する方法について説明します。

通常、予算はメール通知を送信するように構成されています。ただし、特に予算が重要で時間的制約がある場合、必ずしもメールがクラウド費用の状況を把握する最適な方法とは限りません。プログラムによる通知を使用すると、予算メッセージを Slack などの他のメディアに転送できます。

始める前に

開始前に、次のタスクを完了する必要があります。

  1. Cloud Billing API を有効にする
  2. 予算の作成
  3. プログラムによる予算通知を設定する

Slack チャネルと権限を設定する

最初に、Slack ワークスペースと、Slack API を呼び出すためのボットユーザー トークンを作成します。API トークンは、https://api.slack.com/apps で管理できます。詳細については、Slack サイトの Bot Users をご覧ください。

Slack 通知を構成します。

Cloud Run 関数を設定する

  1. Cloud Run 関数を作成するの手順を完了します。[トリガーの種類] が、予算で使用する Pub/Sub トピックと同じに設定されていることを確認します。

  2. 次の依存関係を追加します。

    Node.js

    以下のコードを package.json にコピーします。

    {
      "name": "cloud-functions-billing",
      "private": "true",
      "version": "0.0.1",
      "description": "Examples of integrating Cloud Functions with billing",
      "main": "index.js",
      "engines": {
        "node": ">=16.0.0"
      },
      "scripts": {
        "compute-test": "c8 mocha -p -j 2 test/periodic.test.js --timeout=600000",
        "test": "c8 mocha -p -j 2 test/index.test.js --timeout=5000 --exit"
      },
      "author": "Ace Nassri <anassri@google.com>",
      "license": "Apache-2.0",
      "dependencies": {
        "@google-cloud/billing": "^4.0.0",
        "@google-cloud/compute": "^4.0.0",
        "google-auth-library": "^9.0.0",
        "googleapis": "^143.0.0",
        "slack": "^11.0.1"
      },
      "devDependencies": {
        "@google-cloud/functions-framework": "^3.0.0",
        "c8": "^10.0.0",
        "gaxios": "^6.0.0",
        "mocha": "^10.0.0",
        "promise-retry": "^2.0.0",
        "proxyquire": "^2.1.0",
        "sinon": "^18.0.0",
        "wait-port": "^1.0.4"
      }
    }
    

    Python

    以下のコードを requirements.txt にコピーします。

    slackclient==2.9.4
    google-api-python-client==2.131.0
    

  3. 次のコードを Cloud Run 関数にコピーして、Slack API を使用して Slack チャット チャネルに予算通知を投稿します。

    Node.js

    const slack = require('slack');
    
    // TODO(developer) replace these with your own values
    const BOT_ACCESS_TOKEN =
      process.env.BOT_ACCESS_TOKEN || 'xxxx-111111111111-abcdefghidklmnopq';
    const CHANNEL = process.env.SLACK_CHANNEL || 'general';
    
    exports.notifySlack = async pubsubEvent => {
      const pubsubAttrs = pubsubEvent.attributes;
      const pubsubData = Buffer.from(pubsubEvent.data, 'base64').toString();
      const budgetNotificationText = `${JSON.stringify(
        pubsubAttrs
      )}, ${pubsubData}`;
    
      await slack.chat.postMessage({
        token: BOT_ACCESS_TOKEN,
        channel: CHANNEL,
        text: budgetNotificationText,
      });
    
      return 'Slack notification sent successfully';
    };

    Python

    import base64
    import json
    import os
    
    import slack
    from slack.errors import SlackApiError
    
    # See https://api.slack.com/docs/token-types#bot for more info
    BOT_ACCESS_TOKEN = "xxxx-111111111111-abcdefghidklmnopq"
    CHANNEL = "C0XXXXXX"
    
    slack_client = slack.WebClient(token=BOT_ACCESS_TOKEN)
    
    
    def notify_slack(data, context):
        pubsub_message = data
    
        # For more information, see
        # https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_format
        try:
            notification_attr = json.dumps(pubsub_message["attributes"])
        except KeyError:
            notification_attr = "No attributes passed in"
    
        try:
            notification_data = base64.b64decode(data["data"]).decode("utf-8")
        except KeyError:
            notification_data = "No data passed in"
    
        # This is just a quick dump of the budget data (or an empty string)
        # You can modify and format the message to meet your needs
        budget_notification_text = f"{notification_attr}, {notification_data}"
    
        try:
            slack_client.api_call(
                "chat.postMessage",
                json={"channel": CHANNEL, "text": budget_notification_text},
            )
        except SlackApiError:
            print("Error posting to Slack")
    
    

  4. 次の Slack API postMessage のパラメータが正しく設定されていることを確認します。

    • ボットユーザー OAuth アクセス トークン
    • チャネルの名前

関数をテストする

関数が想定どおりに動作することを確認するには、Cloud Run 関数をテストするの手順に沿って操作します。

成功すると、Slack にメッセージが表示されます。

次のステップ

他のプログラムによる通知の例を確認して、以下を行う方法を学びます。