将以下代码复制到 Cloud Run 函数中,以使用 Slack 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")
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-08-18。"],[[["\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)"]]