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")
Related
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.
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 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)
Give me solution how can i get log directly to slack channel using python and flask.I am able to use logging and save it in log file but i want that info,warning,error,critical,debug logs should directly send to slack channel.
Here is an example of sending a message to a Slack channel via. Python. You must have a Slack web hook configured for your Slack group, which you can then add onto the hook var.
import json, requests
def sendMessageToSlack():
hook = "https://hooks.slack.com/services/<hook goes here>"
headers = {'content-type': 'application/json'}
payload = {"attachments":[
{
"fallback":"",
"pretext":"",
"color":"#fff",
"fields":[
{
"title":"",
"value":"",
"short": False
}
]
}
]
}
r = requests.post(hook, data=json.dumps(payload), headers=headers)
print("Response: " + str(r.status_code) + "," + str(r.reason))
Providing the response returns a 200 code, you should have a message in your channel.
I don't know why you want to utilize flask...
I think you can just use Slack API client together with its Documentation. Basic usage is what you're looking for (coloring etc.).
Using your own solutions isn't recommended - sometimes API changes and you would have to maintain it. Official API client gives you level of abstraction and you don't have to worry about sudden errors.
Posting message (copied from github):
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)
sc.api_call(
"chat.postMessage",
channel="#python",
text="Hello from Python! :tada:"
)
You can generate test token on this website and try it for yourself.
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')