|
15 | 15 | # [START functions_billing_limit]
|
16 | 16 | # [START functions_billing_limit_appengine]
|
17 | 17 | # [START functions_billing_stop]
|
| 18 | +# [START functions_billing_slack] |
18 | 19 | import base64
|
19 | 20 | import json
|
20 | 21 | import os
|
21 | 22 | # [END functions_billing_stop]
|
22 | 23 | # [END functions_billing_limit]
|
23 | 24 | # [END functions_billing_limit_appengine]
|
| 25 | +# [END functions_billing_slack] |
24 | 26 |
|
25 | 27 | # [START functions_billing_limit]
|
26 | 28 | # [START functions_billing_limit_appengine]
|
|
32 | 34 |
|
33 | 35 | # [START functions_billing_slack]
|
34 | 36 | import slack
|
| 37 | +from slack.errors import SlackApiError |
35 | 38 | # [END functions_billing_slack]
|
36 | 39 |
|
37 | 40 | # [START functions_billing_limit]
|
|
42 | 45 | # [END functions_billing_limit]
|
43 | 46 |
|
44 | 47 | # [START functions_billing_slack]
|
45 |
| - |
46 | 48 | # See https://api.slack.com/docs/token-types#bot for more info
|
47 | 49 | BOT_ACCESS_TOKEN = 'xxxx-111111111111-abcdefghidklmnopq'
|
48 |
| - |
49 |
| -CHANNEL_ID = 'C0XXXXXX' |
| 50 | +CHANNEL = 'C0XXXXXX' |
50 | 51 |
|
51 | 52 | slack_client = slack.WebClient(token=BOT_ACCESS_TOKEN)
|
52 | 53 |
|
53 | 54 |
|
54 | 55 | def notify_slack(data, context):
|
55 | 56 | pubsub_message = data
|
56 | 57 |
|
57 |
| - notification_attrs = json.dumps(pubsub_message['attributes']) |
58 |
| - notification_data = base64.b64decode(data['data']).decode('utf-8') |
59 |
| - budget_notification_text = f'{notification_attrs}, {notification_data}' |
| 58 | + # For more information, see |
| 59 | + # https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_format |
| 60 | + try: |
| 61 | + notification_attr = json.dumps(pubsub_message['attributes']) |
| 62 | + except KeyError: |
| 63 | + notification_attr = "No attributes passed in" |
60 | 64 |
|
61 |
| - slack_client.api_call( |
62 |
| - 'chat.postMessage', |
63 |
| - channel=CHANNEL_ID, |
64 |
| - text=budget_notification_text) |
| 65 | + try: |
| 66 | + notification_data = base64.b64decode(data['data']).decode('utf-8') |
| 67 | + except KeyError: |
| 68 | + notification_data = "No data passed in" |
| 69 | + |
| 70 | + # This is just a quick dump of the budget data (or an empty string) |
| 71 | + # You can modify and format the message to meet your needs |
| 72 | + budget_notification_text = f'{notification_attr}, {notification_data}' |
| 73 | + |
| 74 | + try: |
| 75 | + slack_client.api_call( |
| 76 | + 'chat.postMessage', |
| 77 | + json={ |
| 78 | + 'channel': CHANNEL, |
| 79 | + 'text' : budget_notification_text |
| 80 | + } |
| 81 | + ) |
| 82 | + except SlackApiError: |
| 83 | + print('Error posting to Slack') |
65 | 84 | # [END functions_billing_slack]
|
66 | 85 |
|
67 | 86 |
|
|
0 commit comments