publish-subscribegoogle-cloud-pubsubgoogle-admin-sdkgoogle-alertsgoogle-alert-center-api

How to configure Google Workspace Alert Center to publish alerts to a PubSub topic?


I'm building a notification system that will notify employees on slack when they take an action that triggers a DLP Rule.

The ideal flow I'm trying to get at is:

Employee takes action > Rule triggered > Alert is published to PubSub topic > Triggers Cloud function that renders the slack message and sends it to the user.

The point where I'm stuck is having the API alert center to publish the alert the to the PubSub topic. I have done something like this in the past with the Gmail API, to publish to the topic when an particular account received an email. And there was a watch request to configure the account to publish to the topic.

I looked through the Alert Center API documentation and haven´t found a watch request or anything that does something similar.

Is there a way to achieve this? Or is this just impossible?

I searched through the Google Alert Center API reference and the Alert Center console for any options to configure publishing to a pubsub topic or a webhook.


Solution

  • After a couple of hours of trial and error I found the solution to this.

    We have to update the settings by making and updateSetting, and send a settings object in the body.

    Here's some python code to do that using a service account with domain wide delegation:

    from google.oauth2 import service_account
    from googleapiclient.discovery import build
    import json
    
    def main():
    
        # Authenticate the service account
        scopes = ['https://www.googleapis.com/auth/apps.alerts']
        admin_to_impersonate = '******'
        credentials = service_account.Credentials.from_service_account_file(
            'client_secrets.json', scopes=scopes, subject=admin_to_impersonate
            )
        
        # Build the service
        service = build('alertcenter', 'v1beta1', credentials=credentials)
    
        settings = {
            'notifications': [
                {
                    'cloudPubsubTopic': {
                        'topicName': '<YOUR TOPIC NAME>',
                        'payloadFormat': 'JSON'
                    }
                }
            ]
        }
    
        # Execute a updateSetting request
        response = service.v1beta1().updateSettings(body=settings).execute()
        print(response)
    
    if __name__ == '__main__':
        main()