Google Hangouts Chat bot to send DMs via incoming

2019-05-20 22:11发布

问题:

Is it possible to set up this simple bot, using an incoming webhook, but send the message as a DM (not a @mention) to specific user(s)?
My guess is no. But then how could I achieve this?

Right now, the message is just sent into the room in which the bot was added and I can't see anything on DMs in the messaging docs.

You can currently achieve this very easily in Slack by setting up a so called bot user and using their chat.postMessage but I would like to do this in Google Hangouts Chat instead.

from httplib2 import Http
from json import dumps

#
# Hangouts Chat incoming webhook quickstart
#
def main():
    url = '<INCOMING-WEBHOOK-URL>'
    bot_message = {
        'text' : 'Hello from Python script!'}

    message_headers = { 'Content-Type': 'application/json; charset=UTF-8'}

    http_obj = Http()

    response = http_obj.request(
        uri=url,
        method='POST',
        headers=message_headers,
        body=dumps(bot_message),
    )

    print(response)

if __name__ == '__main__':
    main()

回答1:

As of now you would need their Space ID or webhook url in order to DM the user privately whether you use a webhook (like you did) or REST API. Unless you have this Space ID/Webhook you cannot message a user. One way of getting it, is to ask the user for their spaceID and store it. Either way, Google API hasn't given a way to retrieve a different Space ID then the current one you are talking inside of. This means, a bot can only message users its interacted with at some point.

The current Space ID value can be retrieved from the event JSON (event['space']['name']) and then using messages.create to send a new message to the user

service.spaces().messages().create( parent = spaceName, body = response).execute()

OR it can be retrieved from the url https://chat.google.com/dm/ --> space ID is here <---

Google has not released any way of generating your own spaceID for a specific user.

EDIT: In order to get the webhook url. See below:

then copy and paste the webhook url into your code above.

NOTICE: If you need, this webhook url can be manufactured using the usual url for google chat with their space ID as mentioned above and a key and access token in this format: https://chat.googleapis.com/v1/spaces/< space ID >/messages?key=A< key goes here > &token=< access token here > For info on how to get a key and access token, read the documentation provided here: https://developers.google.com/identity/protocols/OAuth2