Opsgenie powershell alert post not working - python

I have successfully made an alert post using Python, but cannot get my powershell alert creation to work. I just get a wall of HTML in my response and no alert creation. Message is the only required field.
Here's what I'm using and it does not work
$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
$head = #{"Authorization" = "GenieKey $api"}
$body = #{
message = "testing";
responders =
]#{
name = "TEAMNAMEHERE";
type = "team"
}]
} | ConvertTo-Json
$request = Invoke-RestMethod -Uri $URI -Method Post -Headers $head -ContentType "application/json" -Body $body
$request
Here is my python code I made and it works just fine.
import requests
import json
def CreateOpsGenieAlert(api_token):
header = {
"Authorization": "GenieKey " + api_token,
"Content-Type": "application/json"
}
body = json.dumps({"message": "testing",
"responders": [
{
"name": "TEAMNAMEHERE",
"type": "team"
}
]
}
)
try:
response = requests.post("https://api.opsgenie.com/v2/alerts",
headers=header,
data=body)
jsontemp = json.loads(response.text)
print(jsontemp)
if response.status_code == 202:
return response
except:
print('error')
print(response)
CreateOpsGenieAlert(api_token="XXX")
EDIT: So I've figured out it has something to do with my "responders" section. It has something to do with the [ ]...but I haven't been able to figure out what exactly. If I remove them, it wont work. If I turn the first one around, it won't work. I can get the alert to create successfully, however I keep getting the following error:
] : The term ']' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\file\Tech\user\powershell scripts\.not working\OpsGenieAlert.ps1:7 char:17
+ ]#{
+ ~
+ CategoryInfo : ObjectNotFound: (]:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

You need to convert your $body to JSON
$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
# Declare an empty array
$responders = #()
# Add a new item to the array
$responders += #{
name = "TEAMNAMEHERE1"
type = "team1"
}
$responders += #{
name = "TEAMNAMEHERE2"
type = "team2"
}
$body = #{
message = "testing"
responders = $responders
} | ConvertTo-Json
$invokeRestMethodParams = #{
'Headers' = #{
"Authorization" = "GenieKey $api"
}
'Uri' = $URI
'ContentType' = 'application/json'
'Body' = $body
'Method' = 'Post'
}
$request = Invoke-RestMethod #invokeRestMethodParams

Related

How to fill ACF fields using Wordpress Rest-Api in Python

I'm trying to fill ACF Fields using Wordpress Rest-Api in Python, but when I try to make request it's giving "400 Bad Request". I'm using ACF latest verison 5.11 that comes with in-built api integration.
This is my code, please help me to solve this problem.
import requests
import json
import base64
url = "example.com/wp-json/wp/v2/posts"
user = "exmaple#gmail.com"
password = "RIHr O7kE SCn0 LXVW xyPc jBn9"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
post = {
"title" : "Hello World",
"type" : "post",
"status" : "publish",
"content" : "This is my first post created using rest API",
"acf" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
}
responce = requests.post(url , headers=header, json=post)
print(responce.status_code, responce.reason)
Three things to check/change here
In your functions.php file in WordPress, ensure you've registered the post meta. For example
function function_name() {
register_meta('post', 'youtube_url',
[
'object_subtype' => 'post',
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
}
]
);
}
add_action( 'rest_api_init', 'function_name' );
2 then update...
"acf" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
to...
"meta" : {
"youtube_url": "https://www.youtube.com/watch?v=0outb6oSJW4"
}
3 And finally, in the field group settings in ACF, ensure 'Show in REST API' is selected

Python - For Loop not iterating through multiple instances of a dictionary

I have the following code
def generate_matter(leaver_user,vaultAccessToken):
for user in leaver_user:
url = "https://vault.googleapis.com/v1/matters/"
headers = {
"Accept" : "application/json",
"Content-Type" : "application/json",
"Authorization": "Bearer " + vaultAccessToken
}
body = json.dumps ({
"state": "OPEN",
"description": "Generated by Python",
"name": user + "'s archive"
})
response = requests.request(
"POST",
url,
headers=headers,
data=body
)
jsonContent = json.loads(response.text)
matterID=jsonContent["matterId"]
#print("Matter ID for " + user + " is " + matterID)
#print(jsonContent)
matter={
"matterInstance": {
"user": user,
"userInfo": {
"matterID": matterID
}
}
}
return matter
def generate_search_query(matter,leaver_user,vaultAccessToken):
print(matter)
for key, value in matter.items():
user=(matter['matterInstance']['user'])
matterID=(matter['matterInstance']['userInfo']['matterID'])
url = "https://vault.googleapis.com/v1/matters/"+matterID+"/savedQueries"
headers = {
"Accept" : "application/json",
"Content-Type" : "application/json",
"Authorization": "Bearer " + vaultAccessToken
}
body=json.dumps({
"displayName": user + "'s email search query",
"query": {
"corpus": "MAIL",
"dataScope": "ALL_DATA",
"searchMethod": "ACCOUNT",
"accountInfo": { "emails": [user]},
"mailOptions": {"excludeDrafts" : "false"},
"timeZone": "Atlantic/Canary",
"method": "ACCOUNT"
}}
)
response = requests.request(
"POST",
url,
headers=headers,
data=body
)
jsonContent = json.loads(response.text)
print(matterID)
print(body)
print(jsonContent)
savedQueryID=jsonContent["savedQueryId"]
print("savedQueryId for " + user + " is " + savedQueryID + " matterID is " + matterID)
matter={
"matterInstance": {
"user": user,
"userInfo": {
"matterID": matterID,
"savedQueryID": savedQueryID
}
}
}
return matter
matter=generate_matter(leaver_user,vaultAccessToken)
savedQueryID=generate_search_query(matter,leaver_user,vaultAccessToken)
What works is the first function - generate_matter().
This returns multiple instances of matter such as
{'matterInstance': {'user': 'testing.testing#domain.com', 'userInfo': {'matterID': '12-34-56-78-91'}}}
{'matterInstance': {'user': 'adtesting#domain.com', 'userInfo': {'matterID': '12-34-56-78-99'}}}
However the function generate_search_query() only seems to execute on the first instance of matter.
I've confirmed this by printing the matter in generate_search_query() before the for loop executes and only the first instance of matter is returned.
{'matterInstance': {'user': 'testing.testing#domain.com', 'userInfo': {'matterID': '12-34-56-78-91'}}}
Adding from the below comments as its useful information.
Printing matter within the for loop from generate_matter does return multiple instances of matter.
Printing matter immediately before calling savedQueryID=generate_search_query(matter,leaver_user,vaultAccessToken) only returns a single instance of matter, so this is when i print / call it outside of the function
How would I solve this so that multiple instances of matter are executed in the for loop within generate_search_query() ?
Thanks
At the end of generate_matter() you're overwriting matter with the last iteration, and then returning it, so its only returning a single element.
To fix this, create a list at the start of generate_matter() (matterList = []) and then where you have matter={...} in generate_matter() replace it with matterList.append({...}). Then at the end of the function return matterList instead of matter.
In generate_search_query() you'll need to wrap everything in another for loop to loop through the list.

"Errors": ["Cannot parse input stream due to I/O error as JSON document: Parse error: expected '}' but saw ',' [ chars read = *****]

I'm trying to create defects programmatically. I am getting a couple errors and having trouble getting any further. Here, essentially, is the code:
import requests, json
rally_auth = ('**uid', '***pwd')
rally_auth_url = 'https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize'
rally_defect = 'https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement'
workspace_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/workspace/123***'
fe_project_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/project/134***'
user_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/user/106***'
l2_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/portfolioitem/l2roadmapitem/166***'
headers = {"Accept": "application/json", "Content-Type": "application/json", "ZSESSIONID" : "_iv********"}
s = requests.Session()
token = '_iv**********'
url = rally_defect + '/create?key=' + token
payload = {
'Workspace' : workspace_ref,
'Name': 'Tesing',
'Description': 'Testing',
'Project': fe_project_ref,
'StoryType': "New Feature",
'PortfolioItem' : l2_ref,
'Owner' : user_ref,
'ScheduleState':'Defined',
}
r = s.put(url, data=json.dumps(payload), headers=headers)
print r.text
print r.status_code
{"CreateResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": ["Cannot parse input stream due to I/O error as JSON document: Parse error: expected '}' but saw ',' [ chars read = *****], "Warnings": []}}
You will need to provide the Artifact type in your JSON. Below is an update to your code that should work for you. I am also assuming 'StoryType' is a Custom String Field. You will need to update the name to 'c_StoryType' to add a value to a Custom Field.
I also removed some of the extra lines. Since you are using an API Key and setting it as the ZSessionID in the Headers, you will not need the Security Token to create the Artifact.
import requests, json
rally_defect = 'https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement'
workspace_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/workspace/123***'
fe_project_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/project/134***'
user_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/user/106***'
l2_ref = 'https://rally1.rallydev.com/slm/webservice/v2.0/portfolioitem/l2roadmapitem/166***'
headers = {"Accept": "application/json", "Content-Type": "application/json", "ZSESSIONID" : "_iv********"}
s = requests.Session()
url = rally_defect + '/create'
payload = {
"HierarchicalRequirement" : {
"Workspace" : workspace_ref,
"Name" : "Tesing",
"Description" : "Testing",
"Project" : fe_project_ref,
"c_StoryType" : "New Feature",
"PortfolioItem" : l2_ref,
"Owner" : user_ref,
"ScheduleState" : "Defined"
}
}
r = s.put(url, data=json.dumps(payload), headers=headers)
print r.text
print r.status_code

GitHub GraphQL API Problems parsing JSON

What is wrong here?
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query+'\"}',headers=headers)
print (r2.json())
I've got
{'message': 'Problems parsing JSON', 'documentation_url': 'https://developer.github.com/v3'}
but this snippet of code below works correctly
query1= '''{ viewer { login name } }'''
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": \"'+query1+'\"}',headers=headers)
print (r2.json())
I've tried out to change quotes (from " into ' or with " and so on) but it doesn't work.
The problem is related with the double quotes (").
On the first snippet, when you join the '{"query": \"'+query+'\"}' with the query variable, you get the following result:
{"query": "{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }"}
Notice how the double quote from "ALEXSSS" are not escaped, therefore the resultant string is not a json valid format.
When you run the second snippet, the resultant string is:
{"query": "{ viewer { login name } }"}
which is a valid json string.
The easiest and best solution is simply use the JSON library instead of trying to do it manually, so you won't need to worry about escaping characters.
import json
query='{ repositoryOwner(login : "ALEXSSS") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', json.dumps({"query": query}), headers=headers)
print (r2.json())
But remember that you could also just escape the characters on the query manually:
query='{ repositoryOwner(login : \"ALEXSSS\") { login repositories (first : 30){ edges { node { name } } } } }'
headers = {'Authorization': 'token xxx'}
r2=requests.post('https://api.github.com/graphql', '{"query": "'+query1+'"}', headers=headers)
print (r2.json())
it works as expected :)

REST API File Upload - Porting Python to PowerShell

Could anyone help me perform the following Python process in PowerShell?
json_res = json.loads(res.text,object_pairs_hook=collections.OrderedDict)
files = {'file':open(image_path,'rb').read()}
_data = json_res.items()
_data[1] = ('upload_params',_data[1][1].items())
upload_file_response = requests.post(json_res['upload_url'],data=_data[1][1],files=files,allow_redirects=False)
Here is my PowerShell to get the initial json response used in the json_res object using:
$initialization_parameters = #{
"name" = $($image.Name);
"size" = $($image.Length);
"content_type" = $(if ($image.Extension -match 'jp*g') { "image/jpeg" } elseif ($image.Extension -match 'png') { "image/png" } elseif ($image.Extension -match 'gif') { "image/gif" } else { "image/jpeg" });
"parent_folder_path" = "profile pictures";
"as_user_id" = $("sis_user_id:" + $file_id)
}
$initialization_parameters = $initialization_parameters | ConvertTo-Json
$initial_response = Invoke-RestMethod -Uri $avatars_base_url -Headers $headers -Body $initialization_parameters -ContentType "application/json" -Method POST
I am not sure how to do the next request though and add the image for upload - I have tried sending a byte array OR just the local file path, but those don't seem to work.
Specifically, I would like to know how to best mimic the 2nd and 5th lines of the Python code I have there in PowerShell.
Any help would be appreciated.
I think this is what you need to do. If not, hopefully it will at least put you on the right track...
$FileContent = [System.IO.File]::ReadAllBytes($Image.FullName)
$UploadInfo #{
"File" = $Image.Name
"Data" = [System.Convert]::ToBase64String($FileContent)
}
$FileUpload = Invoke-JSONMethod -uri $Upload_URL -ContentType "application/json" -Method POST -Body (ConvertTo-Json $UploadInfo) -AcceptType "application/json"

Categories

Resources