I've been trying to make a discord webhook, and for some reason I can't get it to send to save my life. I have all the embeds in a json file, and am trying to run it with python. Any help would be greatly appreciated.
json file:
{
"embeds": [
{
"title": "Title",
"color": 11393254,
"fields": [
{
"name": "Name1",
"value": "value1"
},
{
"name": "Name2",
"value": "value2",
"inline": true
},
],
"footer": {
"text": "Footer",
"icon_url": "random image url"
},
"timestamp": "now",
"thumbnail": {
"url": "random image url"
}
}
],
"username": "Username"
}
python code:
import requests, json
with open('webhook.json') as json_file:
data = json.load(json_file)
url = 'https://discord.com/api/webhooks/xxxxx'
headers={"Content-Type": "application/json"}
requests.post(url, data=json.dumps(data), headers=headers)
What's the status code you get back from the POST? That could be a clue where it's going awry.
Related
I'm programing in Python some API application, using POSTMAN, and a Bearer token. I already receive the token, and to some GET with success response.
But when doing a insert of a record I got 400 Bad request error, this is the code I'm using for adding the record
def add_identity(token, accountid, newIdentity):
end_point = f"https://identityservice-demo.clearid.io/api/v2/accounts/{accountid}/identities/"
headers = CaseInsensitiveDict()
headers["Content-type"] = "application/json; charset=utf-8"
headers["Authorization"] = f"Bearer {token}"
response = requests.request("POST", end_point, data=newIdentity, headers=headers)
print(f"{response.reason} - {response.status_code}")
the variable newIdentity has the following data
nID = {
"privateData": {
"birthday": "1985-30-11T18:23:27.955Z",
"employeeNumber": "99999999",
"secondaryEmail": "",
"cityOfResidence": "Wakanda",
"stateOfResidence": "Florida",
"zipCode": "102837",
"phoneNumberPrimary": "(999)-999-999)",
"phoneNumberSecondary": "+5-(999)-999-9999"
},
"companyData": {
"approvers": [
{
"approverId": ""
}
],
"supervisorName": "Roger Rabbit",
"departmentName": "Presidency",
"jobTitle": "President",
"siteId": "string",
"companyName": "ACME Inc",
"workerTypeDescription": "",
"workerTypeCode": ""
},
"systemData": {
"hasExtendedTime": "true",
"activationDateUtc": "2022-03-16T18:23:27.955Z",
"expirationDateUtc": "2022-03-16T18:23:27.955Z",
"externalId": "999999",
"externalSyncTimeUtc": "2022-03-16T18:23:27.955Z",
"provisioningAttributes": [
{
"name": ""
}
],
"customFields": [
{
"customFieldType": "string",
"customFieldName": "SSNO",
"customFieldValue": "9999999"
}
]
},
"nationalIdentities": [
{
"nationalIdentityNumber": "0914356777",
"name": "Passport",
"issuer": "Wakanda"
}
],
"description": "1st Record ever",
"status": "Active",
"firstName": "Bruce",
"lastName": "Wayne",
"middleName": "Covid",
"displayName": "Bruce Wayne",
"countryCode": "WK",
"email": "bruce.wayne#wakanda.com",
"creationOnBehalf": "ACME"
}
what could solve the problem?
the swagger for the API is
https://identityservice-demo.clearid.io/swagger/index.html#/Identities/get_api_v2_accounts__accountId__identities
Thanks for your help in advance
data have to be a dict ,, you can try import json and data=json.dumps(newIdentity) ,
and if it keeps returning 400 , check well that all the parameters are accepted by the api by recreating the request with Postman or any request editor, and if the api uses any web interface check what is the reason for that 400 . This was translated by Google so I don't know if I said something nonsense :)
I am having trouble with sending a JSON response from my python3.8 lambda function (default lambda_handler function). I am pretty sure I understand what I am doing after reading most of the docs and the Lambda Function Input Event and Response Format. from that resource, it says the only required section is the 'dialogAction' section.
Right now, my lex-bot has 1 intent and one slot. I know that this works because when I add a logger to the code, I can see that my lambda function is recieving confirmed JSON format.
My code tries to send a final response from the lambda function, but when I run the lex-bot in the console I get the following error:
Invalid Lambda Response: Received invalid response from Lambda: Can not construct instance of IntentResponse, problem: The validated object is null at [Source: {"dialogAction": {"type": "Close", "fulfillmentState": "Fulfilled", "message": {"contentType": "PlainText", "content": "milk"}}}; line: 1, column: 128]
Here is my python code:
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def lambda_handler(event, context):
# print
item = event["sessionState"]["intent"]["slots"]["MilkProduct"]["value"]["resolvedValues"][0]
logger.debug(item)
return{
"dialogAction": {
"type": "Close",
"fulfillmentState": "Fulfilled",
"message": {
"contentType": "PlainText",
"content": item
}
}
}
I do not think this is necessary for you to see, but here is what the lex-bot is sending me after it confirms the slot for the intent has been confirmed:
{
"sessionId": "120304235774457",
"inputTranscript": "I want to buy milk",
"interpretations": [
{
"intent": {
"slots": {
"MilkProduct": {
"shape": "Scalar",
"value": {
"originalValue": "milk",
"resolvedValues": [
"milk"
],
"interpretedValue": "milk"
}
}
},
"confirmationState": "None",
"name": "BuyCream",
"state": "ReadyForFulfillment"
},
"nluConfidence": 1
},
{
"intent": {
"slots": {},
"confirmationState": "None",
"name": "FallbackIntent",
"state": "ReadyForFulfillment"
}
}
],
"responseContentType": "text/plain; charset=utf-8",
"invocationSource": "FulfillmentCodeHook",
"messageVersion": "1.0",
"sessionState": {
"intent": {
"slots": {
"MilkProduct": {
"shape": "Scalar",
"value": {
"originalValue": "milk",
"resolvedValues": [
"milk"
],
"interpretedValue": "milk"
}
}
},
"confirmationState": "None",
"name": "BuyCream",
"state": "ReadyForFulfillment"
},
"originatingRequestId": "417dff57-5260-45cc-81a7-06df13fbee9a"
},
"inputMode": "Text",
"bot": {
"aliasId": "TSTALIASID",
"aliasName": "TestBotAlias",
"name": "Shopping",
"version": "DRAFT",
"localeId": "en_US",
"id": "JTGNDOEVQG"
}
}
Can someone please tell me what I am doing wrong? I have been at this for hours and I seriously do not know what I am doing wrong.
Thanks
I am having a problem with getting the correct sort order of a .json file that gets created from an api response using PyCharm Community Edition with python 3.7.
This is the api request:
import requests
import json
url = "https://pokemon-go1.p.rapidapi.com/pokemon_names.json"
headers = {
'x-rapidapi-key': "c061ae2dffmshc2a33d10b00cee7p121f42jsn11f39d53dd1e",
'x-rapidapi-host': "pokemon-go1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
If i now print(response.text), I get the following output: (That's how I want my .json file to look like later)
{
"1": {
"id": 1,
"name": "Bulbasaur"
},
"2": {
"id": 2,
"name": "Ivysaur"
},
"3": {
"id": 3,
"name": "Venusaur"
},
"4": {
"id": 4,
"name": "Charmander"
},
"5": {
"id": 5,
"name": "Charmeleon"
}
}
After that I write the response to the file "pokemondata.json" by doing this:
response_json = json.loads(response.text)
writeFile = open("pokemondata.json", "w")
writeFile.write(json.dumps(response_json, indent=4, sort_keys=True))
writeFile.close()
And then the file looks like this:
{
"1": {
"id": 1,
"name": "Bulbasaur"
},
"10": {
"id": 10,
"name": "Caterpie"
},
"100": {
"id": 100,
"name": "Voltorb"
},
"101": {
"id": 101,
"name": "Electrode"
},
"102": {
"id": 102,
"name": "Exeggcute"
}
}
I could not figure out how to get it done so that the file is sorted by ids (or the numbers before the id, e.g. "1") correctly. Could anybody please explain to me, how I can fix it?
import requests
import json
url = "https://pokemon-go1.p.rapidapi.com/pokemon_names.json"
headers = {
'x-rapidapi-key': "c061ae2dffmshc2a33d10b00cee7p121f42jsn11f39d53dd1e",
'x-rapidapi-host': "pokemon-go1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
response_json = response.json()
int_keys = {int(k):v for k,v in response_json.items()}
with open("sample.json", 'w') as file_obj:
json.dump(int_keys, file_obj, indent=4, sort_keys=True)
Issue is with keys in your json which are in string format. Convert them to integers and save in the file
I'm trying to specify data formats and HTTP headers to ensure valid requests are submitted to the Kafka Bridge using Strimzi Kafka.
Message format
When sending messages using the /topics endpoint, you enter the message payload in the request body, in the records parameter.
The records parameter can contain any of these optional fields:
Message headers
Message key
Message value
**Sample code in Python **
import requests
headers = {'content-type': 'application/vnd.kafka.json.v2+json', }
data = '{ "records": [ { "key": "key-1", "value": "value-1" }, { "key": "key-2",
"value": "value-2" } ] }'
response =
requests.post('http://localhost:54304/topics/my-topic',
headers=headers, data=data)
So I need to modified the sample JSON API payload so that it matches the data format in the request body where data = '{....}'.
Sample JSON API: http://api.open-notify.org/astros.json
Output
{
"message": "success",
"number": 11,
"people": [
{
"name": "Mike Hopkins",
"craft": "ISS"
},
{
"name": "Victor Glover",
"craft": "ISS"
},
{
"name": "Shannon Walker",
"craft": "ISS"
},
{
"name": "Soichi Noguchi",
"craft": "ISS"
},
{
"name": "Mark Vande Hei",
"craft": "ISS"
},
{
"name": "Oleg Novitskiy",
"craft": "ISS"
},
{
"name": "Pyotr Dubrov",
"craft": "ISS"
},
{
"name": "Thomas Pesquet",
"craft": "ISS"
},
{
"name": "Megan McArthur",
"craft": "ISS"
},
{
"name": "Shane Kimbrough",
"craft": "ISS"
},
{
"name": "Akihiko Hoshide",
"craft": "ISS"
}
]
}
Please how do I format the JSON payload into a data structure for producing messages?
I'm trying to write a typeform bot but I am a totally beginner so I have problems with request.post
I am trying to fill this typeform: https://typeformtutorial.typeform.com/to/aA7Vx9
by this code
import requests
token = requests.get("https://typeformtutorial.typeform.com/app/form/result/token/aA7Vx9/default")
data = {"42758279": "true",
"42758410": "text",
"token": token}
r = requests.post("https://typeformtutorial.typeform.com/app/form/submit/aA7Vx9", data)
print(r)
I think that something is wrong with "data" and I am not sure if I use token in a good way. Could you help me?
So, first of all, you need to get another field with the token. To do that, you should pass the header 'accept': 'application/json' in your first request. In the response, you'll get the json object with the token and landed_at parameters. You should use them in the next step.
Then, the post data shoud be different from what you're passing. See the network tab in the browser's developer tools to find out the actual template. It has a structure like that:
{
"signature": <YOUR_SIGNATURE>,
"form_id": "aA7Vx9",
"landed_at": <YOUR_LANDED_AT_TIME>,
"answers": [
{
"field": {
"id": "42758279",
"type": "yes_no"
},
"type": "boolean",
"boolean": True
},
{
"field": {
"id": "42758410",
"type": "short_text"
},
"type": "text",
"text": "1"
}
]
}
And finally, you should convert that json to text so the server would successfully parse it.
Working example:
import requests
import json
token = json.loads(requests.post(
"https://typeformtutorial.typeform.com/app/form/result/token/aA7Vx9/default",
headers={'accept': 'application/json'}
).text)
signature = token['token']
landed_at = int(token['landed_at'])
data = {
"signature": signature,
"form_id": "aA7Vx9",
"landed_at": landed_at,
"answers": [
{
"field": {
"id": "42758279",
"type": "yes_no"
},
"type": "boolean",
"boolean": True
},
{
"field": {
"id": "42758410",
"type": "short_text"
},
"type": "text",
"text": "1"
}
]
}
json_data = json.dumps(data)
r = requests.post("https://typeformtutorial.typeform.com/app/form/submit/aA7Vx9", data=json_data)
print(r.text)
Output:
{"message":"success"}