Slack Webhook - returning invalid_payload - python

I'm trying to send data to a slack webhook but I keep getting an invalid_payload response.
My results variable from below looks like this if i print it in my script:
{u'results': [{u'TunnelID': 11111}]}
webhook_url = 'https://hooks.slack.com/services/xxx/xxx/xxx'
response = requests.post(
webhook_url, data=json.dumps(results),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:%s'
% (response.status_code, response.text)
)
I'm sure its a problem with the way my results variable is formatted, but I can't seem to find the right way to format it.

Perhaps you mean to include results as the message itself? In which case, something like this?
response = requests.post(
webhook_url, json={'text': str(results)},
headers={'Content-Type': 'application/json'}
)

Related

PAYPAL IPN Call responds with Status Retrying and HTTP-Code 404

I am trying to set up a notification from on a payment. Here is my code:
def PayPal_IPN():
'''This module processes PayPal Instant Payment Notification messages (IPNs).'''
# Switch as appropriate
VERIFY_URL_PROD = 'https://ipnpb.paypal.com/cgi-bin/webscr'
VERIFY_URL = VERIFY_URL_PROD
# Read and parse query string
params = request.form.to_dict()
# Add '_notify-validate' parameter
params['cmd'] = '_notify-valudate'
# Post back to PayPal for validation
headers = {'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'Python-IPN-Verification-Script'}
r = requests.post(VERIFY_URL, params=params, headers=headers, verify=True)
r.raise_for_status()
# Check return message and take action as needed
if r.text == 'VERIFIED':
print("SUCCESSFULL")
elif r.text == 'INVALID':
print("FAILURE")
else:
print("NOTHING HAPPENED?")
return ""
Here is my error message:
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://ipnpb.paypal.com/cgi-bin/webscr....
Can someone help me figure out what I am not understanding? maybe the link has changed?
Here is the documentation I'm looking at https://developer.paypal.com/api/nvp-soap/ipn/IPNIntro/
I've tried changing the ipnpb to www. and still no luck.
The problem is the format of params. I'm not sure what request.form.to_dict() returns, but I do know that when you add cmd=_notify_validate it should be in this format:
params.append(('cmd', '_notify-validate'))
Also returning the appropriate format is urllib.parse.parse_qsl

Pysnow Usage of sysparm_query_category

As I cannot see any reference on how to use properly the sysparm_query_category, may I confirm on how did you append the sysparm_query_category in get request?
Added below line of codes. I hope someone can help and guide me as I'm new to ServiceNow. Thanks!
from pysnow import Client
...
resource = self.client.resource(api_path=F"/table/{table}")
resource.parameters.add_custom({"sysparm_query_category": "cat_read_generic"})
request = resource.get(query=query, fields=fields)
https://developer.servicenow.com/dev.do#!/reference/api/sandiego/rest/c_TableAPI
I am not aware pysnow API. I hope this helps. Else refer to the comment above.
#Need to install requests package for python
#easy_install requests
import requests
# Set the request parameters
url = 'https://demonightlycoe.service-now.com/api/now/table/incident?sysparm_query=category%3Dcat_read_generic&sysparm_limit=1'
# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'
# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)
Upon checking and testing, we can use the add_custom
client.parameters.add_custom({'foo': 'bar'})
that would be additional to the parameters like &foo=bar
https://pysnow.readthedocs.io/en/latest/usage/parameters.html

Python - How to Save 2 values outputf.write

I am trying to save user:password if got 200 response status code to a textfile.
but it only saves one value "User" I dunno why. I've tried to add multi values with failed attempts.
outputFilepath = "validaccounts.txt"
def OutPut(text):
with open(outputFilepath, "a") as outputf:
outputf.write("{}\n".format(text))
#headers removed#
#Payload removed#
response = requests.post(url, data=payload, headers=headers, proxies=proxies, timeout=10)
#print(response.text)
if response.status_code == 200:
OutPut(user, password)
except:
pass
How to make it save User:password format in textfile what needed to be edited in outputf.write?
Note: I've removed the payload + headers, I just need to fix the output save user:password part.
Thank you,
regards.
Fixed by doing the following:
def OutPut(text, text1):
with open(outputFilepath, "a") as outputf:
outputf.write("{}:{}\n".format(text, text1))
output(user, password)

Sending Python variable contents to a Slack Webhook

I'm new to looking at python with slack. I've successfully managed to send data from a python script to a slack webhook, using code similar to the following:
import json
import requests
# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/
webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
slack_data = {"text": "<https://alert-system.com/alerts/1234|Click here> for details!"}
response = requests.post(
webhook_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
I'm looking for a way to sent the contents of a python variable in the script as the slack_data payload. For example, if I had a 'date' variable i'd like to include it in the string sent to slack, rather than just the text string listed in the slack_data variable. Can anyone advise how to do this please?
Thanks in advance!

Requests.post error| TypeError: post() takes at least 1 argument (1 given)

I'm using Python 2.7.10 64-bit.
In the update_jira_field method, I'm getting the following error:
TypeError: post() takes at least 1 argument (1 given)
I tried also requests.put(), combination of json = payload while declaring the payload as a json, but still got the same error.
I'm not sure what am I doing wrong, never experienced this error while using the requests module.
import requests
import json
import urllib2
auth = *****
propertKey = 'customfield_13557'
headers = {'Accept':'application/json','Bearer':****'}
def get_jira_real_id(jiraKey):
endpoint = 'https://****.atlassian.net/rest/api/3/issue/{0}'.format(jiraKey)
response = requests.get(endpoint, headers = headers, auth = auth)
if response.status_code == 200:
print "Success getting Jira Id"
response = json.loads(response.text)
return response['id']
def update_jira_field(jiraId,jiraKey):
endpoint = 'https://****.atlassian.net/rest/api/3/issue/{0}'.format(jiraId)
payload = dict({"fields": {"customfield_13557":{"self": "https://****.atlassian.net/rest/api/3/customFieldOption/14915", "value": "Yes", "id": "14915"}}})
response = requests.post(endpoint = endpoint, headers = headers, auth = auth, data = payload)
if response.status_code == 200:
print "Success! Updated", jiraId, jiraKey
jiraList = ['****']
for jiraKey in jiraList:
jiraId = get_jira_real_id(jiraKey)
update_jira_field(jiraId, jiraKey)
print "Done Done Done"
Any idea why I get this error? and how do I fix it?
You try to pass in a named parameter named endpoint, but the correct name is url. It whould work if you change the line to
response = requests.post(endpoint, headers = headers, auth = auth, data = payload)

Categories