使用webhook向Google Hangouts Chat bot发送简单信息

时间:2018-05-28 15:18:14

标签: python hangouts-chat

我已在Google Hangouts Chat的聊天室中设置了一个webhook。

我可以成功运行他们的example code,它会从与聊天中的webhook相关联的机器人生成一条消息:

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()

但是,我希望使用标准库包发送此消息,例如urllib

但是当我使用urllib并运行以下代码时,我会得到urllib.error.HTTPError: HTTP Error 400: Bad Request。为什么我会收到此错误?

import json
import urllib.parse
import urllib.request


def main():
    # python 3.6

    url = '<INCOMING-WEBHOOK-URL>'
    bot_message = {'text': 'Hello from Python script!'}
    message_headers = {'Content-Type': 'application/json; charset=UTF-8'}

    url_encoded = urllib.parse.urlencode(bot_message)
    byte_encoded = url_encoded.encode('utf-8')
    req = urllib.request.Request(url=url, data=byte_encoded, headers=message_headers)
    response = urllib.request.urlopen(req)
    print(response.read())


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

区别在于身体格式。在第一个版本中,您将转储到json中,而在第二个版本中,您将对其进行urlencode。

替换

url_encoded = urllib.parse.urlencode(bot_message)
byte_encoded = url_encoded.encode('utf-8')

byte_encoded = json.dumps(bot_message).encode('utf-8')