I am trying to create a post request to send a message on the site. But for some reason it doesn't work. I am on the right page, but for some reason the message is still not being sent
print(f'{login}', lastChat['userSms'])
Jurl = 'https://funpay.com/chat/?node=userId'
seska = session.get(Jurl )
soup = BeautifulSoup(seska.text, 'lxml')
tag1 = soup.find('div', id='live-counters').get('data-orders')
tag3 = soup.find('div', class_='chat chat-float').get('data-bookmarks-tag')
tag2 = soup.find("div", class_='chat chat-float').get('data-tag')
tag4 = soup.find('div', class_='param-item chat-panel hidden').get('data-tag')
session.get(Jurl)
dataMes = soup.findAll('div', class_='message')
print(dataMes[-1])
objects = '[{"type":"orders_counters","id":"5214431","tag":"' + tag1 + '","data":false},' \
'{"type":"chat_node","id":"users-5054677-5214431","tag":"' + tag2 + '",' \
'"data":{"node":"users-5054677-5214431","last_message":' + lastMes + ',"content":"s"}},' \
'{"type":"chat_bookmarks","id":"5214431","tag":"' + tag3 + '","data":false},' \
'{"type":"c-p-u","id":"5054677","tag":"' + tag4 + '","data":false}]'
request = '{"action":"chat_message",' \
'"data":{"node":"users-5054677-5214431",' \
'"last_message":' + lastMes + ',"content":"s"}}'
datas = {
"objects": objects,
"request": request,
"csrf_token": csrf
}
print(datas)
session.post(Jurl, data=datas)
Creating the JSON with concatenated strings is error-prone and most likely it is failing because the JSON won't parse.
For example, if variable lastMes is a string value then it must be quoted.
request = '{"action":"chat_message",' \
'"data":{"node":"users-5054677-5214431",' \
'"last_message":"' + lastMes + '","content":"s"}}'
# ^ ^
Safer to create a dictionary of the values then use json.dumps() to convert the objects to correctly formatted JSON.
import json
tag1 = tag2 = tag3 = tag4 = lastMes = "XXX"
csrf = "csrf"
objects = [{"type": "orders_counters", "id": "5214431", "tag": tag1, "data": False},
{"type": "chat_node", "id": "users-5054677-5214431", "tag": tag2,
"data": {"node": "users-5054677-5214431",
"last_message": lastMes, "content": "s"}},
{"type": "chat_bookmarks", "id": "5214431", "tag": tag3, "data": False},
{"type": "c-p-u", "id": "5054677", "tag": tag4, "data": False}]
request = {"action": "chat_message",
"data": {"node": "users-5054677-5214431",
"last_message": lastMes,
"content": "s"}}
datas = {
"objects": json.dumps(objects),
"request": json.dumps(request),
"csrf_token": csrf
}
Then make the HTTP POST and check r.status_code.
r = session.post(Jurl, data=datas)
print(r.status_code)
However, if the web service requires a JSON payload (with Content-type header=application/json) not form-encoded data then you need to use the json= parameter.
datas = {
"objects": objects,
"request": request,
"csrf_token": csrf
}
r = session.post(Jurl, json=datas)
Related
I keep receiving key error 'Notes'. Notes is in a nested response. How do I solve this? I have included a sample of the json.
Traceback added by request.
Traceback (most recent call last):
File "/Users/xxxxxx/Documents/code/trade show w notes", line 16, in <module>
target = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (contact["company_name"], contact["location"], contact["summary"], contact["job_title"], contact["name"], contact["job_industry"], contact["email"], contact["first_name"], contact["last_name"], contact["notes"])
KeyError: 'notes'
\
"data": [
{
"team_id": 53806,
"name": "Nicholas Bancroft Cooke",
"first_name": "Nicholas",
],
"email": null,
"metadata": null,
"qualification": [
{
"qualification_id": 17573056,
"qualification": "connected",
"notes": null,
\\
page = 1
url = "https://teams-api.grip.events/1/team/53806/event/123721/member/236388/contact/inbound_lead/reviewed?page=1"
headers = {
'authorization': 'Bearer eaf3bd4b-6861-4ca2-a86e-3a96c73deac0',
}
data = ["company_name", "job_title", "name", "job_industry", "summary", "notes", "location", "first_name", "last_name", "email"]
with open("list31.txt", "w", encoding='utf-8') as f: #added " encoding='utf-8' "
for page in range(1, 1000):
response = requests.get(url=url, headers=headers).json()
contacts = response["data"]
for contact in contacts:
target = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" % (contact["company_name"], contact["location"], contact["summary"], contact["job_title"], contact["name"], contact["job_industry"], contact["email"], contact["first_name"], contact["last_name"], contact["notes"])
f.write(target + "\n")
print(target)
If you are referring to the notes key which is under qualification.
Then it should be: contact["qualification"][0]["notes"]
Here contact["qualification"] is a list. if by any chance contact["qualification"] is an empty list it will raise an IndexError. you need to handle it with a try-catch or if-clause
import requests, json, time
url = 'https://api.kucoin.com/api/v1/orders'
headers = {
"KC-API-KEY": '',
"KC-API-PASSPHRASE": '',
"clientOid": "AAA",
"side": "sell",
"symbol": "BTC-USDT",
"type": "market",
"size": "0.001",
}
response = requests.post(url, headers=headers)
print(response.status_code)
print(response.json())
I am trying to place an order but it isn't working. Am I missing some parameters?
Error:
{'code': '400001', 'msg': 'Please check the header of your request for KC-API-KEY, KC-API-SIGN, KC-API-TIMESTAMP, KC-API-PASSPHRASE'}
According to the official docs, all private request must contain the following headers:
KC-API-KEY
KC-API-SIGN
KC-API-TIMESTAMP
KC-API-PASSPHRASE
KC-API-VERSION
Here is an example of the endpoint to place a order limit:
import base64, hmac, hashlib, json
# constants
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
API_PASSPHRASE = "YOUR_API_PASSPHRASE"
url = "https://api.kucoin.com/api/v1/orders"
now = int(time.time() * 1000)
data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}
data_json = json.dumps(data)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json
signature = base64.b64encode(hmac.new(API_SECRET.encode(
'utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(API_SECRET.encode(
'utf-8'), API_PASSPHRASE.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": API_KEY,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
try:
res = requests.post(
url, headers=headers, data=data_json).json()
print(res)
except Exception as err:
print(err)
Hope it will help.
Did you consider using wrapped library like Python-kucoin ?
https://python-kucoin.readthedocs.io/en/stable/index.html
it is really great and will definitely help you. Have a look to the documentation
from kucoin.client import Client
api_key = '<api_key>'
api_secret = '<api_secret>'
api_passphrase = '<api_passphrase>'
client = Client(api_key, api_secret, api_passphrase)
# place a market buy order
order = client.create_market_order('BTC-USDT', Client.SIDE_BUY, size=0.001)
try removing the spaces from :
data = {"clientOid": "AAA", "side": "sell", "symbol": "BTC-USDT", "type": "market", "size": "0.001"}
I have been trying to find an answer that work on my case but had no success.
I am getting a response 422 when running the code below. I have replaced the json in the response variable and also used json.dumps around the data variable but I am still getting this response. Would you be able to find the issue within my json file? Thanks a lot
todaystr = datetime.today().strftime('%Y-%m-%d')
today = datetime.strptime(todaystr, '%Y-%m-%d')
first_day_of_month = today.replace(day=1)
day_count_str = today - first_day_of_month
day_count_int = day_count_str / timedelta(days=1)
day_count_split = str(day_count_int)
sep = '.'
day_count = day_count_split.split(sep, 1)[0]
dt = str(first_day_of_month.timestamp())
data = {"requestId": "numberOfUniqueAccountsAndVisitors", "timeSeries": {"period": "dayRange", "count": day_count, "first": dt}, "source": {"events": None}, "pipeline": [{"reduce": [{"reduce": {"visitors": {"count": "visitorId"}, "accounts": {"count": "accountId"}}}]}]}
headers = {
'x-pendo-integration-key': API_Key,
'content-type': "application/json"
}
response = requests.post(url, json=data, headers=headers)
print(response)
response_dictionary = json.loads(response.content)
print(response_dictionary)
In the payload to the Pendo Aggregation API, the request object should not be an array. And make sure the "key" should be named as "request"(singular), not as "requests"(plural).
Try something like this
{
"response": {
"mimeType": "application/json"
},
"request": {
"name": "accounts-last7days",
"requestId": "accounts-last7days"
}
}
I want to create a dictionary with using 2 api. Can you guide me?
I want to create a dictionary with using 2 api. Can you guide me?
url = 'https://test.com/api/v1/'
tags = []
result=[]
response = requests.get(url)
results = json.loads(response.text)
for data in results['results']:
second API
url = 'https://test.com/api/v1/'+data['tags_id']
response = requests.get(url)
results = json.loads(response.text)
for data in results['tags']:
tags.append(data['title'])
result of first api
results: [
{
"title": "subject1",
"tags_id": "86111ae6",
},
{
"title": "subject2",
"tags_id": "86ae6",
}]
expected result
results: [
{
"title": "subject1",
"tags: ['a','b'],
},
{
"title": "subject2",
"tags": ['c','d','f'],
}]
second API
"tags": [
{
"title": 'a',
},
{
"title": 'b',
},
]
Since each "title" from the first API has exactly one "tags_id", I think what you want is something like:
url = 'https://test.com/api/v1/'
response = requests.get(url)
results = json.loads(response.text)
output = list()
for d in results['results']:
response = requests.get(f'https://test.com/api/v1/{d["tags_id"]}/show_tags')
result = json.loads(response.text)
output.append({"title": d["title"],
"tags": [t["title"] for t in result["tags"]]})
We have Json Data which i'm trying to parse, While reading the data via url with json & resquest.
Sample Jason Data:
{"statusMessage": "OK", "statusCode": 200, "response": { "id": "15015", "name": "cDOT_stx7116_esx01_07-18-2021_18.00.00.0586", "startTime": 1626624000472, "mounted": false, "vmwareSnapshot": "Yes", "status": "Completed", "policy": "SCV_DLY_NoDR", "entities": [ { "entityName": "CISCAT-2016_CN-SKK", "quiesced": true, "uuid": "500334f5-fea6-2992-a543-e4bd56822913", "locations": [ "[std7116_esx01] CISCAT-2016_CN-SKK/CISCAT-2016_.vmtx" ] }, { "entityName": "ind4481", "quiesced": true, "uuid": "500ae9dd-60e7-2339-4c4c-557ba00a3696", "locations": [ "[stx7116_esx01] ind4481/ind4481.vmx" ] }}
What I tried:
response = requests.get('https://str001.example.com:8144/api/4.1/backups/'+y1, headers=headers, verify =False)
output = response.json()
data4 = output['response']['entities']
Below is what i'm trying to do with a For loop and trying to get the desired index but it did not worked:
for k in data4:
x1 = (k['locations'].rsplit("]", 3)[-3].split("[")[-1],k['entityName'],k['quiesced'])
print (x1)
Desired output
stx7116_esx01 CISCAT-2016_CN-SKK true
If the json object that you have provided is exact then you might try:
locations = []
for i in range(0,len(data4),1):
data_dict = data4[i] # each element is a separate dictionary
location = data_dict['locations'][0] # as locations is a list with a sngle item you'll have to extract it this way
location = location[location.find('[') + 1 : location.finct(']')] # slice the string on range of the indexes of '[' and ']'
desired_output = location + ' ' + data_dict['entityName'] + ' ' + data_dict['quiesced']