Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Ce document explique comment envoyer des notifications de budget à Slack.
Les budgets sont généralement configurés pour envoyer des notifications par e-mail. Toutefois, l'envoi d'e-mails n'est pas toujours le meilleur moyen de rester informé de vos coûts cloud, surtout si votre budget est critique et sensible au facteur temps. Les notifications automatisées vous permettent de transférer vos messages budgétaires vers d'autres plates-formes, comme Slack.
Avant de commencer
Avant de commencer, vous devez effectuer les tâches suivantes :
La première étape consiste à créer un espace de travail Slack ainsi que les jetons de l'utilisateur bot utilisés pour appeler l'API Slack. Les jetons d'API peuvent être gérés à l'adresse https://api.slack.com/apps. Pour obtenir des instructions détaillées, consultez la page concernant les utilisateurs bot sur le site de Slack.
Configurer une fonction Cloud Run
Suivez les étapes décrites dans Créer une fonction Cloud Run.
Assurez-vous que le type de déclencheur est défini sur le même sujet Pub/Sub que celui que votre budget utilisera.
Copiez le code suivant dans votre fonction Cloud Run pour publier des notifications de budget sur un canal de discussion Slack à l'aide de l'API Slack :
Node.js
constslack=require('slack');// TODO(developer) replace these with your own valuesconstBOT_ACCESS_TOKEN=process.env.BOT_ACCESS_TOKEN||'xxxx-111111111111-abcdefghidklmnopq';constCHANNEL=process.env.SLACK_CHANNEL||'general';exports.notifySlack=asyncpubsubEvent=>{constpubsubAttrs=pubsubEvent.attributes;constpubsubData=Buffer.from(pubsubEvent.data,'base64').toString();constbudgetNotificationText=`${JSON.stringify(pubsubAttrs)}, ${pubsubData}`;awaitslack.chat.postMessage({token:BOT_ACCESS_TOKEN,channel:CHANNEL,text:budgetNotificationText,});return'Slack notification sent successfully';};
Python
importbase64importjsonimportosimportslackfromslack.errorsimportSlackApiError# See https://api.slack.com/docs/token-types#bot for more infoBOT_ACCESS_TOKEN="xxxx-111111111111-abcdefghidklmnopq"CHANNEL="C0XXXXXX"slack_client=slack.WebClient(token=BOT_ACCESS_TOKEN)defnotify_slack(data,context):pubsub_message=data# For more information, see# https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_formattry:notification_attr=json.dumps(pubsub_message["attributes"])exceptKeyError:notification_attr="No attributes passed in"try:notification_data=base64.b64decode(data["data"]).decode("utf-8")exceptKeyError: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 needsbudget_notification_text=f"{notification_attr}, {notification_data}"try:slack_client.api_call("chat.postMessage",json={"channel":CHANNEL,"text":budget_notification_text},)exceptSlackApiError:print("Error posting to Slack")
Assurez-vous que les paramètres postMessage de l'API Slack suivants sont correctement définis :
Jeton d'accès OAuth de l'utilisateur bot
Nom du canal
Tester votre fonction
Pour vous assurer que votre fonction fonctionne comme prévu, suivez les étapes décrites dans Tester une fonction Cloud Run.
Si l'opération réussit, un message s'affiche dans Slack.
Étapes suivantes
Consultez d'autres exemples de notifications programmatiques pour découvrir comment effectuer les opérations suivantes :
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[[["\u003cp\u003eThis guide outlines how to configure budget notifications to be sent to a Slack channel instead of just email.\u003c/p\u003e\n"],["\u003cp\u003eBefore setting up Slack notifications, you must enable the Cloud Billing API, create a budget, and set up programmatic budget notifications.\u003c/p\u003e\n"],["\u003cp\u003eSetting up Slack requires creating a workspace and managing bot user tokens through the Slack API interface.\u003c/p\u003e\n"],["\u003cp\u003eA Cloud Run function is created to receive Pub/Sub messages and then use the Slack API to post notifications to a designated Slack channel, with example code provided in Node.js and Python.\u003c/p\u003e\n"],["\u003cp\u003eAfter configuring, you can test the function to ensure messages are successfully delivered to Slack, with further options provided to control resource usage and billing through notifications.\u003c/p\u003e\n"]]],[],null,["# Send notifications to Slack\n\n\u003cbr /\u003e\n\nThis document explains how to send budget notifications to Slack.\n\n[Budgets](/billing/docs/how-to/budgets#manage-notifications)\nare typically configured to send email notifications. However, email isn't\nalways the best way to stay up to date on your cloud costs, particularly if\nyour budget is critical and time sensitive. With programmatic notifications,\nyou can forward your budget messages to other mediums, such as\n[Slack](https://slack.com/).\n\nBefore you begin\n----------------\n\nBefore you begin, you must complete the following tasks:\n\n1. [Enable the Cloud Billing API](https://console.cloud.google.com/apis/api/cloudbilling.googleapis.com)\n2. [Create a budget](/billing/docs/how-to/budgets)\n3. [Set up programmatic budget notifications](/billing/docs/how-to/budgets-programmatic-notifications)\n\nSet up a Slack channel and permissions\n--------------------------------------\n\nThe first step is to create your Slack workspace and the bot user tokens\nthat are used to call the Slack API. API tokens can be managed at\n\u003chttps://api.slack.com/apps\u003e.\nFor detailed instructions, see\n[Bot Users](https://api.slack.com/bot-users)\non the Slack site.\n\nSet up a Cloud Run function\n---------------------------\n\n1. Complete the steps in\n [Create a Cloud Run function](/billing/docs/how-to/listen-to-notifications#create-function).\n Ensure that the **Trigger type** is set to the same Pub/Sub\n topic that your budget will use.\n\n2. Add the following dependencies:\n\n\n ### Node.js\n\n \u003cbr /\u003e\n\n Copy the following to your `package.json`:\n\n\n {\n \"name\": \"cloud-functions-billing\",\n \"private\": \"true\",\n \"version\": \"0.0.1\",\n \"description\": \"Examples of integrating Cloud Functions with billing\",\n \"main\": \"index.js\",\n \"engines\": {\n \"node\": \"\u003e=16.0.0\"\n },\n \"scripts\": {\n \"compute-test\": \"c8 mocha -p -j 2 test/periodic.test.js --timeout=600000\",\n \"test\": \"c8 mocha -p -j 2 test/index.test.js --timeout=5000 --exit\"\n },\n \"author\": \"Ace Nassri \u003canassri@google.com\u003e\",\n \"license\": \"Apache-2.0\",\n \"dependencies\": {\n \"@google-cloud/billing\": \"^4.0.0\",\n \"@google-cloud/compute\": \"^4.0.0\",\n \"google-auth-library\": \"^9.0.0\",\n \"googleapis\": \"^143.0.0\",\n \"slack\": \"^11.0.1\"\n },\n \"devDependencies\": {\n \"@google-cloud/functions-framework\": \"^3.0.0\",\n \"c8\": \"^10.0.0\",\n \"gaxios\": \"^6.0.0\",\n \"mocha\": \"^10.0.0\",\n \"promise-retry\": \"^2.0.0\",\n \"proxyquire\": \"^2.1.0\",\n \"sinon\": \"^18.0.0\",\n \"wait-port\": \"^1.0.4\"\n }\n }\n\n ### Python\n\n \u003cbr /\u003e\n\n Copy the following to your `requirements.txt`:\n\n\n slackclient==2.9.4\n google-api-python-client==2.131.0\n\n \u003cbr /\u003e\n\n3. Copy the following code into your Cloud Run function to post\n budget notifications to a Slack chat channel using the Slack API:\n\n\n ### Node.js\n\n const slack = require('slack');\n\n // TODO(developer) replace these with your own values\n const BOT_ACCESS_TOKEN =\n process.env.BOT_ACCESS_TOKEN || 'xxxx-111111111111-abcdefghidklmnopq';\n const CHANNEL = process.env.SLACK_CHANNEL || 'general';\n\n exports.notifySlack = async pubsubEvent =\u003e {\n const pubsubAttrs = pubsubEvent.attributes;\n const pubsubData = Buffer.from(pubsubEvent.data, 'base64').toString();\n const budgetNotificationText = `${JSON.stringify(\n pubsubAttrs\n )}, ${pubsubData}`;\n\n await slack.chat.postMessage({\n token: BOT_ACCESS_TOKEN,\n channel: CHANNEL,\n text: budgetNotificationText,\n });\n\n return 'Slack notification sent successfully';\n };\n\n ### Python\n\n import base64\n import json\n import os\n import slack\n from slack.errors import SlackApiError\n # See https://api.slack.com/docs/token-types#bot for more info\n BOT_ACCESS_TOKEN = \"xxxx-111111111111-abcdefghidklmnopq\"\n CHANNEL = \"C0XXXXXX\"\n\n slack_client = slack.WebClient(token=BOT_ACCESS_TOKEN)\n\n\n def notify_slack(data, context):\n pubsub_message = data\n\n # For more information, see\n # https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_format\n try:\n notification_attr = json.dumps(pubsub_message[\"attributes\"])\n except KeyError:\n notification_attr = \"No attributes passed in\"\n\n try:\n notification_data = base64.b64decode(data[\"data\"]).decode(\"utf-8\")\n except KeyError:\n notification_data = \"No data passed in\"\n\n # This is just a quick dump of the budget data (or an empty string)\n # You can modify and format the message to meet your needs\n budget_notification_text = f\"{notification_attr}, {notification_data}\"\n\n try:\n slack_client.api_call(\n \"chat.postMessage\",\n json={\"channel\": CHANNEL, \"text\": budget_notification_text},\n )\n except SlackApiError:\n print(\"Error posting to Slack\")\n\n \u003cbr /\u003e\n\n4. Ensure the following Slack API postMessage parameters are set correctly:\n\n - Bot User OAuth access token\n - Channel name\n\nTest your function\n------------------\n\nTo ensure your function works as expected, follow the steps in\n[Test a Cloud Run function](/billing/docs/how-to/listen-to-notifications#test-function).\n\nIf successful, a message will show up in Slack.\n\nWhat's next\n-----------\n\nReview other programmatic notification examples to learn how to do the\nfollowing:\n\n- [Listen to your notifications](/billing/docs/how-to/listen-to-notifications)\n- [Control resource usage with notifications](/billing/docs/how-to/control-usage)\n- [Disable billing usage with notifications](/billing/docs/how-to/disable-billing-with-notifications)"]]