Discord API "Cannot send an empty message" - python

I'm trying to manually respond to a discord API call by getting the token from the logs of my API but when i send the request, it responds with
<Response [400]>
{"message": "Cannot send an empty message", "code": 50006}
Code is below:
import requests
application_id = "9999999999032"
payload = {"type": 4,
"data": {"content": "Congrats on sending your command!"}}
interaction_token = "aW50****lm"
headers = {'content-type': 'application/json'}
r = requests.patch(f"https://discord.com/api/v9/webhooks/{application_id}/{interaction_token}/messages/#original", headers=headers, json=payload)
print(r)
print(r.text)
Link to docs https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type

I haven't tested your code yet, but I think the problem is in the payload variable, instead of doing this:
{
"type": 4,
"data": {
"content": "Congrats on sending your command!"
}
}
Do this:
{
"type": 4,
"content": "Congrats on sending your command!"
}
If it doesn't work, I don't know how to fix it.

Related

Creating Jira issue with REST API

Having issues with trying to create an issue with Jira through the APIs, below is a sample of my code. We are using enterprise jira, I have to replace certain sections with so I hope it wont effect your ability to provide help.
from requests.auth import HTTPBasicAuth
import requests
user = '<ID>'
password = '<password>'
url = 'https://<enterprise>jira.<domain>.com/projects/<MYKEY>/rest/api/3/issue'
headers = {
'Content-Type': 'application/json',
}
json_data = {
"fields": {
"project": {
"key": "<MYKEY>"
},
"summary": "Creating From Collection",
"description": {
"type": "doc",
"version": 1,
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "This is an autogenerated issue from a demo."
}
]
}
]
},
"issuetype": {
"name": "Task"
}
}
}
response = requests.post(
url,
headers=headers,
json=json_data,
verify=False,
auth=(user, password),
)
I get error code 405 and the following message when running print(response.text):
<!doctype html>HTTP Status 405 – Method Not Allowedbody {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}HTTP Status 405 – Method Not AllowedType Status ReportMessage HTTP method POST is not supported by this URLDescription The method received in the request-line is known by the origin server but not supported by the target resource.Apache Tomcat/8.5.78
Im sure I'm doing something wrong so any help will be appreciated.
Also I have verified I have the right access by manually going to the project and creating an issue.
Your URL is wrong. For creating a Jira issue you want to use the create issue endpoint.
For server/datacenter:
url = 'https://<enterprise>jira.<domain>.com/rest/api/2/issue'
For cloud:
url = 'https://<enterprise>jira.<domain>.com/rest/api/3/issue'
You need to use a POST request to either of these endpoints.

Elastic search Api

Hey Stackoverflow fam,
I am working on an API which pulls requests from elastic search tool and displays it.
I am trying to pull data using get request
import requests
import json
payload = {
"query": {
"match": {
"metric": "metric_name"
}
}
}
url = "https://url_name:9200/siren-kinesis*/_search"
payload = json.dumps(payload)
print(type(payload))
headers = {
'Content-Type': 'application/json',
}
result = requests.get(url=url,data=payload,headers=headers,auth=("test#example.com","*"))
print(result.json())
and getting the following error
{
"error": {
"root_cause": [
{
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
}
],
"type": "security_exception",
"reason": "unable to authenticate user [test#example.com] for REST request [/_search]",
"header": {
"WWW-Authenticate": "Basic realm=\"security\" charset=\"UTF-8\""
}
},
"status": 401
}
I am Basic Auth .i.e. passing username and password for authorization.
Can somebody help me ?
In the case of Basic Auth in any request, if you're requesting via postman you can provide the credentials in the Authentication tab. But In the case of Code/Console/Browser, the certificates must be given in the request URL.
e.g.
https://username:password#URL
https://admin:admin#www.the-internet.herokuapp.com/basic_auth

Invalid Credentials Error when updating file to Google drive API

I have been trying to replace files using google API only with the Python HTTPS module. Can somebody please help me with how I can replace the file only with an HTTPS module?
import sys
import json
import requests
import sys
Acesstoken = ""
params = {
"grant_type": "refresh_token",
"client_id": "xxx",
"client_secret": "xxxx",
"refresh_token": "xxxx"
}
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
r = requests.post(authorization_url, data=params)
if r.ok:
token = str((r.json()['access_token']))
Refreshtoken = Acesstoken + token
else:
print('Failed')
sys.exit()
headers = {
"Authorization": "Bearer " + str(Acesstoken),
}
metadataF= {
'name': "Test",
'parents':["1vXn346cBsarvkPthqtI1OLzsMzeQQlBX"]
}
files = {
'data':('metadata', json.dumps(metadataF), 'application/json; charset=UTF-8'),
'file': open("./credentials.json", "rb"),
}
r2= requests.post(
"https://www.googleapis.com/upload/drive/v3/files/XXXXXXXX?uploadType=multipart",
headers= headers,
files= files
)
print(r2)
I only want to use Python's Https Module only. I don't want to use google client library. Please help me if this is possible.
Error
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
<Response [401]> with this ` { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" }
Invalid Credentials means that your token has expired. Access tokens are only valid for an hour. Refresh tokens are only valid for seven days if your app is still in testing.
As documented here the error 401 error: Invalid credentials is related to:
... the access token you're using is either expired or invalid. This error can also be caused by missing authorization for the requested scopes ...
If the token works with another type of request you may want to check the scopes.

Error "name "true" not defined when sending POST request

I am trying to send a POST request that requires the literal true to be sent as part of the JSON payload. I know I can change it to True which Python likes but it fails with an API (SCIM) that I am testing.
How do I send the word true and have Python submit it as-is? This does work when I send via Postman. Using an example with httpbin below with the same error.
import requests
headers = {
"Accept": "Application/json",
"Content-Type": "Application/json"
}
payload = {
"emails": [{
"primary": true,
"value": "jack#justjack.com",
"type": "work"
}]
}
print (type (payload))
print (payload)
resp = requests.post ('http://httpbin.com/post',headers=headers,data=payload)
print(resp.content)
Error Message I get is
"primary": true,
NameError: name 'true' is not defined"
Use Python's regular True and convert your dict to a JSON string when you create your payload:
import json
payload = {
"emails": [{
"primary": True,
"value": "jack#justjack.com",
"type": "work"
}]
}
resp = requests.post('http://httpbin.com/post', headers=headers, data=json.dumps(payload))
# ^^^^^^^^^^
in python we are using True or False instead of true / false
you can read further here in PEP-285

logging into the MATCHBOOK API with Python Requests

I am trying (legitimately and with the go ahead from the site)to log into the betting exchange matchbook.com through their api.
The documentation states:
To Login: https://www.matchbook.com/bpapi/rest/security/session
and
Example Request
POST /security/session
{
"username": "j_henry",
"password": "******"
}
Example Response
{
"session-token": "1418_1234567890",
"user-id": 1418,
"account": { // Same as GET /account API response.
...
}
}
I am using Requests and have the following code:
payload = {"username": "********", "password": "************"}
r = requests.post('https://www.matchbook.com/edge/rest/security/session', data=payload)
print (r.status_code)
I get error code 415? I must be getting the wrong type of response??
I have looked at a lot of very similar posts on here, and I am about to ask matchbook's team, but before I do has anybody got any ideas?
You might have to specify Content-Type, try to add a header to tell the server it's JSON formatted:
payload = {"username": "********", "password": "************"}
headers = {"Content-Type": "application/json;"}
r = requests.post('https://www.matchbook.com/edge/rest/security/session', data=payload, headers=headers)
print (r.status_code)
It does not appear from your code that you are JSON-encoding your payload. The endpoint is likely expecting JSON.
Try this:
payload = '{"username": "********", "password": "************"}'

Categories