Send simple message to Google Hangouts Chat bot using webhook - python

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

Related

How do I use Riot Games API with an API key?

I was trying to connect to the Riot Games API with the Python requests module, and it keeps giving me a 401 error. I added an API key, but it still says unauthorized. If anyone knows what is wrong with the code it would be appreciated.
I have tried tinkering and all I have this code:
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"Authorization": "Bearer " + API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
All I really have concluded is that the API key itself is not the issue, it is the request call.
It looks like Riot Games API uses the header X-Riot-Token to pass the authentication token, not Authorization, for some reason.
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"X-Riot-Token": API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
You can also pass the API key as a query string parameter, however this can be slightly less secure in some scenarios.
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot?api_key=" + API_KEY
response = requests.get(URL)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
Use your api key as a parameter rather than a header.
https://americas.api.riotgames.com/riot/?api_key=YOUR-API-KEY
Here is some help I found: https://apipheny.io/riot-games-api/#:~:text=All%20API%20calls%20to%20Riot,re%20making%20the%20request%20on.

In python, how can we connect to API using a certificate, subscription key?

I am trying to connect to an api for which I was provided with link, certificate(.p12) and subscription key.
Having some issue while giving the certificate details. I am trying in the following 2 ways:
1.
import json
from requests_pkcs12 import get,post
url = 'https://....'
pkcs12_filename = '<certificate file path>'
pkcs12_password = '<certificate password>'
headers = {
# Request headers
'Subscription-Key': '<subscription key>',}
response = post(url, headers=headers, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)
print(response.status_code)
import http.client, urllib.request, urllib.parse, urllib.error, base64
#file = "<certificate path>"
headers = {
'Subscription-Key': '<subscriptionkey>',
#'cert' : crypto.load_pkcs12(open(file, 'rb').read(), "<password>").get_certificate(),
'file' : '<certificate path>',
'password':'<certificate password>',}
params = urllib.parse.urlencode({
})
conn = http.client.HTTPSConnection('<api main link>')
conn.request("GET", "<api remaining link>" , params, headers)
response = conn.getresponse()
data = response.read()
print("Status: {} and reason: {}".format(response.status, response.reason))
conn.close()
I am new to API concept. Will someone help me over this?
Refered to this link: How to use .p12 certificate to authenticate rest api
But didn't get what i need to put in data variable

"Bad Gateway" error using Python requests module with multipart encoded file POST

I am getting the error message "Bad Gateway
The proxy server received an invalid
response from an upstream server" with the following code:
import requests
url = "https://apis.company.com/v3/media"
attachments = 'media': ('x.mp3', open('x.mp3', 'r'))}
headers = {'content-type': "multipart/form-data",'cache-control': "no-cache"
'Authorization':"Bearer zzz" }
response = requests.post(url, files=attachments, headers = headers)
print response.text
I'm following the example in the requests Quickstart documentation, where it says "You can also pass a list of tuples to the data argument": http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
What is causing this error and how can I fix it?
The main problem was that I set the content-type in the header. This code works:
import requests
url = 'https://apis.company.com/v3/media'
token = 'token-goes-here'
headers = { 'Authorization' : 'Bearer ' + token }
filename = 'x.mp3'
with open(filename, 'rb') as media_file:
attachments = {
'media': (filename, media_file, 'application/octet-stream')
}
response = requests.post(url, files = attachments, headers = headers)
print response.text

POST body sent as separate request HttpConnection Python

I have the following code where a POST request is sent to a http server with a JSON request body. The debug prints out 2 requests, showing that the request body is sent as a separate request.
import http.client
import json
if __name__ == "__main__":
connexion = http.client.HTTPConnection('localhost',27015)
headers = {'Content-type': 'application/json','Accept': 'application/json'}
dataSent = {'coup': 'e2e4'}
json_dataSent = json.dumps(dataSent)
connexion.set_debuglevel(1)
connexion.request('POST','/faireCoup',json_dataSent,headers)
reponse = connexion.getresponse()
print(reponse.read().decode())
connexion.close()

"Error parsing JSON" when using Spotify API

I am learning Python and I am trying to create a playlist using the Spotify web api but get a http 400 error: Error parsing json. I guess it has to do with an incorrect variable type in the token but I am having a really hard time debugging it as I can't figure out a way to see the post request in raw format.
Posting through the API requires authorizing and this is the script I've created for that:
import requests
import base64
requests.packages.urllib3.disable_warnings()
client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'
def request_token():
# 1. Your application requests authorization
auth_url = 'https://accounts.spotify.com/authorize'
payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
auth = requests.get(auth_url,params = payload)
print '\nPlease go to this url to authorize ', auth.url
# 2. The user is asked to authorize access within the scopes
# 3. The user is redirected back to your specified URI
resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
resp_code= resp_url.split("?code=")[1].split("&")[0]
# 4. Your application requests refresh and access tokens
token_url = 'https://accounts.spotify.com/api/token'
payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
auth_header = base64.b64encode(client_id + ':' + client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
req = requests.post(token_url, data=payload, headers=headers, verify=True)
response = req.json()
return response
This is the function actually trying to create the playlist using the authorization token (import authorizer is the function above):
import requests
import authorizer
def create_playlist(username, list_name):
token = authorizer.request_token()
access_token = token['access_token']
auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
payload = {'name': list_name, 'public': 'false'}
r = requests.post(api_url, params=payload, headers=auth_header)
But whatever I try it only leads to a 400 error. Can anyone please point out my error here?
Solved by adding a json.dumps for the input: json.dumps(payload) and changing the payload to be 'data' and not 'params' in the request.
So the new functioning request equals:
r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)

Categories

Resources