Sending Python variable contents to a Slack Webhook - python

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!

Related

Capture the UserID and send to Slack Channel using Python

I'm having an issue capturing the userid that will send a message to my Slack Channel and give me a visibility who uses my Python script. The variable name that I use in my Workflow Slack Channel is User and it's data type is Text. The script works fine if I hard code the user but that is not what I want.
I tried below script but it gives me "SyntaxError: invalid syntax"
import json
import requests
#This will send a slack message to my logs channel
url = "https://hooks.slack.com/workflows/XXXXXX/XXXXXX/XXXXXX/XXXXX"
data = {'User': <#User>, 'Message': 'used the app!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)
I'm expecting the script will capture the userid whoever uses the script and send message to my Slack Channel. Correct syntax would be nice. Thank you very much.

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

Data Scraping Discord Messages Python

I am trying to web scrape Discord messages using Python from specific server channels.
import requests
import json
def retrieve_messages(channelid):
headers = {
'authorization': 'enter the authorization code'
}
# need to make a request to the url
r = requests.get(
f'https://discord.com/api/v9/channels/{channelid}/messages', headers=headers)
# create JSON object
jsonn = json.loads(r.text)
# we can now use a for loop on this JSON object
for value in jsonn:
print(value, '\n') # new line as well to separate each message
retrieve_messages('channel server id')
I am expecting the messages to be outputted in the terminal but instead I keep receiving the following output.
The output that I am getting instead of the messages
you're probably using a bot
token = "token"
headers = {
'authorization': f'Bot {token}'
}
try this

Is it possible to make a POST request to Slack with AWS Lambda using only native libraries?

I am trying to make a POST request to Slack using webhooks. I can send a curl to my Slack instance locally but when trying to do so in lambda I run into trouble trying to send the payload.
Everything I've seen says I must use and zip custom libraries but for the purposes of what I'm doing I need to use native python code. Is there a way to send this POST request?
import json
import urllib.request
#import botocore.requests as requests
def lambda_handler(event, context):
message=event['message']
response = urllib.request.urlopen(message)
print(response)
This code gives me a 400 error which is how I know I'm hitting the URL I want (URL is in the message variable) but every attempt at sending a payload by adding headers and a text body seems to fail.
You may try as below:
SLACK_URL = 'https://hooks.slack.com/services/....'
req = urllib.request.Request(SLACK_URL, json.dumps(message).encode('utf-8'))
response = urllib.request.urlopen(req)
Please find attached lambda_handler code, hope this helps you.
All the messages to be posted on slack are put on a SNS topic which in turn is read by a lambda and posted to the slack channel using the slack webhook url.
import os
import json
from urllib2 import Request, urlopen, URLError, HTTPError
# Get the environment variables
SLACK_WEBHOOK_URL = os.environ['SLACK_WEBHOOK_URL']
SLACK_CHANNEL = os.environ['SLACK_CHANNEL']
SLACK_USER = os.environ['SLACK_USER']
def lambda_handler(event, context):
# Read message posted on SNS Topic
message = json.loads(event['Records'][0]['Sns']['Message'])
# New slack message is created
slack_message = {
'channel': SLACK_CHANNEL,
'username': SLACK_USER,
'text': "%s" % (message)
}
# Post message on SLACK_WEBHOOK_URL
req = Request(SLACK_WEBHOOK_URL, json.dumps(slack_message))
try:
response = urlopen(req)
response.read()
print(slack_message['channel'])
except HTTPError as e:
print(e)
except URLError as e:
print(e)

Slack Webhook - returning invalid_payload

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

Categories