將下列程式碼複製到 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"]],["上次更新時間:2025-07-09 (世界標準時間)。"],[[["This guide outlines how to configure budget notifications to be sent to a Slack channel instead of just email."],["Before setting up Slack notifications, you must enable the Cloud Billing API, create a budget, and set up programmatic budget notifications."],["Setting up Slack requires creating a workspace and managing bot user tokens through the Slack API interface."],["A 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."],["After 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."]]],[]]