2

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

我可以成功运行他们的示例代码,它会从聊天中与 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()
4

1 回答 1

3

区别在于正文格式。在第一个版本中,您转储到 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')
于 2018-05-30T18:24:46.430 回答