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
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'm trying to make my zabbix send a payload with trigger information to a rundeck server, so it runs a script based into the information to restart services and solve low level problems.
I'm facing a problem trying to parse the json to send it to rundeck, here's the code on my script # zabbix server:
#!/usr/bin/env python3
import sys
import requests
import json
import logging
# set logging
#logging.basicConfig(filename='/tmp/script.log', level=logging.INFO)
# Webhook URL ( localhost is a example )
api_url = 'http://localhost:4440/api/41/webhook/rLT583Yb0lOkObrFvm6iUz3YjLKWqhal#webhook-listener'
# setting up zabbix payload
#payload = sys.stdin.read() ( couldnt make this work )
payload = '{"alertid": "666", "clock": "1615696071", "message": "Trigger: Server memory usage is too high\nTrigger status: PROBLEM\nTrigger severity: Warning\nTrigger URL: http://zabbix.example.com/tr_events.php?triggerid=11839&eventid=23945\n\nItem values:\n\n1. Memory usage is 85.61% (sign: greater than) (threshold: 70.00%)", "sendto": "admin#example.com", "subject": "Zabbix server: {TRIGGER.NAME}", "eventid": "12345", "hostname": "Testing Variables"}'
# Loading the JSON ( already tried the methods below )
#data = dict(payload)
#data = json.loads(payload)
# Validando o payload
if 'hostname' not in data or not isinstance(data['hostname'], str):
logging.error('Payload com valor hostname inválido')
sys.exit(1)
if 'alertid' not in data or not isinstance(data['event_id'], str):
logging.error('Payload com valor event_id invalido')
sys.exit(1)
# Sorting payload fields
hostname = data['hostname']
event_id = data['alertid']
# setting trigger data as data dictionary ( rundeck data )
trigger_data = {
'hostname': hostname,
'event_id': event_id,
}
# Saving payload as txt to validate
#with open('/tmp/payload.txt', 'w') as f:
#f.write(payload)
# Set up headers
headers = {'Content-Type': 'application/json'}
# Manda o Post
response = requests.post(api_url, data=payload, headers=headers)
# Logando a resposta
logging.info(response.text)
# Print
print(response.text)
This script should bring trigger data through a payload into rundeck, so rundeck understands the payload and read the argument, so i can base my job on the 'hostname' variable ( that zabbix sends ).
I'm getting json parsing error when i run it
json.decoder.JSONDecodeError: Invalid control character at: line 1 column 95 (char 94)
I'm loosing hair, i already tried other ways to parse this json ( ast and dict ), but not seems to work.
already tried other ways to parse the json
already sent the data via the payload directly as text ( json validated )
I ended encoding the webhook function of Zabbix instead of using a script. Thank you guys for your help.
I want to GET a single object from an array in my api. How do I do it.
from urllib2 import Request, urlopen
headers = {
'Content-Type': 'application/json',
'X-Auth-App-Key': 'BvBdsGHQKc1dOOWGMcy0f07XXXXXXXXX0zv5zxHNDhf4P5NFElwKsZWWV3QceKq5J'
}
request = Request('https://XXXXXXt.com/api/v1.0/clients/123', headers=headers)
response_body = urlopen(request).read()
print response_body
Response:
{"id":123,
"isLead":false,
"clientType":1,
"contacts: [ {
"id":174,
"clientId":123,
"email":"mmayert#example.net",
"phone":"1-210-900-9283",
"name":null,
"isBilling":true,
"isContact":true,
"types":[
{"id":1,
"name":"Billing"},
{"id":2,"name":"General"}]}]**,
I have an existing API and I'm trying to create a web app with Twilio for customer support. When a ccertain phone number calls ie. a client, it triggers a web hook (the web app) that goes and formulates a GET command to retrieve the client with that certain phone number so it can greet him
Here is a snippet of code:
api_url = {url}
auth_head = {key: value} << my api authentication header
data = {'title':'Python'} << the valid json object format that the api accepts
Here is what I tried:
data = json.dumps(data)
json_obj = json.loads(data)
response = requests.post(api_url, headers = auth_head, data = json_obj)
print(response.text)
Here is the output:
"400 Bad request"
To make sure the url and my api token key work I tried GET:
response = requests.get(api_url, headers = auth_head)
print(response.status_code)
Output:
"200"
So the url and api token work fine. I feel I am not sending the correct json object construct that the api wants
You don't need to send data as json. Just send data as dictionary. It will accept. requests automatically will encode your dictionary to json
I am trying to hook up to MailChimp's api, in my Django application, to add an email to one of my lists. Seems pretty simple enough. I add my api key to the header of the request, with the email address and other variable in the body of the request. every time I try and connect though, I get a response status code of 400. The message says there is a JSON parsing error, and that my JSON is either formatted incorrectly, or there is missing data required for the request. I am making this same api call however with Postman, and am getting a good response back.
view function
import requests
def join_newsletter(request, email):
# hash the user's email for mailchimp's API
# m = hashlib.md5()
# c_email = email
# m.update(c_email.encode('utf-8'))
# email_hash = m.hexdigest()
api_key = 'apikey ' + settings.MAILCHIMP_API
api_endpoint = api_endpoint
data = {
"email_address": email,
"status": "subscribed"
}
header = {
'Authorization': api_key
}
r = requests.post(api_endpoint, data=data, headers=header)
message = r.content
return message