I've set up a webhook in a chat room in my Google Hangouts Chat.
I can successfully run their example code, which generates a message from the bot associated with the webhook in the chat:
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()
However, I wish to send this message using standard library packages, such as urllib.
But when I use urllib
and run the below code, I get an urllib.error.HTTPError: HTTP Error 400: Bad Request
. Why am I getting this error?
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()
The difference is in the body format. In the first version, you dump into json, while in the second you urlencode it.
replace
url_encoded = urllib.parse.urlencode(bot_message)
byte_encoded = url_encoded.encode('utf-8')
with
byte_encoded = json.dumps(bot_message).encode('utf-8')