将以下代码复制到您的 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-05-05。"],[[["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."]]],[]]