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.
Related
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
I'm currently working on an app, one functionality of it being that it can add songs to the user's queue. I'm using the Spotify API for this, and this is my code to do so:
async def request():
...
uri = "spotify:track:5QO79kh1waicV47BqGRL3g" # temporary, can change later on
header = {'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "{} {}".format(TOKEN_TYPE, ACCESS_TOKEN)}
data = {'uri': uri}
resp = requests.post(url="https://api.spotify.com/v1/me/player/queue", data=data, headers=header)
...
I've tried a lot of things but can't seem to understand why I'm getting Error 400 (Error 400: Required parameter uri missing).
so the Spotify API for the endpoint you're using suggests that the uri parameter required should be passed as part of the url, instead of as a data object.
Instead of data = {'uri': uri} can you please try adding your uri to the end of the url as such:
resp = requests.post(url="https://api.spotify.com/v1/me/player/queue?uri=?uri=spotify%3Atrack%3A5QO79kh1waicV47BqGRL3g", headers=header)
I also suggest using software like postman or insomnia to play around with the requests you send.
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!
Without using the requests module, how can I send messages to a Discord webhook?
I have tried following code:
import urllib2
import json
url = 'webhook url'
values = {"username": "Bot", "text": "This is a test message."}
data = json.dumps(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
This returns following error:
urllib2.HTTPError: HTTP Error 403: Forbidden
You can send the message to a Discord webhook.
make a discord webhook with this tutorial.
Then, use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you.
Use the discord.Webhook.send method to send a message using the webhook.
if you're using version 2 of discord.py, this snippet will work for you:
from discord import SyncWebhook
webhook = SyncWebhook.from_url("your-url")
webhook.send("Hello")
if you're not using version 2 you can use this snippet:
import requests
from discord import Webhook, RequestsWebhookAdapter
webhook = Webhook.from_url("youre-url", adapter=RequestsWebhookAdapter())
webhook.send("Hello")
Your data is not correct - according to the Discord API documentation, it should look like this:
values = {
'username': 'Bot',
'content': 'your message here'
}
Please note that one of content, file or embeds is required. Otherwise the API will not accept your request.
My first suggestion is the following steps:
Make a webhook in the desired Discord channel.
use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you.
use the discord.Webhook.send method to send a message.
another option is to use discord.py (v2) like this:
from discord import SyncWebhook
webhook = SyncWebhook.from_url("url-here")
webhook.send("Hello World")
I'm attempting to post an image to a Slack channel utilizing web hooks. This basic setup has allowed me to post text to the channel, but I've been unable to post the image. Here's my code:
def posting():
import requests
import json
url = 'https://webhook'
image = {'media': open('trial.jpg', 'rb')}
r = requests.post(url, files=image)
r.json
When I post the text, a web hook bot appears in the channel and posts it. Do I need some further authentication to post? Or is it a matter of Slack having their own API for uploading and wants me to go through that? Or something something bots don't have rights to post images?
I took a look at some other questions here, but they didn't appear to be using web hooks or bots, so I'm not sure if my issue is something involving those.
You can do this through the Slack API using their files.upload method: https://api.slack.com/methods/files.upload
You will need an API auth token for this to work properly. You can set up a testing token or follow the instructions to register your program to get a long term one: https://api.slack.com/web#basics
Also, 'media' doesn't seem to be the right json key to use for file uploads:
http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
Here's an example using requests to send an image to a channel. Use '#username' if you want the image to go to a specific user. I've included the content type and header but it should work without them as well.
This will print the response from Slack.
import requests
def post_image(filename, token, channels):
f = {'file': (filename, open(filename, 'rb'), 'image/png', {'Expires':'0'})}
response = requests.post(url='https://slack.com/api/files.upload', data=
{'token': token, 'channels': channels, 'media': f},
headers={'Accept': 'application/json'}, files=f)
return response.text
print post_image(filename='path/to/file.png', token='xxxxx-xxxxxxxxx-xxxx',
channels ='#general')