Google Hangouts Chat bot to send DMs via incoming webhook?

℡╲_俬逩灬. 提交于 2019-12-22 12:37:52

问题


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



来源:https://stackoverflow.com/questions/50714972/google-hangouts-chat-bot-to-send-dms-via-incoming-webhook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!